Search code examples
flutterdartbluetooth-lowenergy

Return of invalid type but don't know why? Flutter/Dart


Hey I am totally new to flutter and lately I've been working on a mobile app which recieves data from the ESP32 via BLE but I got the problem that if I wanna ask the user to disconnect with the device like this:

Future<bool> _onWillPop() {
    return showDialog(
        context: context,
        builder: (context) =>
            new AlertDialog(
              title: Text('Are you sure?'),
              content: Text('Do you want to disconnect device 
              and go back?'),

             actions: <Widget>[
                new ElevatedButton(
                    onPressed: () => 
                      Navigator.of(context).pop(false),
                    child: new Text('No')),
                new ElevatedButton(
                    onPressed: () {
                      disconnectFromDevice();
                      Navigator.of(context).pop(true);
                    },
                    child: new Text('Yes')),
              ],
            ) ??
            false);
  }

It gives me the error warnings:

A value of type 'Future<dynamic>' can't be returned from the method '_onWillPop' because it has a return type of 'Future<bool>'.

The return type 'Object' isn't a 'Widget', as required by the closure's context.

But with my current knowlegde I don't know how to solve my problem. I would be extremly thankful if somebody could help me :) and sorry for any grammar mistakes


Solution

  • The error says that the return type of showDialog is not bool. Instead you can just replace with await and then return the bool.

    Below is a code which you can put up.

    Future<bool> _onWillPop(BuildContext context) async {
        bool shouldPop = false;
        await showDialog(
            context: context,
            builder: (context) =>
                AlertDialog(
                  title: const Text('Are you sure?'),
                  content: const Text('Do you want to disconnect device and go back?'),
                 actions: <Widget>[
                    ElevatedButton(
                        onPressed: () {
                          // shouldPop is already false
                        },
                        child: const Text('No')),
                    ElevatedButton(
                        onPressed: () async {
                          await disconnectFromDevice();
                          Navigator.of(context).pop();
                          shouldPop = true;
                        },
                        child: const Text('Yes')),
                  ],
                ));
        return shouldPop;
      }
    

    I have changed the code a bit so that it returns false if you don't want to pop and returns true if you want to pop. You can just change the code as per your requirement.