Home > OS >  how to read local json file in flutter
how to read local json file in flutter

Time:03-01

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

CodePudding user response:

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

CodePudding user response:

it's showing this error "lateinitializationError: Field 'catalogdata' has not been initialized." then I tried by initializing the 'catalogdata'

While using late before variables make sure that, the variable must be initialized later. Otherwise, you can encounter a runtime error when the variable is used.

If you didn't add the correct location catalog.json in pubsec.yaml your variable catalog didn't gets the correct value so the late variable is not initialized.

enter image description here

So you must add asset path in pubsec.yaml

  assets:
    - assets/
    - assets/images/files/catalog.json
  

Another case here is JSON.decode() return map<string,dynamic> value here you set list.maybe that also cause the problem and not initialised.

enter image description here

instead of this late List catalogdata; use this late var catalogdata; or late Map<string,dynamic> catalogdata;

Sample Code

Catalog.json

{
  "name": "lava",
  "Catagory": "man"
}

Main.dart

import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class AppRoutes {
  static String detail = "/Detail";
  static String Page2 = "/FilterBeacon";
  static String Page1 = "/FilterPoint";
  static String home = "/";
}

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

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      // key: constItem.navigatorKey,

      initialRoute: "/",
      routes: {
        AppRoutes.home: (context) => Home(),
      },
      title: _title,
      // home: ,
    );
  }
}

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

  @override
  State<Home> createState() => _HomeState();
}

var _index = 0;

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Homepage(),
    );
  }
}

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

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

class _HomepageState extends State<Homepage> {
  late var catalogdata;

  Future<String> loadDatas() async {
    var data = await rootBundle.loadString("assets/images/files/catalog.json");
    // setState(() {
      catalogdata = json.decode(data);
    // });
    return "success";
  }

  Future<String> loadData() async {
    var data = await rootBundle.loadString("assets/images/files/catalog.json");
    setState(() {
    catalogdata = json.decode(data);
    });
    return "success";
  }

  @override
  void initState() {
    loadData();
    // loadData().then((value) => catalogdata=value);
  } // String jsons = "";

  // @override
  // Future<void> initState() async {
  //   super.initState();
  //   await loadData();
  // }

  @override
  Widget build(BuildContext context) {
    var futureBuilder = FutureBuilder(
          future:  loadData(),
          builder: (context, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting)
              return Center(child: CircularProgressIndicator());
            else if (snapshot.connectionState == ConnectionState.done)
              return Center(
                child: Text(
                  catalogdata.toString(),
                  style: TextStyle(),
                ),
              );
            else
              return Container();
          });
    return Scaffold(
      appBar: AppBar(
        title: Text("Homepage"),
      ),
      body: Center(
        child: Text(
          catalogdata.toString(),
          style: TextStyle(),
        ),
      ),
    );
  }
}
  • Related