【问题标题】:Returns a Future<Dynamic> instead of Bool返回 Future<Dynamic> 而不是 Bool
【发布时间】:2020-09-11 01:53:28
【问题描述】:

我想在这个方法中返回一个布尔值,但它返回一个 Future

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(left: 0, right: 0, top: 110, bottom: 5),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    QuestionCards(),
                    cla().then((value) => { //this can't be add like this
                      YoutubeViewer(
                          videoId: 'hVQUbKs6qN8', topic: 'topic1'),
                    }
                  )
               ],
            ).
          ),
        ],
      ),
    );
  }

  Future<bool> cla() async {
    bool d = false;
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        print('connected');
        return Future<bool>.value(true);
      }
    } on SocketException catch (_) {
      print('not connected');
      return Future<bool>.value(false);
    }
  }

如果有人能告诉我这需要改变什么 这真的很有帮助 谢谢

【问题讨论】:

    标签: flutter dart async-await boolean


    【解决方案1】:

    使用 Future 对象返回 bool

    return Future<bool>.value(true);
    

    并修改方法如

    Future<bool> cla() async{
    

    像这样使用:

     cla().then((value) {
          // value will provide you true or false
        });
    

    【讨论】:

    • 我希望在 if 语句中输出,但是当我这样做时,它说条件必须有一个静态类型的 'bool'
    • 谢谢,但这可以在小部件中使用,对吧?它说“不能分配给列表类型的小部件”
    • @Thaanu:你能编辑你的问题并告诉我你是如何使用那里的
    • @Thaanu:我可以看到你没有在 YoutubeViewer 中使用 value 变量,实际上 value 是布尔类型,你可以使用 if 条件,比如 if(value) {} else {}跨度>
    【解决方案2】:
    Future<bool> cla() async {
        bool d=false;
        try {
          final result = await InternetAddress.lookup('google.com');
          if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
            print('connected');
            d= true;
          }
        } on SocketException catch (_) {
          print('not connected');
          d= false;
        }
       return d;
    }
    
    @override
    void initState() {
      super.initState();
      // calling cla function 
      setState(() async {
      var value = await getWeather();
      if(value){
       ...
      }
      });
    }
    

    您发现的观察结果是预期的。由于 cla() 函数内部的操作是异步的,并且该方法被标记为异步以返回未来的结果。那么你。将获得未来,并且要获得未来形式的结果,您必须对其调用 await ,如上所示。

    【讨论】:

    • 我希望在 if 语句中输出,但如何在 if 语句中添加它?
    【解决方案3】:
    Future<bool> cla() async{
     // function body goes here..
    }
    

    您可以显式定义方法的返回类型。

    【讨论】:

    • 我希望在 if 语句中输出,但是当我这样做时,它说条件必须有一个静态类型的 'bool'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多