0

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.

2
  • how do you call loadJson? Commented Oct 24, 2022 at 6:29
  • I've edited my post to include the calling code Commented Oct 24, 2022 at 6:37

2 Answers 2

1

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 -- */;
             },
           
         }
      }
    },
  ),
);
Sign up to request clarification or add additional context in comments.

2 Comments

The problem is that I'm calling loadJson from the build method directly, and so I don't think I can use await there.
@FireTheLost check out new update.
0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.