使用BottomNavigationBar时如何保留选项卡?

时间:2019-01-31 08:28:51

标签: flutter

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

1 个答案:

答案 0 :(得分:0)

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