【问题标题】:How can we trigger a stateful widget to rebuild itself with navigation using Bottom Navigation Bar in Flutter?我们如何使用 Flutter 中的底部导航栏触发有状态小部件以通过导航重建自身?
【发布时间】:2020-01-11 20:19:45
【问题描述】:

当我们使用 BottomNavigationBar 导航到 Flutter 中的不同页面时,有状态页面似乎不会自行重建。

这意味着我们不能使用 BottomNavigationBar 触发重建有状态小部件,这与 Drawer 不同。状态保持原样,BottomNavigationBar 在页面上滑动,无助于再次重建整个页面。

int _selectedIndex = 0;
static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
  Page1(),
  Page2(),
  Page3(),
];

void _onItemTapped(int index) {
  setState(() {
    _selectedIndex = index;
  });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: const Text('BottomNavigationBar Sample'),
    ),
    body: _widgetOptions.elementAt(_selectedIndex),
    ),
    bottomNavigationBar: BottomNavigationBar(
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text('Home'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.business),
          title: Text('Business'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.school),
          title: Text('School'),
        ),
      ],
      currentIndex: _selectedIndex,
      selectedItemColor: Colors.amber[800],
      onTap: _onItemTapped,
    ),
  );
}

这里的小部件Page1()Page2()Page3() 是有状态的小部件,当通过底部导航栏导航时,它们似乎不会重建自己。有什么办法可以做到吗?

【问题讨论】:

    标签: flutter dart flutter-layout


    【解决方案1】:

    代替

    static const List<Widget> _widgetOptions = <Widget>[
      Page1(),
      Page2(),
      Page3(),
    ];
    

    使用

    Widget _widgetOptions(int index) {
      switch (index) {
        case 0:
          return Page1();
          break;
        case 1:
          return Page2();
          break;
        case 2:
          return Page3();
          break;
      }
      return Page1();
    }
    

    同时替换

    body: _widgetOptions.elementAt(_selectedIndex),
    

    body: _widgetOptions(_selectedIndex),
    

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多