Flutter - TabBar導航欄切換後,狀態丟失

上一篇講到了html

Flutter - BottomNavigationBar底部導航欄切換後,狀態丟失app

 

裏面提到了TabBar,這兒專門再寫一下吧,具體怎麼操做,來不讓TabBar的狀態丟失。畢竟你們99%的狀況都是不讓其狀態丟失,谷歌就不能默認這個選項嗎??less

 

先看一個沒有保存狀態的例子:ide

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final List<String> _list = ['111111', '222222', '333333'];
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _list.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            "TabBar Status Test",
            textAlign: TextAlign.center,
            style: TextStyle(color: Colors.white),
          ),
          centerTitle: true,
          bottom: TabBar(
            isScrollable: false,
            tabs: _list.map((String ss) {
              return Tab(text: ss);
            }).toList(),
          ),
        ),
        body: TabBarView(
          children: <Widget>[TextField(), TextField(), TextField()],
        ),
      ),
    );
  }
}

 

很簡單,一個標籤頁,每個標籤頁下面都有一個文本框,你能夠輸入文字。post

可是切換標籤頁後,文字丟失。正如預期的那樣。字體

 

 

 

下面咱們把TextField可是拿出來,新建一個page1.dart文件,代碼ui

注意紫色字體部分 AutomaticKeepAliveClientMixinthis

import 'package:flutter/material.dart';

class Page1 extends StatefulWidget {
  @override
  _Page1State createState() => _Page1State();
}

class _Page1State extends State<Page1> with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextField(),
    );
  }
}

 

Page2 和 Page3 同理。spa

而後再main.dart中引用code

import 'page1.dart';
import 'page2.dart';
import 'page3.dart';

 

修改

body: TabBarView(
          children: <Widget>[Page1(), Page2(), Page3()],
        ),

 

這樣一來,再輸入文字之後,切換標籤,狀態仍然保持!

相關文章
相關標籤/搜索