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

視頻地址:https://www.bilibili.com/video/av39709290/?p=9html

博客地址:https://jspang.com/post/flutterDemo.html#toc-e3aapp

 

新建keep_alive_demo.dart.less

裏面新建類 MyHomePage是一個動態的widgetjsp

with只能引入混入的mixin的。AutomaticKeepAliveClientMixinide

 

 

聲明一個計數器:並重寫wantKeepAlivepost

再聲明一個內部的方法。點擊按鈕增長咱們的計數器ui

 

而後寫咱們的buildthis

而後再寫咱們浮動的按鈕。用floatingActionButtonspa

 

main.dart引入頁面3d

 

 

 

預覽效果:

 

從第二個切回到一個tab。裏面的數字不變,狀態保持了

 

最終代碼:

import 'package:flutter/material.dart';
import 'keep_alive_demo.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>[
         MyHomePage(),
         MyHomePage(),
         MyHomePage(),
        ],
      ),
    );
  }
}
main.dart

 

 

 

import 'package:flutter/material.dart';

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

class _MyHomePageState extends State<MyHomePage> with AutomaticKeepAliveClientMixin {
  int _counter=0;//聲明一個計數器
  @override
  bool get wantKeepAlive => true;//這是一個方法

  void _incrementCounter(){
    setState(() {
     _counter++; 
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,//垂直居中
          children: <Widget>[
            Text('點一次增長一個數字'),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '增長',
        child: Icon(Icons.add),
      ),
    );
  }
}
keep_alive_demo.dart
相關文章
相關標籤/搜索