rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

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?

Upvotes: 20

Views: 36980

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17143

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

Upvotes: 48

Related Questions