【问题标题】:Flutter type 'String' is not subtype of type 'FutureOr<Model>' , Response Json Without KeyFlutter 类型 'String' 不是类型 'FutureOr<Model>' 的子类型,响应 Json 没有键
【发布时间】:2021-05-06 12:44:25
【问题描述】:

我正在尝试这样调用服务,我认为这里有问题,因为“结果”返回 Future 并且无法分配给 String,或者如何将 Future 解析为 String? 和 MyApi 返回 Json 没有 Key 这样的东西

身体

ReturnStatus

所以我试图将响应直接存储到用户变量中,但仍然无法正常工作

UI(按钮登录)

login.loginProcess
    ? Center(child: CircularProgressIndicator())
    : RaisedButton(
        color: myPrimaryColor,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8)),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Login",
                style: TextStyle(
                    color: Colors.black,
                    fontFamily: "NunitoSansBold")),
          ],
        ),
        padding:
            EdgeInsets.only(top: 16.0, bottom: 16.0),
        onPressed: () {
          print("clicked Button Login");
          **login.authenticationUser(context);**
        },
      ),

服务

class AuthService {
  Future<User> authenticateUser(String id, String password) async {
    var user;
    try {
      final resAuth = await http.post(
        "${BaseUrl.auth}api/AuthenticateUser",
        body: {"login": id, "password": password},
      );
      if (resAuth.statusCode == 200) {
        user = resAuth.body;
      }
    } catch (e) {
      return user;
    }
    return user;
  }
}

带有 ChangeNotifier 的提供程序(用于处理业务逻辑和 stuf)

authenticationUser(BuildContext context) async {
  if (_controllerEmail.text != "" && _controllerPassword.text != "") {
    loginProcess = true;
    final ioc = new HttpClient();
    ioc.badCertificateCallback =
        (X509Certificate cert, String host, int port) => true;
    //TODO StoredSharedPreference
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    try {
      AuthService authService = new AuthService();
      var result = authService.authenticateUser(
          _controllerEmail.text, _controllerPassword.text);
      showSnackBar(result);
      _preferences.setString("status", "seen");
    } catch (e) {
      print(e);
      showSnackBar(result.toString());
    }
    loginProcess = false;
  } else {
    autoValidate = true;
  }
} 

型号

class User {
  String status;
  String id;
  String userName;

  User({
    this.status,
    this.id,
    this.userName,
  });

  factory User.fromJson(Map<String, dynamic> json) =>
      User(status: json["status"], id: json["id"], userName: json["userName"]);

  Map<String, dynamic> toJson() =>
      {"status": status, "id": id, "userName": userName};
}

=======UPDATE,更改方法 authenticationUser(添加等待)=======

服务

class AuthService {
  Future<User> authenticateUser(String id, String password) async {
    var user;
    try {
      final resAuth = await http.post(
        "${BaseUrl.auth}api/AuthenticateUser",
        body: {"login": id, "password": password},
      );
      if (resAuth.statusCode == 200) {
        user = resAuth.body;
      }
    } catch (e) {
      return user;
      // throw Exception(e.toString());
    }
    return user;
  }
}

提供者

authenticationUser(BuildContext context) async {
    if (_controllerEmail.text != "" && _controllerPassword.text != "") {
      loginProcess = true;
      final ioc = new HttpClient();
      ioc.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
      //TODO StoredSharedPreference
      SharedPreferences _preferences = await SharedPreferences.getInstance();
      try {
        AuthService authService = new AuthService();
        var result = await authService.authenticateUser(
            _controllerEmail.text, _controllerPassword.text);
        _preferences.setString("status", "seen");
        showSnackBar(result.toString());
      } catch (e) {
        print(e);
        /* showSnackBar(e.toString());*/
      }
      loginProcess = false;
    } else {
      autoValidate = true;
    }
  }

在捕获 (e) { 打印(e);

e 的值为 String' is not a subtype of type 'FutureOr&lt;User&gt;'

==从 resAuth 更新添加图像值==

resAuthValue

【问题讨论】:

    标签: flutter dart async-await future provider


    【解决方案1】:

    您可能需要添加await

    var result = await authService.authenticateUser(
              _controllerEmail.text, _controllerPassword.text);
    

    编辑

    将您的 authenticateUser 方法更改为此

    Future authenticateUser(String id, String password) async {
        var user;
        try {
          final resAuth = await http.post(
            "${BaseUrl.auth}api/AuthenticateUser",
            body: {"login": id, "password": password},
          );
          if (resAuth.statusCode == 200) {
            return resAuth.body;
          }
        } catch (e) {
         return false;
        }
        return false;
      }
    

    如下更改提供者代码

     try {
            AuthService authService = new AuthService();
            var result = await authService.authenticateUser(
                _controllerEmail.text, _controllerPassword.text);
            _preferences.setString("status", "seen");
            if(result!=false)
            showSnackBar(result.toString());
          } catch (e) {
            print(e);
            /* showSnackBar(e.toString());*/
          }
    

    【讨论】:

    • 尝试添加等待,现在我无法在方法 authenticationUser 上执行 try-catch 时存储用户值,通过捕获并获取类型 'String' 不是类型 'FutureOr 的子类型'
    • 请通过粘贴最新代码和错误来更新您的帖子。
    • print(e.toString()); 可以解决问题。
    • 得到相同的结果 catch (e) { print(e.toString());
    • 你能在AuthService 中打印resAuth 吗?看看你得到了什么价值。
    猜你喜欢
    • 2020-11-26
    • 2022-11-14
    • 1970-01-01
    • 2021-09-07
    • 2021-01-13
    • 2022-07-21
    • 2021-08-02
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多