首页 > 解决方案 > 加载异步地图时传递空值

问题描述

我正在尝试将此地图作为下一页路线的值传递,但 MaterialApp 内的jsonResult中的值变为空值。

调试,可以看到地图中包含了模型的信息。但是,在 MaterialApp 号中,它只显示为 null:

  JjModel jmodel = JjModel();
  dynamic jsonResult;

  loadJson() async {
    Map<String, dynamic> mapInicial = jmodel.informacoesIniciais();
    final Directory _appDocDir = await getApplicationDocumentsDirectory();
    final Directory _appDocDirFolder =
        Directory('${_appDocDir.path}/fileSettings');

    File jsonFile = File('${_appDocDirFolder.path}/Preferences.json');

    if (await jsonFile.exists()) {
      String data = jsonFile.readAsStringSync();
      jsonResult = json.decode(data);
    } else {
      final Directory _appDocDirNewFolder =
          await _appDocDirFolder.create(recursive: true);
      File jsonFile = File('${_appDocDirNewFolder.path}/Preferences.json');
      jsonResult = mapInicial;
    }
    return jsonResult;
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Menu de Serviços',
      debugShowCheckedModeBanner: false,
      theme: androidTheme(),
      home: ServiceList(jsonResult: jsonResult),
    );
  }
}

标签: androidflutterdart

解决方案


您标记loadJsonasync这样它 MaterialApp创建后完成。MaterialApp用包装FutureBuilder,重构loadJson为返回值并将其设置为futureprop。然后snapshot.data用作ServiceList.

PS 建议阅读更多关于异步的内容。阅读此内容以开始https://www.woolha.com/articles/dart-event-loop-microtask-event-queue


推荐阅读