代码之家  ›  专栏  ›  技术社区  ›  harunB10

如何在Widget中使用Future<bool>

  •  0
  • harunB10  · 技术社区  · 5 年前

    我在我的提供者存储库中有一个未来的功能。不管怎样 Future<bool> 因为我需要 async 对于http请求。

    Future<bool> hasCard() async {
        String token = await getToken();
        var body = jsonEncode({"token": token, "userID": user.getUserID()});
    
        var res = await http.post((baseUrl + "/hasCard"), body: body, headers: {
          "Accept": "application/json",
          "content-type": "application/json"
        });
    
        print(res.toString());
    
        if (res.statusCode == 200) {
          this.paymentModel = PaymentModel.fromJson(json.decode(res.body));
          return true;
        }
        return false;
      }
    

    在我的小部件中,我想检查这个值:

    Widget build(BuildContext context) {
        var user = Provider.of<UserRepository>(context);
        if(user.hasCard())
        {
          //do something
        }
    

    但我收到一条错误信息:

    条件必须具有静态类型“bool”。dart(非bool条件)

    因为它是 Widget 异步

    0 回复  |  直到 5 年前
        1
  •  1
  •   Carlos Javier Córdova Reyes    5 年前

    你可以用 FutureBuilder ,它将根据 future 值,在 未来

    FutureBuilder(
      future: hasCard(),
      builder: (context, snapshot) {
        if (snapshot.data == null)
          return Container(
              width: 20,
              height: 20,
              child: CircularProgressIndicator());
        if (snapshot.data)
          return Icon(
            Icons.check,
            color: Colors.green,
          );
        else
          return Icon(
            Icons.cancel,
            color: Colors.red,
          );
      },
    )
    
        2
  •  0
  •   Javad Moradi    5 年前

    不仅仅是为了 Future<bool> FutureBuilder 其中,future是返回future类型的内容,snapshot是从future接收的数据。

      FutureBuilder(
          future: hasCard(),
          builder: (context, snapshot) {
            if (snapshot.data != null){
              print(snapshot.data)}
            else{
             print("returned data is null!")}  
          },
        )
    

    我建议给bool分配一个默认值。