首页 文章

从方法访问Map对象到构建方法

提问于
浏览
1

我真的很陌生,我认为自己是Dart世界的初学者 .

我有一个本地json文件,我想在我的flutter应用程序上显示它的内容 .

这是我的json样本:

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

因此,每次创建窗口小部件时,我还使用initState方法加载json文件并解码,然后将其存储在名为fruits的Map对象上 . 像这样:

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

我的问题是每当我调用Map对象时果子:

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

它给出了一个错误:

Error: Getter not found: 'fruits'.

为什么我不能从方法中访问Map对象?提前致谢 .

1 回答

  • 0

    fruits 是一个局部变量 . 因此,它无法通过 loadJson 方法进行访问 .

    让它 state variable 喜欢

    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();
     }
    ....
    }
    

相关问题