Flutter 解决 TabBar导航栏切换后,状态丢失

通过 AutomaticKeepAliveClientMixin 实现。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  MainPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  State<StatefulWidget> createState() {
    return MainPageState();
  }
}

class MainPageState extends State<MainPage> {
  List<String> _list = ['111111', '222222', '3333333'];

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _list.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text("TabBar Status Test", textAlign: TextAlign.center, style: TextStyle(color: Colors.white)),
          centerTitle: true,
          bottom: TabBar(
            isScrollable: false,
            tabs: _list.map((String ss) {
              return Tab(text: ss);
            }).toList(),
          ),
        ),
        body: TabBarView(
          children: <Widget>[Page1('第一页'), Page2('第二页'), Page3('第三页')],
        ),
      ),
    );
  }
}

Page1、Page2、Page3 的内容请参照 >>> Flutter BottomNavigationBar切换页面被重置问题(保存状态)