你必须使用AutomaticKeepAliveClientMixin-mixin
将 AutomaticKeepAliveClientMixin 混合添加到 State 的 State(项目小部件)中,覆盖 wantKeepAlive 方法并返回 true。
我解决了什么:
你的完整(更新)飞镖:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
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> {
List<Widget> _widgets = [MyStatefulWidget()];
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.separated(
itemCount: _widgets.length,
itemBuilder: (_, index) {
return _widgets[index];
},
reverse: true,
shrinkWrap: true,
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
width: 5,
);
},
),
floatingActionButton: TextButton(
onPressed: () {
setState(() {
// Insert first in the list, hope it's just need to rebuild only the first item, the remains are unchanged
_widgets.add(MyStatefulWidget());
});
},
child: Container(
child: Text(
'Press',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.red,
),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> createState');
return _MyStatefulState();
}
}
+class _MyStatefulState extends State<MyStatefulWidget> with AutomaticKeepAliveClientMixin{
StreamSubscription? countdownSubscription;
int countdownTime = 30;
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
initTimeoutUI();
}
void initTimeoutUI() {
countdownSubscription = Future.delayed(Duration(seconds: 1)).asStream().listen((value) {
if (countdownTime > 0) {
setState(() {
countdownTime--;
});
}
initTimeoutUI();
});
}
@override
void dispose() {
super.dispose();
countdownSubscription?.cancel();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Container(
width: 100,
height: 100,
child: Center(child: Text('countdown: $countdownTime')),
);
}
}