简体   繁体   中英

How to read local json import in flutter?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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