Flutter- How to get the local json file and decode it in Flutter

Article Directory
Method 1: rootBundle.loadString
Method 2: DefaultAssetBundle.of(context).loadString
The difference between the two methods
To obtain the local json file in Flutter, two methods are provided in the blog post. Here first create a local json file under the path "assets/config/anime.json", as shown in the figure below
insert image description here

Then  pubspec.yaml add the following to the configuration file insert image description here

Next is how to get the local json file.

Method 1: rootBundle.loadString

You can use  rootBundle.loadString the method to get the local json file. As shown in the following code

 List _animes = []; // 动漫列表

  @override
  void initState() {
    rootBundle.loadString("assets/config/anime.json").then((value) {
      var map = json.decode(value); // 解码
      _animes = map["animes"]; // 列表赋值
    });
    super.initState();
  }

Then just traverse the array directly, as shown in the following code (irrelevant code has been omitted)

 ..._animes.map(
   (e) => Row(
     children: <Widget>[Text("${e['id']}"), Text(e['name'])],
   ),
 )

The effect diagram is as follows

Method 2: DefaultAssetBundle.of(context).loadString

The method used  DefaultAssetBundle.of(context).loadString to get the local json file.

The final effect is the same as method 1, just upload the code directly

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("加载本地json文件")),
      body: FutureBuilder(
        future: DefaultAssetBundle.of(context).loadString("assets/config/anime.json"),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          var map = json.decode(snapshot.data.toString());
          _animes = map["animes"]; // 列表赋值
          // 因为获取 json 文件是异步的,如果还没有获取到数据,则显示 loading 组件
          if (snapshot.connectionState != ConnectionState.done) {
            return Center(child: CircularProgressIndicator());
          }
          return Card(
            child: Column(
              children: _animes
                  .map((e) => Row(children: <Widget>[Text("${e['id']}"), Text(e['name'])]))
                  .toList(),
            ),
          );
        },
      ),
    );
  }

The difference between the two methods
Regarding the difference between the two ways of loading local json files, the following two are relevant information I found, for reference only

Loading through the rootBundle object: Each Flutter application has a rootBundle object through which the main resource bundle can be easily accessed, and the asset can be loaded directly using the global static rootBundle object in package:flutter/services.dart.
Loading via DefaultAssetBundle: It is recommended to use DefaultAssetBundle to obtain the AssetBundle of the current BuildContext. Instead of using the default asset bundle built by the application, this approach makes a different AssetBundle that the parent widget dynamically replaces at runtime, which is useful for localization or testing scenarios.
Here is how to get local json files in Flutter.


Original link: https://blog.csdn.net/qq_42351033/article/details/118669642

 

 

Guess you like

Origin blog.csdn.net/qq_27909209/article/details/130410477