【问题标题】:Access a Map object from a method to the build method从方法访问 Map 对象到 build 方法
【发布时间】:2018-09-02 00:30:23
【问题描述】:

我真的是 Flutter 的新手,我认为自己是 Dart 世界的初学者。

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

这是我的 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 对象? 提前致谢。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      相关资源
      最近更新 更多