20个Flutter实例视频教程-第08节: 保持页面状态

博客地址:

https://jspang.com/post/flutterDemo.html#toc-bb9

视频地址:

https://www.bilibili.com/video/av39709290/?p=8

 

创建项目demo05

 

keepAliveDemo是一个自定义组件

 

keepAliveDemo这个组件必须是个动态组件,因为他来回的切换还要变换里面的效果

sfu快捷键快速生成

第一个知识点就是with。

这里我们继承自State,如果我们还要继承其他的类呢?这里就用到了with。表示混入。为了解决多重继承的问题

混入with SingleTickerProviderStateMixin。作用就是我们在初始化Tabcontroller的时候要用到一个垂直的选项。这个选项必须在这个混入里面使用

 

我们现在已经混入了这个类

定义TabController _controller.

因为要保持来回切换这个状态页面不变。所以要重写我们的销毁方法和initState方法

 

再重写我们的销毁方法

 

然后再来写我们的TabBar

 

最终效果:

 

 

代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: KeepAliveDemo()
    );
  }
}

class KeepAliveDemo extends StatefulWidget {
  @override
  _KeepAliveDemoState createState() => _KeepAliveDemoState();
}

class _KeepAliveDemoState extends State<KeepAliveDemo> 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: <Widget>[
          Text('1111'),
          Text('2222'),
          Text('3333'),
        ],
      ),
    );
  }
}
main.dart

 

posted @ 2019-03-24 15:13  高山-景行  阅读(184)  评论(0编辑  收藏  举报