gpt4 book ai didi

dart - setState() 在 flutter 中的异步调用中不起作用

转载 作者:IT王子 更新时间:2023-10-29 06:51:52 25 4
gpt4 key购买 nike

我正在尝试读取一个名为 mood.json 的 json 文件并将其解析为一个名为“data”的列表,但是当我运行 setState() 时, data 从未改变,对这个问题有帮助吗?代码如下所示:

class DisplayPage extends StatefulWidget {
@override
_DisplayPageState createState() => new _DisplayPageState();
}

class _DisplayPageState extends State<DisplayPage> {
List _data = [];
Directory dir;
File jsonFile;
String jsonPath;

Future getData() async {
dir = await getApplicationDocumentsDirectory();
jsonPath = dir.path + "/" + "mood.json";
jsonFile = new File(jsonPath);
setState(() {
_data = json.decode(jsonFile.readAsStringSync());
});
}

@override
void initState() {
super.initState();
getData();
print(_data.length);
}


@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Mood')
),
body: new ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Text(_data[index]["title"]),
);
},),
);
}
}

最佳答案

我认为你的问题可能是别的;我采用了您的代码并将网络调用更改为仅等待 5 秒,然后返回一些虚拟数据并且它工作正常。

Future getData() async {
await new Future.delayed(const Duration(seconds: 5));
setState(() {
_data = [
{"title": "one"},
{"title": "two"},
];
});
}

您应该在 setState 调用中放置一个断点,以确保它确实被调用,并且分配给 _data 的数据符合您的预期。

关于dart - setState() 在 flutter 中的异步调用中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50527439/

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