如何保存PageView的索引?

时间:2018-11-23 17:03:52

标签: flutter

我有一个PageView显示4个页面,还有一个BottomNavigationBar来切换它们。我在使用PageController时遇到了麻烦。

在任何页面中,我都导航到一个新的Screen,但是当返回时,PageView返回到初始页面,而没有返回到最后一页。

这是我使用PageView的方式

@override
void initState() {
  super.initState();
  _page = 0;
  _pageController = PageController(keepPage: true);
}

return Scaffold(
  appBar: AppBar(
      title: getAppBarTitle(_page),
      centerTitle: true,
      actions: renderActions(_page)),
  body: PageView(
      children: <Widget>[
        DashboardScreen(),
        InstructionsScreen(),
        CatalogScreen(),
        ProfileScreen()
      ],
      controller: _pageController,
      onPageChanged: onPageChanged,
      physics: NeverScrollableScrollPhysics()),
  bottomNavigationBar: BottomNavigationBar(
    key: bottomNavigationBar,
    type: BottomNavigationBarType.shifting,
    onTap: navigationTapped,
    currentIndex: _page,
    items: [
      BottomNavigationBarItem(
          icon: Icon(Icons.home, color: Colors.grey),
          activeIcon:
              Icon(Icons.home, color: Theme.of(context).primaryColor),
          title: Text('Dashboard',
              style: TextStyle(color: Theme.of(context).primaryColor)),
          backgroundColor: Colors.white),
      BottomNavigationBarItem(
          icon: Icon(Icons.receipt, color: Colors.grey),
          activeIcon:
              Icon(Icons.receipt, color: Theme.of(context).primaryColor),
          title: Text('Instructions',
              style: TextStyle(color: Theme.of(context).primaryColor)),
          backgroundColor: Colors.white),
      BottomNavigationBarItem(
          icon: Icon(Icons.dashboard, color: Colors.grey),
          activeIcon:
              Icon(Icons.dashboard, color: Theme.of(context).primaryColor),
          title: Text('Catalog',
              style: TextStyle(color: Theme.of(context).primaryColor)),
          backgroundColor: Colors.white),
      BottomNavigationBarItem(
          icon: Icon(Icons.person, color: Colors.grey),
          activeIcon:
              Icon(Icons.person, color: Theme.of(context).primaryColor),
          title: Text('Profile',
              style: TextStyle(color: Theme.of(context).primaryColor)),
          backgroundColor: Colors.white)
    ],
  ),
);

void navigationTapped(int page) {
  _pageController.animateToPage(page,
    duration: const Duration(milliseconds: 300), curve: Curves.ease);
}

void onPageChanged(int page) {
  setState(() {
    this._page = page;
  });
}

例如在DashboardScreen中,我转到一个新页面,如:

Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => CodeScreen()))

我该如何解决?我需要使用Redux还是Bloc来实现这一目标?

谢谢。

0 个答案:

没有答案