I am really new to flutter and I consider myself as a total beginner in the world of Dart.

I have a local json file and I wanted to display the contents of it on my flutter app.

Here is a sample of my json:

{
"apple": {"color": "red", "tasty": "yes"},
"banana": {"color": "yellow", "tasty": "nope"}
}

So everytime the widget is created, I also load the json file using the initState method and decode then stored it on my Map object named fruits. Like this:

Future<Null> loadJson() async {
    var myJson = await rootBundle.loadString("files/fruits.json");
    Map<String, dynamic> fruits = json.decode(myJson);
}

@override
void initState(){
    super.initState();
    loadJson();
}

My problem is whenever I call the Map object fruits:

new Text("""${fruits["banana"]['color']}""")

It gave an error:

Error: Getter not found: 'fruits'.

Why can't I access the Map object from a method? Thanks in advance.


Solution 1: Dinesh Balasubramanian

fruits is a local variable. So it is not accessible outisde of loadJson method.

Make it state variable like

class YourStateClass extends State<YourStatefulWidget> {
  Map<String, dynamic> fruits; //state variable

  Future<Null> loadJson() async {
   var myJson = await rootBundle.loadString("files/fruits.json");
   fruits = json.decode(myJson);
   setState(() {}) // you might need this as it is async
 }

 @override
 void initState(){
  super.initState();
  loadJson();
 }
....
}