Flutter:使用IndexedStack重新构建小部件?

smdncfj3  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(239)

我知道IndexedStack的目的是一次显示缓存中的一个小部件,以防止小部件被重新构建。
但在某些情况下,必须更新小部件中的数据。
现在考虑下面的代码示例,假设我希望在点击Increment选项卡时重新生成第1页(即:每当我从“递减”选项卡切换到“递增”选项卡时):
home.dart

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Widget> pages = [Page1(), Page2()];
  int selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Save Page State'),
      ),  

      body: IndexedStack(
        index: selectedIndex,
        children: pages,
      ),

      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.plus_one_outlined),
            label: 'Increment',
          ),  
          BottomNavigationBarItem(
            icon: Icon(Icons.exposure_minus_1_outlined),
            label: 'Decrement',
          ),  
        ],  
        currentIndex: selectedIndex,
        onTap: (index){
            setState(() {
                selectedIndex = index;
            }); 
        },  
      ),  
    );  
  }
}

page1.dart

class Page1 extends StatefulWidget {
  @override
  _Page1State createState() => _Page1State();

}

class _Page1State extends State<Page1> {
  int count = 0;

  @override
  Widget build(BuildContext context) {

    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        Center(
          child: Text(
            '$count',
            style: Theme.of(context).textTheme.headline2,
          ),  
        ),  
        ElevatedButton(
          onPressed: () {
            setState(() {
              count++;
            }); 
          },  
          child: Text('Increment'),
        )   
      ],  
    );  
  }
}

page2.dart

class Page2 extends StatefulWidget {
  @override
  _Page2State createState() => _Page2State(); 
} 

class _Page2State extends State<Page2> {
  int count = 0;               

  @override
  Widget build(BuildContext context) {
    return Column(             
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [              
        Center(
          child: Text(
            '$count',          
            style: Theme.of(context).textTheme.headline2,
          ),                   
        ),                     
        ElevatedButton(        
          onPressed: () {      
            setState(() {      
              count--;
            });
          },
          child: Text('Decrement'),
        )
      ],
    );
  }
}

我该怎么做?
我尝试从列表中删除Page1小部件,然后使用removeAtinsert再次添加它,但它不起作用。
有什么想法?

gpnt7bae

gpnt7bae1#

从列表中删除小部件,然后使用removeAt再次添加它,insert最终完成了任务,但必须沿着使用UniqueKey来强制小部件生命周期重新开始。

// page1.dart
class Page1 extends StatefulWidget {
 Page1({ Key? key }) : super(key: key); // <= Add key

 @override
 _Page1State createState() => _Page1State();

}

class _Page1State extends State<Page1> {
  int count = 0;

  @override
  Widget build(BuildContext context) {

return Column(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: [
    Center(
      child: Text(
        '$count',
        style: Theme.of(context).textTheme.headline2,
      ),  
    ),  
    ElevatedButton(
      onPressed: () {
        setState(() {
          count++;
        }); 
      },  
      child: Text('Increment'),
    )   
  ],  
);  
}
}

// home.dart
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Widget> pages = [Page1(), Page2()];
  int selectedIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Save Page State'),
      ),  

      body: body(selectedIndex),

      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.plus_one_outlined),
            label: 'Increment',
          ),  
          BottomNavigationBarItem(
            icon: Icon(Icons.exposure_minus_1_outlined),
            label: 'Decrement',
          ),  
        ],  
        currentIndex: selectedIndex,
        onTap: (index){
            setState(() {
                selectedIndex = index;
            }); 
        },  
      ),  
    );  
  }

  body(selectedIndex) {
      // Check for Page1.
      if (selectedIndex == 0) {
          pages.removeAt(0);
          // Pass a UniqueKey as key to force the widget lifecycle to start over.
          pages.insert(0, new Page1(key: UniqueKey()));
      }   

      return IndexedStack(
        index: selectedIndex,
        children: pages,
      );  
  }
}

相关问题