setState() 在颤动的异步调用中不起作用

nuj*_*bse 4 dart flutter

我正在尝试读取一个mood.json名为“data”的 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"]),
          );
          },),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*eny 8

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

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

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