How to read local json 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);

Leave a Comment