如何在Flutter中读取本地JSON导入? [英] How to read local json import in flutter?

查看:1035
本文介绍了如何在Flutter中读取本地JSON导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在flutter目录中有一个JSON文件,而不在资产中.

I have a JSON file in the flutter directory, not in assets.

json_data.json:-

json_data.json:-

 {
    "foo" : "bar"
 }

我想在其他文件上读取此JSON.

I want to read this JSON on different files.

喜欢

myfile.dart:-

myfile.dart:-

 import "package:mypackage/json_data.json" as data;
 import 'dart:convert';
 
  var my_data = json.decode(data);

我遇到了错误:-

The name 'data' refers to an import prefix, so it must be followed by '.'.
Try correcting the name to refer to something other than a prefix, or renaming the prefix.

这是什么问题?为什么我无法在Flutter中从本地导入中读取JSON?

What is the problem here? why can't I read JSON from local import in flutter?

推荐答案

您应该考虑加载

You should look into loading assets in flutter. You can't simply import an arbitrary file. Importing is for source code/libraries.

您需要将此文件声明为pubspec.yaml

You need to declare this file as an asset in your pubspec.yaml

flutter:
  assets:
    - json_data.json

然后,您可以在代码中将此资产作为String加载:

Then in your code you can load this asset as a String:

import 'package:flutter/services.dart' show rootBundle;

Future<String> getJson() {
  return rootBundle.loadString('json_data.json');
}

您可以使用现有代码对JSON进行解码,但应将其放在方法主体中的某个位置.您调用此getJson函数以检索JSON字符串:

You can decode the JSON with your existing code, but it should be placed in a method body somewhere. You call this getJson function to retrieve the JSON String:

var my_data = json.decode(await getJson());


或者,您可以通过将JSON文件的内容直接作为String放入代码中来进一步简化此操作,但这可能无法实现,这取决于您打算将此JSON使用.


Alternatively, you could simplify this even further by putting the contents of your JSON file directly into the code as a String, but this may not be possible, it depends on your intended use of this JSON.

const String data = '''
{
  "foo" : "bar"
}
''';
var my_data = json.decode(data);

这篇关于如何在Flutter中读取本地JSON导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆