How to read local json import in flutter?

你说的曾经没有我的故事 提交于 2020-12-30 04:11:33

问题


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

json_data.json:-

 {
    "foo" : "bar"
 }

I want to read this JSON on different files.

like

myfile.dart:-

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

I am getting the error:-

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.

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


回答1:


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

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

flutter:
  assets:
    - json_data.json

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

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());

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


来源:https://stackoverflow.com/questions/63653299/how-to-read-local-json-import-in-flutter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!