页面状态保持

状态保持需要做到以下两点:
1:with AutomaticKeepAliveMixIn
2:@override
  bool get wantKeepAlive=>true;



完整示例:
main.dart:
import 'package:flutter/material.dart';
import 'pageview.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin{
TabController _tabController;
@override
void initState() {
// TODO: implement initState
_tabController=TabController(length: 3, vsync: this);
super.initState();
}
@override
void dispose() {
// TODO: implement dispose
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AutomaticKeepAlive'),
bottom: TabBar(
controller: _tabController,
tabs: <Widget>[
Tab(icon: Icon(Icons.send),text: 'send',),
Tab(icon: Icon(Icons.event),text: 'event',),
Tab(icon: Icon(Icons.map),text: 'map',),
],
),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
PageViewWidget(index:6),
PageViewWidget(index:5),
PageViewWidget(index:3),
],
),

);
}
}




pageview.dart:
import 'package:flutter/material.dart';
import 'dart:ui';

class PageViewWidget extends StatefulWidget {
int index=0;
PageViewWidget({Key key,@required this.index}):super(key:key);
@override
_PageViewWidgetState createState() => _PageViewWidgetState();
}

class _PageViewWidgetState extends State<PageViewWidget> with AutomaticKeepAliveClientMixin{
int count=0;
@override
bool get wantKeepAlive=>true;

@override
Widget build(BuildContext context) {
return Container(
width: window.physicalSize.width,
height: window.physicalSize.height,
child: Stack(
children: <Widget>[
Image.network('http://www.ecobentech.com/images/${widget.index}.jpg',fit: BoxFit.cover,width: window.physicalSize.width,),
Positioned(
top: 200,
left: 60,
child: ActionChip(label: Text('$count'), onPressed:(){
setState(() {
count++;
});
}),
)
],
),
);
}
}


上一篇:java – 如何使用EasyMock模拟从抽象类继承的方法?


下一篇:AJPFX详解泛型中super和extends关键字