Home > Enterprise >  Flutter: type 'Future<bool?>' is not a subtype of type 'FutureOr<bool>�
Flutter: type 'Future<bool?>' is not a subtype of type 'FutureOr<bool>�

Time:12-29

I'm new on the Flutter & working on the integration of POS printing machine in flutter & using the pos_printer_manager package.

It shows an error in the catch part of this package i.e. type 'Future<bool?>' is not a subtype of type 'FutureOr<bool>' in type cast

& pointing out in this code

/// [writeBytes] let you write raw list int data into socket
  @override
  Future<ConnectionResponse> writeBytes(List<int> data,
      {bool isDisconnect: true}) async {
    try {
      if (!isConnected) {
        await connect();
      }
      if (Platform.isAndroid || Platform.isIOS) {
        if ((await (bluetooth.isConnected as FutureOr<bool>))) {
          Uint8List message = Uint8List.fromList(data);
          PosPrinterManager.logger.warning("message.length ${message.length}");
          await bluetooth.writeBytes(message);
          if (isDisconnect) {
            await disconnect();
          }
          return ConnectionResponse.success;
        }
        return ConnectionResponse.printerNotConnected;
      }
      //  else if (Platform.isIOS) {
      //   // var services = (await fbdevice.discoverServices());
      //   // var service = services.firstWhere((e) => e.isPrimary);
      //   // var charactor =
      //   //     service.characteristics.firstWhere((e) => e.properties.write);
      //   // await charactor?.write(data, withoutResponse: true);
      //   return ConnectionResponse.success;
      // }
      return ConnectionResponse.unsupport;
    } catch (e) {
      print("Error : $e");
      return ConnectionResponse.unknown;
    }
  }

This is due to bluetooth.isConnected as FutureOr<bool>.

So any big difference between Future<bool?> & FutureOr<bool> ?

Basically I faced type casting error in the package & I need a solution to handle this on the package side & how to manage the optional.

CodePudding user response:

Based on your findings typecast is not required, it requires a null check

change this it to

if (Platform.isAndroid || Platform.isIOS) {
         bool? isConnected  = await bluetooth.isConnected;
        if (isConnected != null && isConnected!) {
          Uint8List message = Uint8List.fromList(data);
          PosPrinterManager.logger.warning("message.length ${message.length}");
          await bluetooth.writeBytes(message);
          if (isDisconnect) {
            await disconnect();
          }
          return ConnectionResponse.success;
        }
        return ConnectionResponse.printerNotConnected;
      }

CodePudding user response:

Resolved it by a simple check:

bool? btConnected = await bluetooth.isConnected ?? false;
  • Related