Home > Enterprise >  Casting Future<List<String>> to a List<String> throws an exception in Flutter
Casting Future<List<String>> to a List<String> throws an exception in Flutter

Time:06-16

I have this function:

  Future<List<String>> _readJson(String path) async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path   '/'   path;
    String response = await File(appDocPath).readAsString();

    final data = await (json.decode(response) as List<dynamic>).cast<String>();

    return data;
  }

As you can see, the output is a Future<List<String>>. I want to assign the output of this function to a new list like this (to be able to iterate through the elements:

  void _function(Map<dynamic, dynamic> playbackData) {
    ...

    List<String> jsonList = readJSON('landmarks.json') as List<String>;

    for(int i = 0; i <= jsonList.length - 1;   i){
      print(jsonList[i]);
    }
  }

But this is my error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Future<List<String>>' is not a subtype of type 'List<String>' in type cast

I know that the output is a Future List of Strings but I am deliberately casting it to a List of strings for that purpose. Where am I going wrong?

CodePudding user response:

I've managed to read a Future<List<String>> with the following code. Just await for your result before assigning it to jsonList. Don't forget to mark your function as async too:

void _function(Map<dynamic, dynamic> playbackData) async {
  ...

  List<String> jsonList = await readJSON('landmarks.json');

  for (int i = 0; i <= jsonList.length - 1;   i) {
    print(jsonList[i]);
  }
}

CodePudding user response:

Just await the return and you will get List<String>

and change the return type to

_readJson(String path) async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path   '/'   path;
    String response = await File(appDocPath).readAsString();

    final data = json.decode(response);

    return data;
  }

Then to read its data

List<dynamic> jsonList = await readJSON('landmarks.json');
for(int i = 0; i <= jsonList.length - 1;   i){
      print(jsonList[i]);
    }
  • Related