颤振设置状态,为什么第一个输出为空,如何跳过输出直到它不为空?



Answers.json

{
"hello-world3-2": "19"
}

我的游戏屏幕代码

String userAnswer = '';
var decodedAnswer;
class GameScreen extends StatefulWidget {
@override
_GameScreenState createState() => _GameScreenState();
}
class _GameScreenState extends State<GameScreen> {

在这里,我从 JSON 文件中得到的答案是 19

getDatas() async {
final realAnswer = await rootBundle.loadString('lib/assets/answers.json');
final decodedText = await json.decode(realAnswer.toString());
decodedAnswer = decodedText["hello-world3-2"];

我想在更改其值后全局进行解码答案

setState(
() {
while (decodedAnswer == null) {
decodedAnswer = decodedText["hello-world3-2"];

再次循环,以防解码答案仍然为空

continue;
}
},
);
}
@override
Widget build(BuildContext context) {
getDatas();
print(decodedAnswer.toString());

端子输出

Performing hot restart...                                               
Restarted application in 2,381ms.
W/Settings(25117): Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
V/HiTouch_HiTouchSensor(25117): User setup is finished.
V/AudioManager(25117): playSoundEffect   effectType: 0
V/AudioManager(25117): querySoundEffectsEnabled...
I/flutter (25117): null
I/flutter (25117): 19
I/flutter (25117): 19
I/flutter (25117): 19
I/flutter (25117): 19
I/flutter (25117): 19

你正在考虑这个问题。Flutter 是一个声明式框架,这意味着您实际上并不想像使用 C 代码那样逐步控制应用程序流。setState方法更改 StatefulWidget 的状态并使其再次build。你不想在那里循环并不断检查值是否已更改 - 这只会导致你的代码冻结。

与其将其视为:1(创建小部件,2(构建小部件,3(检查数据更新4(如果数据未更新,请重复3(

你想这样想:1(创建一个小部件,2(开始数据检索过程,完成后,改变状态,3(构建我的小部件,让它弄清楚何时重建。

因此,您可以改为执行以下操作:

class _GameScreenState extends State<GameScreen> {
String _data;
@override
void initState() {
super.initState();
_data = '';
getData().then((value) {
setState(() {
_data = value;
});
});
}
Future<String> getData() async {
//do your processing
return decodedText;
}
@override
Widget build(BuildContext context) {
pritn(_data);
return Text(_data);
}
}

重构函数以获取类似于

Future<String> getDatas() async {
//---- Fetch data from file.
return "your return value";}

并使用它

getDatas().then((value){
//--- Perform update here. 
//--- setState or whatever
setState(() {
decodedAnswer = decodedText["hello-world3-2"];
});
print("Value :$value");
});

最新更新