Ahmed Wagdi
Ahmed Wagdi

Reputation: 4391

How to return a bool from a function that doesn't have a return statement at the end of the function in flutter

I have a function that should return a bool, but that bool is decided based on if statement which returns inside the if statement. Due to not having a return statement at the end of the function it returns null and the IDE shows this error :

This function has a return type of 'Future<bool>', but doesn't end with a return statement.
Try adding a return statement, or changing the return type to 'void'.dartmissing_return

here is my function :


  Future<bool> printSellTicket() async {
    PrinterBluetoothManager printerManager = PrinterBluetoothManager();
    printerManager.scanResults.listen(
      (printers) async {
      if (printers.length > 0) {
        printer = printers[0];
        printerManager.startScan(Duration(seconds: 4));
        printerManager.selectPrinter(printer);
        final PosPrintResult res =
            await printerManager.printTicket(prepareSellTicketData());
        print('Print result: ${res.msg}');
        return true;
      } else {
        return false;
      }
    }
    );
  }

Upvotes: 0

Views: 130

Answers (2)

HII
HII

Reputation: 4109

You can remove the else-block,and keep the return false after the if-block, as this return will never be reached if the if-block is executed

 Future<bool> printSellTicket() async {
    PrinterBluetoothManager printerManager = PrinterBluetoothManager();
    printerManager.scanResults.listen(
      (printers) async {
      if (printers.length > 0) {
        printer = printers[0];
        printerManager.startScan(Duration(seconds: 4));
        printerManager.selectPrinter(printer);
        final PosPrintResult res =
            await printerManager.printTicket(prepareSellTicketData());
        print('Print result: ${res.msg}');
        return true;
      } 

     return false;
    }
    );
  }

Upvotes: 1

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27147

You can remove return type and it will work for you.

if you return value(true/false) then it will return other wise it don’t.

Upvotes: 0

Related Questions