【问题标题】:Variable return null when i load json file the first time [duplicate]当我第一次加载 json 文件时,变量返回 null [重复]
【发布时间】:2021-08-29 14:02:39
【问题描述】:

我的代码工作正常,但我不知道为什么变量:Map dataJsonObject; 当我使用 adb 构建我的应用程序时返回“null”(在 android studio 代码中) )。 但是,如果我执行 hot reloadhot restart,我的变量“dataJsonObject” 给我正确的值。当我第一次构建代码时,如何获得正确的值以返回给我。 谢谢

我的代码

import 'package:flutter/material.dart';
import 'dart:convert'; //(jsonDecode)
import 'package:flutter/services.dart'; // (loadJson)
import 'package:flutter/foundation.dart'; //(debugPrint)

class ProverbDisplay extends StatefulWidget {
  final int myId;
  final String myCountry;
  const ProverbDisplay(this.myId, this.myCountry);

  @override
  _ProverbDisplayState createState() => _ProverbDisplayState();
}

class _ProverbDisplayState extends State<ProverbDisplay> {
  Map<String, dynamic> dataJsonObject;

  //Get JSON
  Future getJsonProverb() async {
    final String rawJson = await rootBundle.loadString('assets/json/data.json');
    dataJsonObject = await jsonDecode(rawJson);
    return dataJsonObject;
  }

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

  @override
  Widget build(BuildContext context) {
    debugPrint(' jsonData : $dataJsonObject'); //Return null

    return Container(
      color: Colors.blue,
      height: 250,
      child: Row(
        children: [
          Container(
            width: 300,
            child: PageView.builder(itemBuilder: (context, index) {
              return Text("$dataJsonObject");
            }),
          ),
        ],
      ),
    );
  }
}


【问题讨论】:

    标签: flutter dart future


    【解决方案1】:

    您正在初始化状态下执行getJsonProverb(),但该函数可能在您的构建函数运行之前无法完成。由于函数尚未完成,dataJsonObject 仍可能为空。你应该做的是确保你的未来完成,然后只渲染小部件。您可以通过使用未来的构建器来实现这一点。以下是我将如何重写您的代码:

    import 'dart:convert'; //(jsonDecode)
    
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart'; // (loadJson)
    
    class ProverbDisplay extends StatefulWidget {
      final int myId;
      final String myCountry;
    
      const ProverbDisplay(this.myId, this.myCountry);
    
      @override
      _ProverbDisplayState createState() => _ProverbDisplayState();
    }
    
    class _ProverbDisplayState extends State<ProverbDisplay> {
      Future getJsonProverbFuture = getJsonProverb();
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
            future: getJsonProverbFuture,
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return Text('Loading...');
              } else {
                return Container(
                  color: Colors.blue,
                  height: 250,
                  child: Row(
                    children: [
                      Container(
                        width: 300,
                        child: PageView.builder(itemBuilder: (context, index) {
                          return Text("${snapshot.data}");
                        }),
                      ),
                    ],
                  ),
                );
              }
            });
      }
    }
    
    //Get JSON
    Future getJsonProverb() async {
      final String rawJson = await rootBundle.loadString('assets/json/data.json');
      return await jsonDecode(rawJson);
    }
    

    更多关于未来建设者的信息https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

    【讨论】:

    • 你不应该在构建方法中调用异步函数。创建一个变量并将future保存到该变量中,然后在build方法中使用该变量。否则,该方法将被多次调用,因为构建函数可能会被多次调用。
    • 我同意,将编辑它谢谢@nvoigt
    猜你喜欢
    • 2015-08-31
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多