Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to read local json file in flutter

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),
        ),
      ),
    );
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
      ],
    ),
  ),
 );
 }
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading