Home > Mobile >  Flutter void function does not print a list when called
Flutter void function does not print a list when called

Time:06-13

I have this function in Flutter. All it does is take a given JSON file and convert a part of the data into a list and then print the elements of the list.

Future<void> readJson() async {
    final String response = await rootBundle.loadString('contents.json');
    final data = await json.decode(response);
    final myInts = (data['content_entries'] as List).cast<double>();
    for(int i = 0; i <= myInts.length;   i){
      print(i);
    }
  }

This is how I generate the JSON files:

  Future<File> saveToJsonFile(List<Map> contents, String filename) async {
    String encodedLandmarks = jsonEncode(contents);
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path   '/'   filename;
    return await File(appDocPath).writeAsString(encodedLandmarks);
  }

When I call the function, this is my output:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Unable to load asset:
/data/user/0/io.flutter.plugins.cameraexample/app_flutter/contents.json

The file does exist but I don't know where I'm going wrong.

CodePudding user response:

  • Open your pubspec.yaml file
  • Find the flutter > assets section
  • Add the filename

Assuming the file is in the assets folder e.g.

flutter:
  assets:
    - assets/contents.json

CodePudding user response:

You can read the string from the dynamically generated file as below.

File file = File(filePath);
String contents = await file.readAsString();
  • Related