how to read local json file in flutter

8,519

Here’s sample.json:

{
  "items": [
{
  "id": "p1",
  "name": "Item 1",
  "description": "Description 1"
},
{
  "id": "p2",
  "name": "Item 2",
  "description": "Description 2"
},
{
  "id": "p3",
  "name": "Item 3",
  "description": "Description 3"
}
]
}

The code which is used to fetch data from the JSON file (see the full code below):

Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
// ... 
}

Declare the json file in the assets section in your pubspec.yaml file:

flutter:
assets:
- assets/sample.json

main.dart

import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:flutter/services.dart';

 void main() {
  runApp(const MyApp());
 }

 class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
 Widget build(BuildContext context) {
   return const MaterialApp(
  // Hide the debug banner
  debugShowCheckedModeBanner: false,
  title: 'Kindacode.com',
  home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _items = [];

// Fetch content from the json file
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/sample.json');
final data = await json.decode(response);
setState(() {
  _items = data["items"];
});
}

  @override
 Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
    centerTitle: true,
    title: const Text(
      'Kindacode.com',
    ),
  ),
  body: Padding(
    padding: const EdgeInsets.all(25),
    child: Column(
      children: [
        ElevatedButton(
          child: const Text('Load Data'),
          onPressed: readJson,
        ),

        // Display the data loaded from sample.json
        _items.isNotEmpty
            ? Expanded(
                child: ListView.builder(
                  itemCount: _items.length,
                  itemBuilder: (context, index) {
                    return Card(
                      margin: const EdgeInsets.all(10),
                      child: ListTile(
                        leading: Text(_items[index]["id"]),
                        title: Text(_items[index]["name"]),
                        subtitle: Text(_items[index]["description"]),
                      ),
                    );
                  },
                ),
              )
            : Container()
      ],
    ),
  ),
 );
 }
 }
Share:
8,519
Ahsan Tony
Author by

Ahsan Tony

Updated on November 26, 2022

Comments

  • Ahsan Tony
    Ahsan Tony over 1 year

    I am trying to read a local json file named "catalog.json" I wrote all the nessessary codes but it's showing this error "lateinitializationError: Field 'catalogdata' has not been initialized." then i tried by initializing the 'catalogdata' variable but then it shows that 'catalogdata' variable is empty . I dont know how to solve it . Please help me. my code

    import 'package:flutter/material.dart';
    import 'dart:convert';
    import 'package:flutter/services.dart';
    
    class Homepage extends StatefulWidget {
      const Homepage({Key? key}) : super(key: key);
    
      @override
      _HomepageState createState() => _HomepageState();
    }
    
    class _HomepageState extends State<Homepage> {
      late List catalogdata;
      Future<String> loadData() async {
        var data = await rootBundle.loadString("assets/images/files/catalog.json");
        setState(() {
          catalogdata = json.decode(data);
        });
        return "success";
      }
    
      @override
      void initState() {
        // TODO: implement initState
        this.loadData();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Homepage"),
          ),
          body: Center(
            child: Text(
              catalogdata[0],
              style: TextStyle(fontSize: 20),
            ),
          ),
        );
      }
    }
    
    • Daviswww
      Daviswww about 2 years
      have you tried add await before this.loadData();
    • Jaimin Modi
      Jaimin Modi over 1 year
      Do you have idea about reading it from app storage path.. ?
  • Ahsan Tony
    Ahsan Tony about 2 years
    thanks bro you saved me. I am new to flutter . I am trying to learn it . thanks for your help