如何在使用底部导航栏时保留选项卡



每当我从选项卡 1 切换到选项卡 2 然后切换回选项卡 1 时,都会重建选项卡 1 上的内容。无论如何要防止这种情况?

class BottomNavBarExample extends StatefulWidget {
  @override
  BottomNavBarExampleState createState() {
    return new BottomNavBarExampleState();
  }
}
class BottomNavBarExampleState extends State<BottomNavBarExample> {
  List<BottomNavigationBarItem> _tabs = [
    BottomNavigationBarItem(
        icon: Icon(Icons.library_books), title: Text('Library')),
    BottomNavigationBarItem(icon: Icon(Icons.public), title: Text('Public')),
    BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('Account')),
  ];
  var _currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Demo')),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: this._currentIndex,
        items: this._tabs,
        onTap: (value) {
          setState(() {
            this._currentIndex = value;
          });
        },
      ),
      body: Stack(children: [
        new Offstage(
          offstage: this._currentIndex != 0,
          child: new TickerMode(
            enabled: this._currentIndex == 0,
            child: LibraryPage(),
          ),
        ),
        new Offstage(
          offstage: this._currentIndex != 1,
          child: new TickerMode(
            enabled: this._currentIndex == 1,
            child: GalleryPage(),
          ),
        ),
        new Offstage(
          offstage: this._currentIndex != 2,
          child: new TickerMode(
            enabled: this._currentIndex == 2,
            child: AccountPage(),
          ),
        ),
      ]),
    );
  }
}

然后,对于每个页面,包括AutomaticKeepAliveClientMixin

最新更新