AutomaticKeepAliveClientMixin在BottomNavigationBar页面中不起作用。
创始人
2024-09-23 18:30:22
0

要解决AutomaticKeepAliveClientMixin在BottomNavigationBar页面中不起作用的问题,可以考虑使用AutomaticKeepAliveClientMixin的子类KeepAliveWidget来包装BottomNavigationBar。以下是一个示例代码:

import 'package:flutter/material.dart';

class MyBottomNavigationBar extends StatefulWidget {
  @override
  _MyBottomNavigationBarState createState() => _MyBottomNavigationBarState();
}

class _MyBottomNavigationBarState extends State with AutomaticKeepAliveClientMixin{
  int _currentIndex = 0;

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context); // 这一行很重要,必须调用父类的build方法

    return Scaffold(
      body: _getPageByIndex(_currentIndex),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (int index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('首页'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            title: Text('设置'),
          ),
        ],
      ),
    );
  }

  Widget _getPageByIndex(int index) {
    switch (index) {
      case 0:
        return HomeScreen();
      case 1:
        return SettingsScreen();
      default:
        return HomeScreen();
    }
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('首页'),
    );
  }
}

class SettingsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('设置'),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: MyBottomNavigationBar(),
  ));
}

在这个示例中,通过在MyBottomNavigationBar的状态类中混合AutomaticKeepAliveClientMixin,并重写wantKeepAlive方法来实现自动保持页面状态。同时,还需要在build方法中调用super.build(context)来确保父类的build方法被调用。这样就可以保持BottomNavigationBar中的页面状态了。

相关内容

热门资讯

科技分享!微乐自建房辅助工具脚... 科技分享!微乐自建房辅助工具脚本,微乐家乡麻将自建房辅助app(开挂自建房)脚本微乐家乡麻将自建房辅...
普及知识!微信雀神麻将挂件开挂... 普及知识!微信雀神麻将挂件开挂辅助,微乐自建房脚本免费入口(开挂自建房)插件1、操作简单,无需微信雀...
一分钟揭秘!微乐家乡麻将自建房... 一分钟揭秘!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)脚本1、打开软件启动之...
热门推荐!微乐家乡麻将自建房辅... 热门推荐!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)攻略1、微乐家乡麻...
发现一款!微乐自建房辅助工具,... 发现一款!微乐自建房辅助工具,微乐小程序免费黑科技(开挂自建房)软件1、全新机制【微乐自建房辅助工具...
揭秘一下!微乐家乡麻将自建房辅... 揭秘一下!微乐家乡麻将自建房辅助app,微乐自建房脚本免费入口(开挂自建房)攻略在进入微乐家乡麻将自...
分享给玩家!微乐自建房辅助工具... 分享给玩家!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)教程1、下载好微乐自建房辅助工具...
实测揭晓!微乐家乡麻将自建房辅... 实测揭晓!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)插件1、进入游戏-...
终于知道!微信卡五星辅助器,微... 终于知道!微信卡五星辅助器,微乐小程序免费黑科技(开挂自建房)插件1、完成微信卡五星辅助器有辅助插件...
今日百科!微乐自建房辅助工具插... 今日百科!微乐自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)工具1、微乐自建房辅助工具插件...