Open In App

Flutter – Load JSON Assets

Improve
Improve
Like Article
Like
Save
Share
Report

In Flutter, you can load JSON assets using the rootBundle method from the flutter/services package. First, create a new Flutter project by running the following command in your terminal.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Add the material package that gives us the important methods and then call the runApp method in the main function that will call our application.

import 'package:flutter/material.dart';

void main() {
    runApp(RunMyApp());
}

Step 3: Now we have to make a stateful widget RunMyApp Because our application does go to change its state and then return the materialApp widget which allows us the set the title and theme and many more.

Step 4: Next, create a new file named data.json in the assets directory of your project. The assets directory should be located at the same level as the lib directory. In the data.json file, add some JSON data. For example:

{
  "name": "John Doe",
  "age": 30,
  "email": "johndoe@example.com"
}

Step 5: Open the pubspec.yaml file and add the following code to specify the asset.

Dart




flutter:
  assets:
    - assets/data.json


Step 6: In your Dart code, import the flutter/services package:

Dart




import 'package:flutter/services.dart' show rootBundle;


To load the JSON data from the asset, use the rootBundle.loadString method as shown below:

Dart




Future<void> loadJsonAsset() async {
  final String jsonString = await rootBundle.loadString('assets/data.json');
  final data = jsonDecode(jsonString);
  print(data);
}


The loadString method returns a Future<String> that represents the contents of the file. The jsonDecode method from the dart:convert library is then used to convert the JSON string to a Dart object. Call the loadJsonAsset method to load the JSON data when your app starts:

Dart




import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}
  
class _MyAppState extends State<MyApp> {
  var jsonData;
  Future<void> loadJsonAsset() async {
    final String jsonString = await rootBundle.loadString('assets/data.json');
    var data = jsonDecode(jsonString);
    setState(() {
      jsonData = data;
    });
    //print(jsonData);
  }
  
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadJsonAsset();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.green),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Load Assets Json'),
        ),
        body: Center(
            child: jsonData != null
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [Text(jsonData['name']), Text(jsonData['email'])],
                  )
                : CircularProgressIndicator()),
      ),
    );
  }
}


Output :

 



Last Updated : 27 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads