Flutter Future.delayed 无限循环
Flutter Future.delayed on endless loop
我是运行这个代码
Future.delayed(Duration(milliseconds: 500)).then((value) => {opened = false,setState(() {}), value = "null"});
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
getStorage();
Future.delayed(Duration(milliseconds: 500))
.then((value) => {opened = false, setState(() {}), value = "null"});
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
color: Colors.green,
alignment: Alignment.center,
child: AnimatedContainer(
duration: Duration(milliseconds: 3000),
height: opened ? 0 : 300,
width: opened ? 0 : 300,
curve: Curves.fastOutSlowIn,
alignment: Alignment.center,
child: Lottie.asset('assets/101349-swing.json'),
),
),
),
);
}
}
它returns
I/flutter (22251): false
不断,我想避免,因为我认为它效率低下。
你在build
方法里面添加了Future.delay
,这是一个StatefullWidget,build方法可以多次调用,比如每当你调用setState()
build方法就会触发并调用Future.delay
在你的情况下提供无限循环。
要调用单次,覆盖initState
,你可以这样做,
@override
void initState() {
super.initState();
_initFuture();
}
_initFuture() async {
Future.delayed(Duration(milliseconds: 500))
.then((value) => {opened = false, setState(() {}), value = "null"});
}
我是运行这个代码
Future.delayed(Duration(milliseconds: 500)).then((value) => {opened = false,setState(() {}), value = "null"});
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
getStorage();
Future.delayed(Duration(milliseconds: 500))
.then((value) => {opened = false, setState(() {}), value = "null"});
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
color: Colors.green,
alignment: Alignment.center,
child: AnimatedContainer(
duration: Duration(milliseconds: 3000),
height: opened ? 0 : 300,
width: opened ? 0 : 300,
curve: Curves.fastOutSlowIn,
alignment: Alignment.center,
child: Lottie.asset('assets/101349-swing.json'),
),
),
),
);
}
}
它returns
I/flutter (22251): false
不断,我想避免,因为我认为它效率低下。
你在build
方法里面添加了Future.delay
,这是一个StatefullWidget,build方法可以多次调用,比如每当你调用setState()
build方法就会触发并调用Future.delay
在你的情况下提供无限循环。
要调用单次,覆盖initState
,你可以这样做,
@override
void initState() {
super.initState();
_initFuture();
}
_initFuture() async {
Future.delayed(Duration(milliseconds: 500))
.then((value) => {opened = false, setState(() {}), value = "null"});
}