解决Flutter使用bottomNavigationBar切换时页面初始化的问题

407 阅读1分钟

解决Flutter使用bottomNavigationBar切换时页面初始化的问题

使用IndexedStack索引层叠组件

直接上代码

class _IndexState extends State<IndexPage> {

  int _currentIndex = 0;

  static const List<Widget> _widgetOptions = <Widget>[    HomePage(title: 'Flutter Demo Home Page'),    MyPage()  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: _widgetOptions,
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        unselectedItemColor: Colors.black45,
        selectedItemColor: Theme.of(context).primaryColor,
        showUnselectedLabels: true,
        items: const [
          BottomNavigationBarItem(icon: Icon(IconFont(0xe619)), label: "首页"),
          BottomNavigationBarItem(icon: Icon(IconFont(0xe603)), label: "我的"),
        ],
        currentIndex: _currentIndex,
        onTap: (value) {
          setState(() {
            _currentIndex = value;
          });
        },
      )
    );
  }
}