在测试AutomaticKeepAliveClientMixin并遇到问题,在navigator.push后页面丢失状态。有人知道此问题吗?任何解决方法?为任何信息而高兴,欢呼
我的目标是保持页面状态
重现步骤:打开应用程序,单击PageOne的按钮,然后向左和向右滑动,页面将丢失状态 图像
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: MyApp()));
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
initialIndex: 0,
length: 2,
child: Scaffold(
body: TabBarView(
children: <Widget>[Page1(), Page2()],
),
bottomNavigationBar: Material(
child: TabBar(
labelColor: Colors.black,
tabs: <Widget>[
Tab(
icon: Icon(Icons.check),
),
Tab(
icon: Icon(Icons.check),
),
],
),
),
),
),
);
}
}
class Page1 extends StatefulWidget {
@override
Page1State createState() {
return new Page1State();
}
}
class Page1State extends State<Page1> with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
Container(
height: 300,
color: Colors.orange,
),
Container(
height: 300,
color: Colors.pink,
),
Container(
height: 300,
color: Colors.yellow,
child: Center(
child: Container(height: 26,
child: MaterialButton(
color: Colors.blue,
child:
Text('clicking this and back then swipe => page loses state'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PushedPage()),
);
}),
),
),
),
],
);
}
@override
bool get wantKeepAlive => true;
}
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(height: 300, color: Colors.orange);
}
}
class PushedPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
color: Colors.blue,
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
anm*_*ail 14
从AutomaticKeepAliveClientMixin的文档中:
///为[AutomaticKeepAlive]的客户提供了具有便捷方法的混合。与[State]子类一起使用。
///子类必须实现[wantKeepAlive],并且它们的[build]方法必须调用super.build(返回值始终返回null,应将其忽略)。
因此,在您的代码中,在返回ListView之前,只需调用super.build:
Widget build(BuildContext context) {
super.build(context);
return ListView(..
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1403 次 |
| 最近记录: |