Flutter 切换Tab导航栏保持页面的数据状态

效果图

main

import 'package:flutter/material.dart';
import 'keep_alive_demo.dart';
main(){
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
       primarySwatch: Colors.pink,
      ),
      home: KeepAliveDemo(),
    );
  }
}
class KeepAliveDemo extends StatefulWidget {
  KeepAliveDemo({Key key}) : super(key: key);

  _KeepAliveDemoState createState() => _KeepAliveDemoState();
}
                                              // 混入  类似多重继承
class _KeepAliveDemoState extends State  with SingleTickerProviderStateMixin{
  TabController _controller;

  // 初始状态
  @override
  void initState() {
    super.initState();
     //设置三个按钮
    _controller = TabController(length: 3,vsync: this);
  }

  // 销毁状态
  @override
  void dispose() {
   _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Keep Alive Demo'),
      bottom: TabBar(
        controller: _controller,
        tabs: [
          Tab(icon: Icon(Icons.directions_car),),
          Tab(icon: Icon(Icons.directions_transit),),
          Tab(icon: Icon(Icons.directions_bike),)
        ],
      ),),
      body: TabBarView(
        controller: _controller,
        children: [
          // 调用写好的方法
          MyHomePage(),
          MyHomePage(),
          MyHomePage(),
        ],
      ),
    );
  }
}

keep_alive_demo

import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State with AutomaticKeepAliveClientMixin{
  
  // 计数器
  int _counter = 0;
  @override
  bool get wantKeepAlive => true;

  //内部使用相加的方法
  _incrementCounter(){
    setState(() {
      _counter++;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('点击一次加一'),
            Text('$_counter',
            // 设置样式
            style: Theme.of(context).textTheme.display1,)
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // 响应事件
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

你可能感兴趣的:(Flutter 切换Tab导航栏保持页面的数据状态)