Home > Blockchain >  Extract String From Future<String> In Flutter
Extract String From Future<String> In Flutter

Time:10-24

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:

@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.

CodePudding user response:

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 -- */;
             },
           
         }
      }
    },
  ),
);

CodePudding user response:

You are getting data but not decoding it. You need to decode for using the loaded data.

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

Also, please don't forget to import dart convert library to use jsonDecode.

import 'dart:convert';
  • Related