Neeraj Sharma
2 min readSep 12, 2019

Flutter — Read Json file stored in asset folder

Future<String>_loadFromAsset() async {
return await rootBundle.loadString("assets/quiz.json");
}

Future parseJson() async {
String jsonString = await _loadFromAsset();
final jsonResponse = jsonDecode(jsonString);
}

What is an asset?

Asset (in Android world this is called a resource) is a file that is bundled with the app. Common types of asset includes json file, icons, images

Where do you store assets your Flutter project?

  1. Create a folder named assets in your Flutter Project

2. Make an entry for the asset quiz.json under assets (which btw is the name of the assets folder)in pubspec.yaml

What is a Future?

Using Future you can handle long running tasks (such as network request, file IO, image processing etc)

How to define a Future?

Future myFoo() { }

How to define a Future that returns something?

Future<String> myFoo() {}

This defines a Future that returns a String.

How to use a Future?

Two ways

  1. Common way is to await on the Future by marking the with async
Future<String>_loadFromAsset() async {
return await rootBundle.loadString("assets/quiz.json");
}

In this example, the function will wait till the json file quiz.json stored in the asset folder in the project is loaded and it returns the String with json data which further needs to be decoded.

2. The second way is to use .then if you do not want to mark with async and use await.

Neeraj Sharma
Neeraj Sharma

Written by Neeraj Sharma

Mobile application developer, an urban traveller, and a passionate photographer — “programming is a creative process almost like story telling”

Responses (2)