How to use a String returned by a Future<String> method in flutter?

983 Views Asked by At

I'm trying to read a json file's components using the following method:

import 'dart:io';

class CharacterDataReader {
  Future<String> read() async {
    final file = File('assets/data/character_data.json');

    String data = await file.readAsString();

    return data;
  }
}

Now, I'm trying to assign the read values to a String named data and json.decode() it in another class using the following:


Future<String> data = CharacterDataReader().read();
Map<String, dynamic> characterData = json.decode(data);

However, this doesn't work since json.decode() only accepts Strings as a parameter. Therefore, can someone please tell me how do I convert this Future into an actual string?

1

There are 1 best solutions below

0
On BEST ANSWER

since its a future you have to add await keyword

String data= await CharacterDataReader().read();

check out dart official doc on asynchronous programming