个人资料登录后返回null

时间:2018-12-09 18:18:57

标签: dart flutter

我开发了单独的类来调用API。在此过程中,我为Web API调用,模型类和一个登录屏幕开发了单独的类。从登录屏幕,我正在调用API类,并且从中成功登录。但是我想从那里检索配置文件数据。 哪一个返回null给我。

在这里供您参考的是我从其中调用API类的登录类代码的代码

    //Login Button
    final loginButton = ButtonTheme(
      minWidth: MediaQuery.of(context).size.width-40,
      height: 50.0,
      child: new RaisedButton(
          color: blueColor,
          onPressed: (){
            foo();
          },
          child: Text('Log In',
            style: styleLoginButton,
          ),
          shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
          ),
      );

     void foo() async{
      print('foo called');
      final profile = await LoginAPI().profileGetRequest();
      print(profile.firstName);
    }

API类

class LoginAPI {

  Future<Profile> profileGetRequest() async {
    try {
      String strUserName = "test@tester.ch";
      String strPassword = "tester";
      String basicAuth = 'Basic ' +
          base64Encode(utf8.encode('$strUserName:$strPassword'));
      String strURL = Config.API_URL + Config.PROFILE;
      final response = await http.get(
        strURL,
        headers: {
          "Authorization": basicAuth,
          "Content-Type": "application/json"
        },
      );
      if (response.statusCode == 200) {
        final responseJson = json.decode(response.body);
        return Profile.fromJson(responseJson);
      }
      else {
        return Profile.fromError(json.decode(response.body));
      }
    } catch (exception) {
      print('exception $exception');
      return null;
    }
  }
}

个人资料模型

class Profile{
  final int userId;
  final String firstName;
  final String lastName;
  final String gender;


  Profile(
      this.userId,
      this.firstName,
      this.lastName,
      this.gender
  );

  //Profile when Error received
  Profile.fromError(Map<String, dynamic> json):
        userId = 0,
        firstName = null,
        lastName = null,
        gender = null;

  //Profile when No Error Received
  Profile.fromJson(Map<String, dynamic> json):
        userId = json['userId'],
        firstName = json['firstName'],
        lastName = json['lastName'],
        gender = json['gender'];
}

1 个答案:

答案 0 :(得分:1)

地图键不匹配,您必须像这样更改键

firstName ---> firstname
lastName ---> lastname

使用下面的代码

//Profile when No Error Received
  Profile.fromJson(Map<String, dynamic> json):
        userId = json['userId'],
        firstName = json['firstname'],
        lastName = json['lastname'],
        gender = json['gender'];
相关问题