Write to/read from file and setState – flutter


Question for more experienced colleagues. In my application I have a listview of items loaded from a json file.

itemBuilder: (context, index) => allRadioList(articles[index], context, _content, onPressing: () {
_writeDataFav(articles[index].id.toString(), _content);

The user can add an item to the favorites by clicking on the button via writing an array with ID numbers to a local file, then loading the contents of the file and saving it to setState.

icon: Icon(LineIcons.heartAlt, size: 20, color: Colors.yellow),
onPressed: onPressing,

When a user removes an item from favorites, I load the contents of the file, modify it and save it to the file, and then load it and save it to setState.

    Future<void> _readData() async {
    final dirPath = await _getDirPath();
    final myFile = await File('$dirPath/fav.txt');
    final data = await myFile.readAsString(encoding: utf8);
    setState(() {
      _content = data;
    Future<void> _writeDataFav(newString, _content) async {
    final _dirPath = await _getDirPath();
    final _myFile = File('$_dirPath/fav.txt');
      String res = '${_content}|${newString}|';
      await _myFile.writeAsString(res);

This works almost perfectly, but occasionally the contents of the file don’t load, after action click or an empty table is loaded. After refreshing everything is ok. It looks like the file could not be loaded before the next operations were performed.

Is it possible to execute the function only after verifying that the file has been saved? Only then set setState?

I considered using sharedPreferrences or a local database, but that’s probably too much for such a small array of data.


Change the onPressing to async function so _readData will only be executed after _writeDataFav is completed.

onPressing: () async {
  await _writeDataFav(articles[index].id.toString(), _content);
  await _readData();

Answered By – TYJ

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *