Flutter中如何保持BottomNavigationBar切换页面后状态

Flutter中 BottomNavigationBar 开发底部导航很方便,
但是初次使用时会发现,切换页面后,状态恢复了,如何保持。

参考:https://www.cnblogs.com/hupo376787/p/10624636.html

关键点:使用IndexedStack

 //body: _children[_currentIndex],
      body: IndexedStack(
        index: _currentIndex,
        children: _children,
      )
import 'package:flutter/material.dart';

import './pages/home_page.dart';
import './pages/book_page.dart';
import 'package:bottom_nav_bar_test/pages/movie_page.dart';
import 'package:bottom_nav_bar_test/pages/music_page.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bottom Navigation',
      home: Main(),
      theme: ThemeData(primaryColor: Colors.orange),
    );
  }
}

class Main extends StatefulWidget {
  @override
  _MainState createState() => _MainState();
}

class _MainState extends State<Main> {
  int _currentIndex = 0;
  final List<Widget> _children = [Home(), Book(), Music(), Movie()];

  final List<BottomNavigationBarItem> _list = <BottomNavigationBarItem>[
    BottomNavigationBarItem(
        icon: Icon(Icons.home),
        title: Text('Home'),
        //backgroundColor: Colors.orange
        ),
    BottomNavigationBarItem(
        icon: Icon(Icons.book),
        title: Text('Book'),
        //backgroundColor: Colors.orange
        ),
    BottomNavigationBarItem(
        icon: Icon(Icons.music_video),
        title: Text('Music'),
        //backgroundColor: Colors.orange
        ),
    BottomNavigationBarItem(
        icon: Icon(Icons.movie),
        title: Text('Movie'),
        //backgroundColor: Colors.orange
        ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Navigation'),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        items: _list,
      ),
      //body: _children[_currentIndex],
      body: IndexedStack(
        index: _currentIndex,
        children: _children,
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容