Returns a Future<Dynamic> instead of Bool

Viewed 1457

I want to return a bool in this method but it return a 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);
    }
  }

If someone can tell me that what need to be changed in this It would be really helpful Thank you

3 Answers

Return bool using Future object

return Future<bool>.value(true);

and modify method like

Future<bool> cla() async{

Use like:

 cla().then((value) {
      // value will provide you true or false
    });
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){
   ...
  }
  });
}

The observation you found is expected. Since the operation inside cla() function is async and the method is marked as async to return the future result. So you. will get future and to get the result form future you have to call await on it as shown above.

Future<bool> cla() async{
 // function body goes here..
}

you can explicitly define return type of the method.

Related