(Flutter 十五)保持页面状态

保持页面状态的意思就是在app中来回切换页面的时候,保持每个页面的数据状态不变。


第一个tabbar页面显示1

第二个tabbar页面显示2

1、main.dart
with是dart的关键字,混入的意思,就是说可以将一个或者多个类的功能添加到自己的类无需继承这些类, 避免多重继承导致的问题。

import 'package:flutter/material.dart';
import 'keep_alive_demo.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.blue,
      ),
      home:KeepAliveDemo() ,
    );
  }
}

//使用动态组件,它需要来回切换
class KeepAliveDemo extends StatefulWidget {
  @override
  _KeepAliveDemoState createState() => _KeepAliveDemoState();
}

//with的作用是多重继承,混入一个这样的东西,因为后续需要用到vsync属性
class _KeepAliveDemoState extends State with SingleTickerProviderStateMixin {
  TabController _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar( //把tabbar也添加到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(),
        ],
      ),
    );
  }
}

2、keep_alive_demo.dart

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State with AutomaticKeepAliveClientMixin{

  int _counter = 0;
  @override
/*这是一个方法,属于AutomaticKeepAliveClientMixin内部的,
  设置为true就可以保持当前页面不被修改
  设置为false时,每次更新页面数据都会被清除*/
  bool get wantKeepAlive => true; 

  void _incrementCounter(){ //内部方法,实现计数加1
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center, //主轴居中对齐
          children: [
            Text('点一次数量加1'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display3,//设置皮肤样式
            )
          ],
        ),
      ),
      //浮动按钮
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment', //提示
        child: Icon(Icons.add),
      ),
    );
  }
}

你可能感兴趣的:((Flutter 十五)保持页面状态)