美文网首页
Flutter 填坑日记(一)

Flutter 填坑日记(一)

作者: 小西北北 | 来源:发表于2019-08-24 11:57 被阅读0次

    最近在学习flutter过程中遇到了一些问题,归纳一下:
    1、应用首页使用BottomNavigationBar,切换底部标签会重新渲染布局,界面不会保持之前的状态。
    解决方案:Scaffold中body使用IndexedStack,代码如下:

    class _MyHomePageState extends State<MyHomePage> {
    
      _MyHomePageState();
    
      int _selectedIndex = 0;
    
      var _pageController = PageController(initialPage: 0);
    
      final _pages = <Widget>[
        FirstPage(),
        SecondPage(),
        ThirdPage(),
        ForthPage(),
        FivePage(),
      ];
    
      var titles = <String>[
        '首页',
        '支部',
        '待办',
        '党务',
        '我的',
      ];
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
      }
    
      @override
      void dispose() {
        // TODO: implement dispose
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(titles[_selectedIndex]),
          ),
          body: IndexedStack(
            index: _selectedIndex,
            children: _pages,
          ),
          bottomNavigationBar: BottomNavigationBar(
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                  icon: Icon(Icons.home), title: Text(titles[0])),
              BottomNavigationBarItem(
                  icon: Icon(Icons.device_hub), title: Text(titles[1])),
              BottomNavigationBarItem(
                  icon: Icon(Icons.assignment), title: Text(titles[2])),
              BottomNavigationBarItem(
                  icon: Icon(Icons.work), title: Text(titles[3])),
              BottomNavigationBarItem(
                  icon: Icon(Icons.people), title: Text(titles[4])),
            ],
            currentIndex: _selectedIndex,
            type: BottomNavigationBarType.fixed,
            fixedColor: Colors.red,
            onTap: _onItemTapped,
          ),
        );
      }
    
      void _onItemTapped(int index) {
        //bottomNavigationBar 和 PageView 关联
        setState(() {
          _selectedIndex = index;
        });
        _pageController.animateToPage(index,
            duration: const Duration(milliseconds: 300), curve: Curves.ease);
      }
    

    2、布局使用TabController时也会出现如1的问题,界面会重置。这种情况只需要在子界面加上AutomaticKeepAliveClientMixin,然后重写wantKeepAlive即可,代码如下:

    class _NewsPageState extends State<NewsPage> with AutomaticKeepAliveClientMixin {
    
      @override
      bool get wantKeepAlive => true;
    }
    

    需要注意的是,这种方法对BottomNavigationBar无效。

    相关文章

      网友评论

          本文标题:Flutter 填坑日记(一)

          本文链接:https://www.haomeiwen.com/subject/knwfectx.html