Home > Enterprise >  read file returns null Flutter
read file returns null Flutter

Time:10-19

I have a page that writes a color on file, called "colors.txt".Then the page is closed, when it will be opened again this file will be read and its content (String) printed on the screen.

This is the class that handles reads and writes :

class Pathfinder {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/colors.txt');
  }

  Future<File> writeColor(String color) async {
    final file = await _localFile;
    // Write the file
    return file.writeAsString('$color');
  }

  Future<String> readColor() async {
    try {
      final file = await _localFile;

      // Read the file
      final contents = await file.readAsString();

      return contents;
    } catch (e) {
      // If encountering an error, return 0
      return "Error while reading colors";
    }
  }
}

Before page closure, the color has been saved with writeColor, we just need to read the file and print its content. And this is how I read the color :

void initState() {
    super.initState();
    String colorRead;
    () async {
      pf = new Pathfinder();
      colorRead = await pf.readColor();
    }();
    print("Color in initState: "   colorRead.toString());
  }

The problem is that colorRead is always null. I already tried .then() and .whenCompleted() but nothing changed.

So my doubt is : Am I not waiting read operation in right way or the file, for some reasons, is deleted when page is closed?

I think that if file wouldn't exists then readColor should throw an error.

EDIT : How writeColor is called :

Color bannerColor;
//some code
await pf.writeColor(bannerColor.value.toRadixString(16));

CodePudding user response:

  void initState() {
    super.initState();
    String colorRead;
    () async {
      pf = new Pathfinder();
      colorRead = await pf.readColor();
    }();
    print("Color in initState: "   colorRead.toString()); /// << this will execute before the async code in the function is executed
  }

It's null because of how async/await works. The print statement is going to be called before the anonymous async function finishes executing. If you print in inside the function you should see the color if everything else is working correctly.

  • Related