Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read local json import in flutter?

Tags:

json

flutter

dart

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?

like image 847
rahul Kushwaha Avatar asked Aug 30 '20 01:08

rahul Kushwaha


People also ask

How do I read local JSON in flutter?

The code which is used to fetch data from the JSON file (see the full code below): Future<void> readJson() async { final String response = await rootBundle. loadString('assets/sample. json'); final data = await json.

How do you call a JSON in flutter?

Step 1: Create a project in Vs code, And remove the default code. Step 2: Before writing the code just add the HTTP plugin in your pubspec yaml file. Step 3: In main. dart file call the main() function , inside it run the runApp( ) method and give it an App (MyApp).


1 Answers

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);
like image 154
Christopher Moore Avatar answered Oct 02 '22 21:10

Christopher Moore