Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract String From Future<String> In Flutter

I’m using flutter, and I’m loading in a locally stored JSON file like so:

Future<String> loadJson(String file) async {
  final jsonData = await rootBundle.loadString("path/to/$file.json");
  return jsonData;
}

The problem is that this returns a Future<String> and I’m unable to extract the actual JSON data (as a String) from it.

I call loadJson in the Widget build method like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@override
Widget build(BuildContext context) {
  final data = ModalRoute.of(context)!.settings.arguments as Map;
  final file = data["file"];
  String jsonData = loadJson(file); // The issue is here

  return Scaffold (/* -- Snip -- */);
}

How would I go about doing this? Any help is appreciated.

>Solution :

loadJson is Future and you need to await for its result:

String jsonData = await loadJson(file);

you also can’t run Future function inside build method, you need to use FutureBuilder:

return Scaffold (
    body: FutureBuilder<String>(
       future: loadJson(file),
       builder: (context, snapshot) {
         switch (snapshot.connectionState) {
           case ConnectionState.waiting:
               return Text('Loading....');
           default:
             if (snapshot.hasError) {
               return Text('Error: ${snapshot.error}');
             } else {
               String jsonData = snapshot.data ?? "";

               return /* -- Snip -- */;
             },
           
         }
      }
    },
  ),
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading