[flutter] 플러터(IndexedStack)에서 인덱스 변경시 이전 페이지와 새 페이지의 상태를 동시에 관리하는 방법은 무엇인가요?

가장 간단한 방법은 IndexedStack의 children에 StatefulWidget을 사용하는 위젯들을 정의하고, 각 위젯에 상태를 관리하는 메서드를 추가하는 것입니다. 이 메서드는 페이지의 상태가 변경될 때 호출되도록 하면 됩니다.

예를 들어, 두 개의 페이지를 가지고 있는 IndexedStack이 있다고 가정해봅시다. 이전 페이지는 첫 번째 페이지이고, 새 페이지는 두 번째 페이지입니다. 그리고 첫 번째 페이지에는 increment라는 버튼이 있고, 두 번째 페이지에는 decrement라는 버튼이 있습니다. 사용자가 버튼을 누를 때마다 각 페이지의 상태가 변경됩니다.

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  int count = 0;

  void increment() {
    setState(() {
      count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Count: $count'),
            RaisedButton(
              child: Text('Increment'),
              onPressed: increment,
            ),
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  int count = 0;

  void decrement() {
    setState(() {
      count--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Count: $count'),
            RaisedButton(
              child: Text('Decrement'),
              onPressed: decrement,
            ),
          ],
        ),
      ),
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Indexed Stack Demo'),
        ),
        body: IndexedStack(
          index: currentIndex,
          children: [
            FirstPage(),
            SecondPage(),
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: currentIndex,
          onTap: (index) {
            setState(() {
              currentIndex = index;
            });
          },
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('First Page'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.work),
              title: Text('Second Page'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() => runApp(MyApp());

위의 예제 코드에서 IndexedStack의 핵심은 indexchildren입니다. index는 현재 표시 중인 페이지의 인덱스를 나타내며, children은 각 페이지의 StatefulWidget을 포함합니다.

FirstPage와 SecondPage에서는 상태를 관리하기 위해 StatefulWidget을 사용하고, count 값을 업데이트하는 메서드를 제공합니다. 이 메서드는 setState()를 호출하여 변경된 값을 다시 화면에 반영합니다.

전체 앱의 기능은 BottomNavigationBar를 통해 현재 페이지를 변경하면 IndexedStack의 index가 변경됩니다. 이로 인해 현재 표시 중인 페이지가 변경되고, 이전 페이지와 새 페이지의 상태가 동시에 관리됩니다.

위의 예제 코드를 실행해보면, 첫 번째 페이지에서 Increment 버튼을 누르면 count 값이 증가하고, 두 번째 페이지로 이동하면 Decrease 버튼을 눌러 count 값을 감소시킬 수 있습니다. 페이지 간의 상태 전환을 완전히 동기화하기 위해서는 더 많은 로직과 상태를 추가해야 할 수도 있습니다.