【问题标题】:Not able to load local JSON File in Flutter无法在 Flutter 中加载本地 JSON 文件
【发布时间】:2020-10-15 03:02:45
【问题描述】:

我正在开发一个个人 Flutter 项目,其中包含一些本地存储的 JSON 文件

这是代码

class CCategory extends StatefulWidget {
  @override
  _CCategory createState() => _CCategory();
}
class Prod {
  String Name;
  String Image;
  Prod({ this.Name, this.Image});
  factory Prod.fromJson(Map<String, dynamic> parsedJson) {
    return Prod(
        Name: parsedJson['Name'],
        Image: parsedJson['Image']);
  }
}
Future<String> _loadProdAsset() async {
  return await rootBundle.loadString('assets/data/Dabur.json');
}
Future<Prod> loadProd() async {
  String jsonString = await _loadProdAsset();
  final jsonResponse = json.decode(jsonString);
  return new Prod.fromJson(jsonResponse);
}

class _CCategory extends State<CCategory> {

  Prod _prod;
  bool _loaded = false;
  @override
  void initState() {
    super.initState();
    loadProd().then((s) => setState(() {
      _prod = s;
      _loaded = true;
    }));
  }
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitDown,
      DeviceOrientation.portraitUp,

    ]);
    return MaterialApp(
        title: "Dabur Products",
        theme: ThemeData(
          primaryColor: Colors.black,
        ),
        home: Scaffold(
            appBar: AppBar(
              title: Text("Dabur Products",
              ),
            ),
            body: _loaded?Center(

                child: ListView(

                    children: <Widget>[
                ListTile(
                leading: Image.asset('${_prod.Image}'),
                  title: Text('${_prod.Name}'),
    )
    ]

    )
    )
                : new Center(
              child: new CircularProgressIndicator(),
            )
        ),
    );

    }

    }

JSON 文件的内容没有被加载,这是我在调试时遇到的错误

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] 未处理的异常:“List”类型不是“Map”类型的子类型

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: android json flutter dart flutter-layout


    【解决方案1】:

    我不知道您的 JSON 文件长什么样,但看看您的错误代码,json.decode(jsonString) 似乎给您一个List 而不是Map。我猜你的 JSON 文件实际上是一个列表:

    [ 
      ... content ...
    ]
    

    相反,您的 JSON 文件应如下所示(使用 { }):

    { 
      "Name": ...,
      "Image": ...
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 1970-01-01
      • 2021-03-25
      • 2019-05-30
      • 2016-02-04
      • 2013-09-04
      • 1970-01-01
      • 2011-11-12
      相关资源
      最近更新 更多