NoSuchMethodError:在空调用getter“姓”

时间:2019-04-02 09:41:06

标签: android json flutter response

我正在使用自定义login运行BaaS进程。提交按钮运行onPressed方法,该方法检查Response response; if reponse.statusCode == 200,然后将fromJson(reponse.data).surnamefromJson(response.data).firstname发送到Homepage屏幕。我已经设置了Homepage屏幕的段落,并且可以运行,但是当我尝试Hot Reload应用程序然后尝试访问首页时,它抛出了NoSuchMethodError I/flutter (14935): The getter 'surname' was called on null.我该如何解决这个问题吗?

我尝试将widget.data.surname中的string分配给initState中的随机widget.data.surname,它可以清除错误,但不会重新分配widget.data.firstname和{{ 1}}至fromJson(reponse.data).surnamefromJson(response.data).firstname

class Data
{
  String surname = '';
  String firstname= '';

  Data ({this.surname, this.firstname});
}
Response response;
          Dio dio = new Dio();
          response = await dio.get(findUrl, queryParameters: {"username": _username, "password": _password});
          print(response.statusCode);

          if(response.statusCode == 200){
            print(UsersInfo.fromJson(response.data).surname);

            userSurname = UsersInfo.fromJson(response.data).surname;

            userFirstname = UsersInfo.fromJson(response.data).firstname;

            var data = Data (
              surname: userSurname,
              firstname: userFirstname
            );

            Fluttertoast.showToast(
                msg: "Login successful",
                toastLength: Toast.LENGTH_LONG,
                gravity: ToastGravity.BOTTOM,
                timeInSecForIos: 6,
                backgroundColor: Colors.black,
                textColor: Colors.white,
                fontSize: 16.0
            );

            Future.delayed (Duration(seconds: 7),
                    () async {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => HomePage(data: data))
                  );
                  print('7 seconds');
                }
            );
          }

第二屏幕(主页屏幕)

Data data;

  HomePage ({this.data});
enum AuthStatus {
  notSignedIn,
  signedIn
}
AuthStatus _authStatus = AuthStatus.notSignedIn;

  @override
  initState() {
    super.initState();
    setState(() {
      widget.data = Data (surname: '', firstname: '');
       _authStatus = ((widget.data.surname == '')) ? AuthStatus.notSignedIn : AuthStatus.signedIn;
    });
  }

1 个答案:

答案 0 :(得分:0)

小部件中的数据是最终数据。如果在其中更改一个版本,请保持其状态不变。然后在initState中执行以下操作:

_data = widget.data ?? Data();

编辑:我遗漏了重要的笔记。不要在initState中调用setState,它尚未构建,并且您设置的任何数据都会在第一次绘制时出现。

并更改Data类,使其具有默认参数:

class Data{
  final String surname;
  final String firstname;

  Data ({this.surname = '', this.firstname = ''});
}

或者您甚至可以添加从UsersInfo对象提取的工厂:

Data.fromUsersInfo(UsersInfo info) : firstname = info.firstname, surname = info.surname;

然后在onPressed方法中,您可以使用以下方法制作数据:

var data = Data.fromUsersInfo(UsersInfo.fromJson(response.data));

我不确定您对这些数据还有什么用,但这应该可以工作:)