gpt4 book ai didi

flutter - 抖动几秒钟后如何更新图像?

转载 作者:行者123 更新时间:2023-12-03 04:23:33 24 4
gpt4 key购买 nike

我正在构建Flutter应用程序,该应用程序需要在一段时间后更改图像。我认为将while循环与内部的sleep方法一起使用可能会解决问题。但事实并非如此,在循环结束后,Image只会发生变化。应用程序用户界面也被冻结。

所需的输出:应每10秒更改一次图像。

Image When I clicked On Start BUtton To start The Loop Image After Loop Ends

图像和按钮文本而不是更新 Loop运行时,请帮助我获得所需的输出。


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Test(
),
),
)
);
}}
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}

class _TestState extends State<Test> {
int imgnumber=1;
int varToCheckButtonPress = 0;
String BtnTxt = "START";
void inc(){
while(imgnumber<10)
{
print(imgnumber);
setState(() {
sleep(Duration(seconds:5));
imgnumber++;
});
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(flex: 1,
child: Container(
child: Image.asset('images/'+imgnumber.toString()+'.png'),
height: 500,
width:500,
color: Colors.green,
),
),
FlatButton(
child: Text(BtnTxt),
onPressed: (){
if (varToCheckButtonPress == 0) {
setState(() {
BtnTxt = 'PAUSE';
varToCheckButtonPress = 1;
});
} else if (varToCheckButtonPress == 1) {
setState(() {
BtnTxt = 'RESUME';
varToCheckButtonPress = 0;
});
}
inc();
},
)
],
);
}
}

最佳答案

您不应该在setState中使用sleep尝试用以下方法替换inc函数:

void inc() async {
while(imgnumber<10)
{
print(imgnumber);
await Future.delayed(const Duration(seconds: 10));
setState(() {
imgnumber++;
});
}
}

关于flutter - 抖动几秒钟后如何更新图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61179376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com