Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState() is not working in async calls in flutter

Tags:

flutter

dart

I'm trying to read a json file named mood.json and parse it to a list named "data", but when I run setState(), the data never changed, any help about this problem? The code looks like this:

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"]),
          );
          },),
    );
  }
}
like image 426
nujabse Avatar asked May 25 '18 10:05

nujabse


1 Answers

I think your problem may be something else; I took your code and changed the network call to just wait 5 seconds and then return some dummy data and it worked fine.

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

You should put a breakpoint inside your setState call to ensure it's actually being called and that the data being assigned to _data is as you expect.

like image 50
Danny Tuppeny Avatar answered Sep 22 '22 08:09

Danny Tuppeny