20個Flutter實例視頻教程-第08節: 保持頁面狀態

博客地址:html

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

視頻地址:less

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

 

建立項目demo05ide

 

keepAliveDemo是一個自定義組件post

 

keepAliveDemo這個組件必須是個動態組件,由於他來回的切換還要變換裏面的效果ui

sfu快捷鍵快速生成this

第一個知識點就是with。spa

這裏咱們繼承自State,若是咱們還要繼承其餘的類呢?這裏就用到了with。表示混入。爲了解決多重繼承的問題3d

混入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
相關文章
相關標籤/搜索