如何在 Flutter 中的选项卡(TabBar)之间保持状态?

Hoa*_*yen 4 state-management flutter

我有一个TabBarView3 TabBar。当我在选项卡 1 中时我做了一些事情,然后当我回到选项卡 1 时导航到选项卡 2 我希望选项卡 1 的先前状态不会改变。

我如何在 Flutter 中实现这一点?

下面是我的代码截图

class _LandingPageState extends State<LandingPage> with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;
  PageController pageController;
  TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: 3, vsync: this, initialIndex: 0);
    pageController = PageController(initialPage: 0)
      ..addListener(() {
        setState(() {
          _selectedIndex = pageController.page.floor();
        });
      });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
              bottomNavigationBar: BottomNavigationBar(
              currentIndex: _selectedIndex,
              onTap: (index) {
                setState(() {
                  _selectedIndex = index;
                  tabController.animateTo(index,
                      duration: Duration(microseconds: 300),
                      curve: Curves.bounceIn);
                });
              },
              items: [
                BottomNavigationBarItem(
                    icon: Icon(Icons.assignment), title: Text("Các yêu c?u")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.history), title: Text("L?ch s?")),
                BottomNavigationBarItem(
                    icon: Icon(Icons.person), title: Text("H? s?")),
              ]),
          body: TabBarView(
              controller: tabController,
              children: [
                RequestPage(key: PageStorageKey<String>("request_page"),),
                HistoryPage(key: PageStorageKey<String>("history_page")),
                ProfilePage(key: PageStorageKey<String>("profile_page"))])
          ),
    );
  }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Mig*_*ivo 13

确保您的所有TabBarView孩子都是StatefulWidgets,然后在所有孩子中添加一个AutomaticKeepAliveClientMixin,例如,对于您的RequestPage,它应该如下所示:

class RequestPage extends StatefulWidget {
  RequestPage({Key key}) : super(key: key);

  @override
  _RequestPageState createState() => _RequestPageState();
}

class _RequestPageState extends State<RequestPage> with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return // Your widget tree
  }

  @override
  bool get wantKeepAlive => true;
}
Run Code Online (Sandbox Code Playgroud)

  • 最佳答案!遵循指示并且工作得非常有魅力!使所有 TabBarView 子项 **Stateful**,使所有子项符合 **AutomaticKeepAliveClientMixin** ,覆盖所有子项中的 **wantKeepAlive** ,并在所有子项的 build 方法中调用 **super.build(context)** 。 (4认同)
  • 不,这实际上是最正确的方法之一,这正是因为 `AutomaticKeepAliveClientMixin` 的存在。但是,请记住,“AutomaticKeepAliveClientMixin”只能在 keepAlive 通知程序下工作,例如“TabBarView”、“ListView”等。这些是父部件,它们迭代其子部件并“询问”它们是否应该保持活动状态或回收。如果您在没有任何这些父级的情况下使用“AutomaticKeepAliveClientMixin”,则不会产生任何效果。 (2认同)