101

How do I load a JSON asset into my Flutter app?

My pubspec.yaml file has the following:

assets:
    - assets/data.json

I keep getting stuck trying to load the data. I tried:

final json = JSON.decode(
    DefaultAssetBundle.of(context).loadString("assets/data.json")
);

But I get the error:

The argument type 'Future< String>' can't be assigned to the parameter type 'String'.

2
  • Apparently JSON.Decode returns a map, not a string Apr 10, 2018 at 15:52
  • 1
    Yes, the end result I want is a map from JSON.decode. I'm just having trouble feeding it the string representation of the JSON file.
    – nalyd88
    Apr 10, 2018 at 15:54

4 Answers 4

111

Try out :

String data = await DefaultAssetBundle.of(context).loadString("assets/data.json");
final jsonResult = jsonDecode(data); //latest Dart
2
  • 2
    I also like json_serializable's approach. Doesn't need to include that json as asset in the pubspec.yaml at all. Apr 10, 2018 at 16:59
  • I had to declare the assets/data.json in my pubspec.yaml otherwise the file was not be found, using Flutter 3.x. Nov 21, 2022 at 2:06
51

@Alexandre Beaudet's answer is correct but doesn't give a lot of context about what is going on.

When you're calling loadString, it's actually an asynchronous method call. You can tell because it returns a Future<value> rather than just a value. This means that it doesn't immediately have a result of String, but will at some point in the future.

There are two main ways of dealing with asynchronicity in Dart; the first being to use async and await, the second being to use the futures directly. See the dart guide on Asynchronous Programming.

If you use future.then directly, you can do it from a normal function (i.e. from initState etc). You simply specify the callback and in the callback what to do with the result.

void printDailyNewsDigest() {
  final future = gatherNewsReports();
  future.then((news) => print(news));
}

If you want to use await as @Alexandre has illustrated, you need to mark the function you are using it from as async, i.e.:

Future<Void> printDailyNewsDigest() async {
  String news = await gatherNewsReports();
  print(news);
}

If you override a function (i.e. initState) you also need to make sure you don't change the return value. That should get caught by dart 2's typing most of the time, but void -> Future doesn't seem to be.

One last thing to note - if you're using the result of the data to build widgets, you'll probably want to look at using a FutureBuilder.

1
  • 1
    Was in a rush yesterday, thanks for putting some explanations and context ! Apr 11, 2018 at 7:11
36

I use the following to parse json in assets:

import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
//...
Future<Map<String, dynamic>> parseJsonFromAssets(String assetsPath) async {
    print('--- Parse json from: $assetsPath');
    return rootBundle.loadString(assetsPath)
        .then((jsonStr) => jsonDecode(jsonStr));
  }

Usage async:

parseJsonFromAssets(path)
    .then((dmap) => {
    // here you get json `dmap` as Map<String, dynamic>
    print(dmap);
}));

Usage sync:

Map<String, dynamic> dmap = await parseJsonFromAssets('assets/test.json');
4
  • Dear thunder Why String jsonString = await _loadAStudentAsset(); final jsonResponse = json.decode(jsonString); return chiese.fromJson(jsonResponse[0]); give me only first row of json ..i can't retrive all rows ?? Dec 31, 2019 at 14:46
  • @DanieleAngelini Does your Json string contains \n or any thing like it? And where do u get the first row? jsonResponse or jsonResponse[0] ? Jan 9, 2020 at 6:32
  • Dear thundertrick can look here flutterforum.co/t/cannot-read-entire-file-to-parse-json/778 i post all my code... thx ...i'm stuck!!! Jan 16, 2020 at 1:45
  • @DanieleAngelini It seems u r parsing a json array, which might not be supported. Try to add the array to a json, such as {"data":[{},{}]} Jan 17, 2020 at 3:22
33

You can use this code :)

loadJson() async {
  String data = await rootBundle.loadString('assets/json/keyboard.json');
  jsonResult = json.decode(data);
  print(jsonResult);
}

Can load on start :)

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await loadJson();
    });
  }

Need to add the JSON on the asset

flutter:
  uses-material-design: true
  assets:
    - assets/json/keyboard.json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.