我正在尝试读取一个名为 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"]),
);
},),
);
}
}
1 回答
我认为你的问题可能是另一回事;我拿了你的代码并将网络调用更改为等待5秒,然后返回一些虚拟数据,它工作正常 .
您应该在
setState
调用中放置一个断点,以确保它实际被调用,并且分配给_data
的数据正如您所期望的那样 .