简体   繁体   English

如何读取flutter中的本地json文件

[英]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."我正在尝试读取名为“catalog.json”的本地 json 文件,我编写了所有必要的代码,但它显示此错误“lateinitializationError:字段‘catalogdata’尚未初始化。” then i tried by initializing the 'catalogdata' variable but then it shows that 'catalogdata' variable is empty.然后我尝试初始化“catalogdata”变量,但随后它显示“catalogdata”变量为空。 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),
        ),
      ),
    );
  }
}

Here's sample.json:这是示例 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):用于从 JSON 文件中获取数据的代码(请参阅下面的完整代码):

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:在 pubspec.yaml 文件的资产部分声明 json 文件:

flutter:
assets:
- assets/sample.json

main.dart主要.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()
      ],
    ),
  ),
 );
 }
 }

it's showing this error "lateinitializationError: Field 'catalogdata' has not been initialized."它显示此错误“lateinitializationError:字段'catalogdata'尚未初始化。” then I tried by initializing the 'catalogdata'然后我尝试初始化“catalogdata”

While using late before variables make sure that, the variable must be initialized later.在确保使用late before 变量时,变量必须稍后初始化。 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.如果您没有在 pubsec.yaml 中添加正确的位置 catalog.json,您的变量 catalog 没有获得正确的值,因此未初始化 late 变量

在此处输入图像描述

So you must add asset path in pubsec.yaml所以你必须在 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.这里的另一种情况是JSON.decode() return map<string,dynamic> value here you set list.maybe 这也会导致问题并且未初始化。

在此处输入图像描述

instead of this late List catalogdata;而不是这个late List catalogdata; use this late var catalogdata;使用这个late var catalogdata; or late Map<string,dynamic> catalogdata;或后期 Map<string,dynamic> 目录数据;

Sample Code示例代码

Catalog.json目录.json

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

Main.dart主要.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(),
        ),
      ),
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM