Flutter BottomNavigationBar切換頁面被重置問題(保存狀態(tài))

開始嘗試用flutter開發(fā),flutter版本1.0,寫類似微信底部tab切換界面時(shí)發(fā)現(xiàn)界面老被重置,網(wǎng)上找了一圈說保持狀態(tài)需要子頁面mixin AutomaticKeepAliveClientMixin,然后重寫

 @override
  bool get wantKeepAlive => true; 

但發(fā)現(xiàn)需要配合其他組件,不是隨便mixin就有用的,嘗試幾種寫法總結(jié)BottomNavigationBar+List<Widget>+AutomaticKeepAliveClientMixin是沒有用的

  1. 首先嘗試BottomNavigationBar+List<Widget>實(shí)現(xiàn)的頁面切換保持狀態(tài),一般剛開始學(xué)都會(huì)這么寫:
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
        title: "demo",
        home: MainPage(),
      );
}

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MainPageState();
}

class MainPageState extends State<MainPage> {
  int _currentIndex;
  List<Widget> _pages;

  @override
  void initState() {
    super.initState();
    _currentIndex = 0;
    _pages = List()..add(FirstPage("第一頁"))..add(SecondPage("第二頁"))..add(ThirdPage("第三頁"));
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        body: _pages[_currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          items: getItems(),
          currentIndex: _currentIndex,
          onTap: onTap,
        ),
      );

  List<BottomNavigationBarItem> getItems() {
    return [
      BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Home")),
      BottomNavigationBarItem(icon: Icon(Icons.adb), title: Text("Adb")),
      BottomNavigationBarItem(icon: Icon(Icons.person), title: Text("Person"))
    ];
  }

  void onTap(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

子頁面代碼,三個(gè)界面一樣:

class FirstPage extends StatefulWidget {
  String _title;

  FirstPage(this._title);

  @override
  State<StatefulWidget> createState() => FirstPageState();
}

class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin{
  int _count = 0;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget._title),
      ),
      body: Center(
        child: Text(widget._title + ":點(diǎn)一下加1:$_count"),
      ),
      floatingActionButton: FloatingActionButton(
          heroTag: widget._title, child: Icon(Icons.add), onPressed: add),
    );
  }

  void add() {
    setState(() {
      _count++;
    });
  }
}

結(jié)果無法實(shí)現(xiàn)保持頁面

第一個(gè).2019-01-28 02_41_56.gif

2.第二種BottomNavigationBar+PageView,與android的ViewPager類似,界面小改動(dòng)一下,添加一個(gè)按鈕,點(diǎn)擊跳轉(zhuǎn)到一個(gè)新的界面


1548613610101.png

代碼如下:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
        title: "demo",
        home: MainPage(),
      );
}

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MainPageState();
}

class MainPageState extends State<MainPage> {
  int _currentIndex;
  List<Widget> _pages;
  PageController _controller;

  @override
  void initState() {
    super.initState();
    _currentIndex = 0;
    _pages = List() ..add(FirstPage("第一頁"))  ..add(SecondPage("第二頁")) ..add(ThirdPage("第三頁"));
    _controller = PageController(initialPage: 0);
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        body: PageView.builder(
            physics: NeverScrollableScrollPhysics(),//viewPage禁止左右滑動(dòng)
            onPageChanged: _pageChange,
            controller: _controller,
            itemCount: _pages.length,
            itemBuilder: (context, index) => _pages[index]),
        bottomNavigationBar: BottomNavigationBar(
          items: getItems(),
          currentIndex: _currentIndex,
          onTap: onTap,
        ),
      );

  List<BottomNavigationBarItem> getItems() {
    return [
      BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Home")),
      BottomNavigationBarItem(icon: Icon(Icons.adb), title: Text("Adb")),
      BottomNavigationBarItem(icon: Icon(Icons.person), title: Text("Person"))
    ];
  }

  void onTap(int index) {
    _controller.jumpToPage(index);
  }

  void _pageChange(int index) {
     if (index != _currentIndex) {
      setState(() {
        _currentIndex = index;
       });
     }
  }
}

子界面:

class FirstPage extends StatefulWidget {
  String _title;

  FirstPage(this._title);

  @override
  State<StatefulWidget> createState() => FirstPageState();
}

class FirstPageState extends State<FirstPage>
    with AutomaticKeepAliveClientMixin {
  int _count = 0;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget._title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(widget._title + ":點(diǎn)一下加1:$_count"),
            MaterialButton(
                child: Text("跳轉(zhuǎn)"),
                color: Colors.pink,
                onPressed: () => Navigator.push(context,
                    MaterialPageRoute(builder: (context) => NewPage())))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          heroTag: widget._title, child: Icon(Icons.add), onPressed: add),
    );
  }

  void add() {
    setState(() {
      _count++;
    });
  }
}

需要跳轉(zhuǎn)的一個(gè)界面:

class NewPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text("新的界面"),
        ),
        body: Center(
          child: Text("我是一個(gè)新的界面"),
        ),
      );
}
2.2019-01-28 02_40_50.gif

猛一看效果出來了,左右切換界面沒有問題,結(jié)果跳轉(zhuǎn)新界面時(shí)又出現(xiàn)新問題,當(dāng)?shù)谝豁撎D(zhuǎn)新的界面再返回,再切第二、三頁發(fā)現(xiàn)重置了,再切回第一頁發(fā)現(xiàn)頁被重置了。

發(fā)生這種情況需要在重寫Widget build(BuildContext context)時(shí)調(diào)用下父類build(context)方法,局部代碼:

@override
  Widget build(BuildContext context) {
    //在這邊加上super.build(context);
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget._title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(widget._title + ":點(diǎn)一下加1:$_count"),
            MaterialButton(
                child: Text("跳轉(zhuǎn)"),
                color: Colors.pink,
                onPressed: () => Navigator.push(context,
                    MaterialPageRoute(builder: (context) => NewPage())))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          heroTag: widget._title, child: Icon(Icons.add), onPressed: add),
    );
  }
第三個(gè).2019-01-28 02_53_55.gif

這種布局樣式網(wǎng)上還有一種用的比較多的是BottomNavigationBar+IndexedStack( ),這邊就不貼出來了

  • 經(jīng)過長期測試BottomNavigationBar+TabBarView方案行不通,后期會(huì)遇到其他問題,目前最好用還是viewpage和IndexedStack。

最后像這種多頁面使用FloatingActionButton,用它跳轉(zhuǎn)新界面是一定要設(shè)置heroTag,要不然跳轉(zhuǎn)會(huì)黑屏報(bào)錯(cuò)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 7,388評論 0 17
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對...
    cosWriter閱讀 11,685評論 1 32
  • 原文在此,此處只為學(xué)習(xí) Widget與ElementWidget主要接口Stateless WidgetState...
    lltree閱讀 4,631評論 0 1
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,670評論 4 61
  • 寶貝: 今天過的怎么樣,開心嗎? 我今天到山東出差,特別想把最近夢里的感受講給你聽: 一個(gè)人在北京,夢里都孤單,曾...
    楊靜相伴要你好看閱讀 323評論 0 1

友情鏈接更多精彩內(nèi)容