kakzaki / blue_thermal_printer

Working with thermal printer via bluetooth (Flutter)
MIT License
166 stars 211 forks source link

(MethodCall) => Null' is not a subtype of type '((MethodCall) => Future<dynamic>)?' #70

Closed excode closed 3 years ago

excode commented 3 years ago

he following _CastError was thrown building Builder: type '(MethodCall) => Null' is not a subtype of type '((MethodCall) => Future)?' in type cast

The relevant error-causing widget was MaterialApp-[#3d82a]

When the exception was thrown, this was the stack

0 new BlueThermalPrinter._

package:blue_thermal_printer/blue_thermal_printer.dart:39

1 BlueThermalPrinter._instance

package:blue_thermal_printer/blue_thermal_printer.dart:42

STUCK IN THIS issue please help.

Thank you

kakzaki commented 3 years ago

thanks for the information, i fixed it at ver 1.1.3

excode commented 3 years ago

Hello still getting the same error

version updated in pubspec flutter clean then debug

Still same error

type '(MethodCall) => Null' is not a subtype of type '((MethodCall) => Future)?' in type cast

The relevant error-causing widget was MaterialApp-[#889c1]

type '(MethodCall) => Null' is not a subtype of type '((MethodCall) => Future)?' in type cast

The relevant error-causing widget was MaterialApp-[#889c1] lib/…/jounalHome/JournalHome.dart:96 When the exception was thrown, this was the stack

0 new BlueThermalPrinter._

package:blue_thermal_printer/blue_thermal_printer.dart:37

1 BlueThermalPrinter._instance

package:blue_thermal_printer/blue_thermal_printer.dart:40

2 BlueThermalPrinter._instance (package:blue_thermal_printer/blue_thermal_printer.dart)

package:blue_thermal_printer/blue_thermal_printer.dart:1

3 BlueThermalPrinter.instance

package:blue_thermal_printer/blue_thermal_printer.dart:42

4 new _MedicineDetailsState

package:mypaaa/…/medicine/medicine_details.dart:45 ...

excode commented 3 years ago
Screenshot 2021-03-25 at 3 18 05 PM
kakzaki commented 3 years ago

can you run the example code?

excode commented 3 years ago

import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:mypaaa/blocs/appointment/appointment.dart'; import 'package:mypaaa/blocs/authentication/user_repository.dart'; import 'package:mypaaa/blocs/medicine/bloc.dart'; import 'package:mypaaa/blocs/journal/journal.dart'; import 'package:mypaaa/serviceLocator.dart'; import 'package:mypaaa/utils/allTranslation.dart'; import 'package:mypaaa/widgets/form-inputs/Loading.dart'; import 'package:mypaaa/widgets/ui_elements/PrescriptionData.dart'; import 'package:flutter/services.dart'; import 'package:blue_thermal_printer/blue_thermal_printer.dart'; import 'dart:io'; import 'package:mypaaa/utils/country_codes.dart' as countryList; import 'package:mypaaa/utils/printing.dart';

class MedicineDetails extends StatefulWidget { final Journal journal; final Appointment appointment; MedicineDetails({ required this.journal, required this.appointment, }); @override State createState() => _MedicineDetailsState(); }

class _MedicineDetailsState extends State { BlueThermalPrinter bluetooth = BlueThermalPrinter.instance;

List _devices = []; late BluetoothDevice _device; bool _connected = false; bool _pressed = false; bool _showDropDown = false; String pathImage = ''; String username = ""; String usernameMasked = ""; String currencyCode = ""; Printing printing = Printing(); MedicineBloc _medicineBloc = locator.get(); @override void initState() { super.initState();

initPlatformState();

initSavetoPath();

}

initSavetoPath() async {

Map<String, String> user = await UserRepository().getRegistrationPhone();

setState(() {
  //pathImage = '$dir/$filename';
  username = user["phone"] ?? '';
  usernameMasked = username.replaceRange(2, 10, ".");

  Map<String, dynamic> _countryMapMap =
      countryList.getCountryCodes(widget.journal.currency, "curSymbol");
  if (_countryMapMap["curCode"] != null) {
    currencyCode = _countryMapMap["curCode"] ?? "USD";
  } else {
    currencyCode = "USD";
  }
});

}

void load() { _medicineBloc.add(SearchMedicineEvent( pageno: 0, searchWord: "", isReport: 1, journalId: widget.journal.id, appointmentId: widget.appointment.id)); }

@override Widget build(BuildContext contextFrm) { //print("###sdsdsdsdsds####"); return Scaffold( resizeToAvoidBottomInset: true, appBar: AppBar( title: Text(widget.appointment.name + " " + widget.appointment.age.toString() + "/" + widget.appointment.genderChar), ), body: Container( width: MediaQuery.of(context).size.width, child: BlocBuilder( bloc: _medicineBloc, builder: (context, state) { if (state is MedicineLoading) { if (state.journalId != widget.journal.id || state.appointmentId != widget.appointment.id || state.isReport == 0) { load(); } return Loading(); } else if (state is MedicineInitial) { load();

              return Text("");
            } else if (state is MedicineLoaded) {
              if (state.journalId != widget.journal.id ||
                  state.appointmentId != widget.appointment.id ||
                  state.isReport == 0) {
                load();
                return Text("");
              } else {
                return SingleChildScrollView(
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          // if (_showDropDown)
                          DropdownButton(
                            items: _getDeviceItems(),
                            onChanged: (BluetoothDevice? value) =>
                                setState(() {
                              if (value != null) {
                                _device = value;

                                _showDropDown = true;
                              }
                            }),
                            value: _device,
                          ),
                          RaisedButton(
                            onPressed: _pressed
                                ? null
                                : _connected
                                    ? _disconnect
                                    : _connect,
                            child:
                                Text(_connected ? 'Disconnect' : 'Connect'),
                          ),
                          RaisedButton(
                            onPressed: _connected
                                ? () {
                                    initPlatformState();
                                    printing.printBluetoothPrescription(
                                        bluetooth,
                                        currencyCode,
                                        usernameMasked,
                                        widget.journal,
                                        state.medicine,
                                        widget.appointment);
                                  }
                                : null,
                            child: Text(allTranslations.text("print")),
                          ),
                        ],
                      ),
                      PrescriptionData(
                          journal: widget.journal,
                          data: state.medicine,
                          appointment: widget.appointment,
                          printMode: true),
                    ],
                  ),
                );
              }
            } else {
              return Text("");
            }
          }),
    ));

}

Future initPlatformState() async { List devices = [];

try {
  devices = await bluetooth.getBondedDevices();
} on PlatformException {
  // TODO - Error
}

bluetooth.onStateChanged().listen((state) {
  switch (state) {
    case BlueThermalPrinter.CONNECTED:
      setState(() {
        _connected = true;
        _pressed = false;
      });
      break;
    case BlueThermalPrinter.DISCONNECTED:
      setState(() {
        _connected = false;
        _pressed = false;
      });
      break;
    default:
      print(state);
      break;
  }
});

if (!mounted) return;
setState(() {
  _devices = devices;
});

}

List<DropdownMenuItem> _getDeviceItems() { List<DropdownMenuItem> items = []; if (_devices.isEmpty) { items.add(DropdownMenuItem( child: Text('NONE'), )); } else { _devices.forEach((device) { items.add(DropdownMenuItem( child: Text(device.name ?? ''), value: device, )); }); } return items; }

void _connect() { if (_device == null) { show('No device selected.'); } else { bluetooth.isConnected.then((isConnected) { if (isConnected == false) { bluetooth.connect(_device).catchError((error) { setState(() => _pressed = false); }); setState(() => _pressed = true); } }); } }

void _disconnect() { bluetooth.disconnect(); setState(() => _pressed = true); }

//write to app path Future writeToFile(ByteData data, String path) { final buffer = data.buffer; return new File(path).writeAsBytes( buffer.asUint8List(data.offsetInBytes, data.lengthInBytes)); }

Future show( String message, { Duration duration: const Duration(seconds: 3), }) async { await new Future.delayed(new Duration(milliseconds: 100)); Scaffold.of(context).showSnackBar( new SnackBar( content: new Text( message, style: new TextStyle( color: Colors.white, ), ), duration: duration, ), ); }

@override void dispose() { bluetooth.disconnect(); //bluetooth = null; super.dispose(); } }

==========================

printing.dart

import 'dart:convert';

import 'package:intl/intl.dart'; import 'package:blue_thermal_printer/blue_thermal_printer.dart'; import 'package:mypaaa/blocs/appointment/appointment.dart'; import 'package:mypaaa/blocs/invoice/invoice.dart'; import 'package:mypaaa/blocs/invoiceproduct/invoiceproduct.dart'; import 'package:mypaaa/blocs/journal/journal.dart'; import 'package:mypaaa/blocs/medicine/medicine.dart'; import 'package:mypaaa/blocs/productblog/address.dart'; import 'package:mypaaa/blocs/productblog/jconfig.dart'; import 'package:mypaaa/utils/allTranslation.dart'; import 'package:mypaaa/utils/config.dart'; import 'package:mypaaa/utils/helper.dart';

class Printing { void printBluetooth( BlueThermalPrinter bluetooth, String currencyCode, String usernameMasked, Journal journal, List listData, Invoice invoice, [String qrCode = '', String paidAmount = '', String returnAmount = '']) async { JConfig jConfig = JConfig.fromMap(json.decode(journal.config)); Address address = Address.fromMap(json.decode(journal.address)); InvoiceProduct item; String lft, rgt; double subTotal, itemTotal; String line = "--------------------------------"; //String itemLine = ". . . . . . . . ."; itemTotal = 0; bluetooth.isConnected.then((isConnected) { if (isConnected == true) { bluetooth.printCustom(journal.title, 1, 1); bluetooth.printCustom(address.address, 0, 1); bluetooth.printCustom( address.city + " " + address.state + " " + address.country, 0, 1); bluetooth.printCustom(journal.enterBy, 0, 1);

    bluetooth.printNewLine();
    bluetooth.printCustom(invoice.businessName, 0, 0);
    bluetooth.printCustom(invoice.contactNumber, 0, 0);
    if (invoice.invoiceType == 1) {
      if (invoice.invoiceInfos.dtype == OrderModes.home) {
        if (invoice.territory.length > 0) {
          bluetooth.printCustom(invoice.invoiceInfos.hourseRoadNo, 0, 0);
          //bluetooth.printCustom(invoice.territory, 0, 0);
        }
        if (invoice.destinationAddress.length > 0) {
          // bluetooth.printCustom(invoice.territory, 0, 0);
          bluetooth.printCustom(
              invoice.invoiceInfos.address +
                  " " +
                  invoice.invoiceInfos.city +
                  " " +
                  invoice.invoiceInfos.country +
                  " " +
                  invoice.invoiceInfos.postcode,
              0,
              0);
        }
        if (invoice.latitude > 0 && invoice.longitude > 0) {
          String locationCode = invoice.latitude.toString() +
              "#MyPaaaLoc#" +
              invoice.longitude.toString();
          bluetooth.printQRcode(locationCode, 250, 250, 1);
        }
      }
    }

    bluetooth.printLeftRight(invoice.invoiceId, invoice.date, 0);
    bluetooth.printCustom(line, 1, 1);
    // bluetooth.printNewLine();
    int counter = 0;
    for (int i = 0; i < listData.length; i++) {
      counter = i + 1;
      item = listData[i];
      lft = item.quantity.toString() +
          " " +
          item.unitName +
          " x " +
          item.unitPrice.toString();
      subTotal = item.quantity * item.unitPrice;
      itemTotal += subTotal;
      rgt = subTotal.toStringAsFixed(2);
      bluetooth.printCustom(
          counter.toString() + ") " + item.productName, 0, 0);
      //bluetooth.printCustom("Unit:" + item.unitName, 1, 0);
      bluetooth.printLeftRight(lft, rgt, 0);
      //bluetooth.printLeftRight(itemLine, "", 0);
    }
    bluetooth.printCustom(line, 1, 1);
    bluetooth.printLeftRight("Sub", itemTotal.toString(), 1);
    if (invoice.gst > 0) {
      bluetooth.printCustom(jConfig.tax_label, 1, 0);
      bluetooth.printLeftRight(
          jConfig.tax + " % ", invoice.gst.toStringAsFixed(2), 0);
    }
    if (invoice.discount > 0) {
      bluetooth.printCustom(jConfig.discount_label, 1, 0);
      bluetooth.printLeftRight(
          jConfig.discount + " % ", invoice.discount.toStringAsFixed(2), 0);
    }
    if (invoice.others > 0) {
      bluetooth.printCustom(jConfig.other_label, 1, 0);
      bluetooth.printLeftRight(
          jConfig.other + " % ", invoice.others.toStringAsFixed(2), 0);
    }
    bluetooth.printCustom(line, 1, 1);
    bluetooth.printLeftRight(
        "Total", invoice.finalPrice.toStringAsFixed(2), 1);
    if (paidAmount.length > 0) {
      bluetooth.printLeftRight("Payment", paidAmount, 1);
      bluetooth.printLeftRight("Change", returnAmount, 1);
    }
    bluetooth.printNewLine();
    bluetooth.printCustom(
        Helper().formatCurrency(invoice.finalPrice, currencyCode + " "),
        1,
        1);
    bluetooth.printNewLine();
    bluetooth.printCustom("Thank you!", 2, 1);
    if (qrCode.length > 10) {
      bluetooth.printQRcode(qrCode, 250, 250, 1);
    }
    DateFormat printTimeFormat =
        DateFormat('dd/MM/yyyy').add_jm(); // DateFormat.yMd().add_jm();
    String printTime =
        printTimeFormat.format(DateTime.now()).toString().trim();
    bluetooth.printLeftRight(printTime, usernameMasked.trim(), 0);
    //bluetooth.printCustom(line, 1, 1);
    bluetooth.printCustom("MyPaaa a product from ExCode.Net", 0, 1);
    //bluetooth.printLeftRight(DateTime.now().toIso8601String(), '', 1);
    bluetooth.printNewLine();
    //bluetooth.printNewLine();
    bluetooth.paperCut();
  }
});

}

void printBluetoothPrescription( BlueThermalPrinter bluetooth, String currencyCode, String usernameMasked, Journal journal, List listData, Appointment appointment, [String qrCode = '']) async { JConfig jConfig = JConfig.fromMap(json.decode(journal.config)); Address address = Address.fromMap(json.decode(journal.address)); Medicine item; List plist = MedProcedures.list; String lft, rgt; String subTotal, itemTotal; String line = "--------------------------------"; String line2 = ". . . . . . . . . . . . . . . . "; String unitName2, unitName, name, procedure; int qty = 0; Helper helper = Helper(); String days = allTranslations.text("days"); //String itemLine = ". . . . . . . . ."; itemTotal = ""; subTotal = ""; bluetooth.isConnected.then((isConnected) { if (isConnected == true) { bluetooth.printCustom(journal.title, 1, 1); bluetooth.printCustom( journal.subCategoryId + " " + jConfig.speciality, 1, 1); bluetooth.printCustom(address.address, 0, 1); bluetooth.printCustom( address.city + " " + address.state + " " + address.country, 0, 1); bluetooth.printCustom(journal.enterBy, 0, 1);

    bluetooth.printNewLine();
    bluetooth.printCustom(appointment.name, 0, 0);
    bluetooth.printCustom(appointment.contactNumber, 0, 0);

    bluetooth.printLeftRight(
        appointment.genderChar, appointment.age.toString() + " yrs", 0);
    bluetooth.printCustom(line, 1, 1);
    // bluetooth.printNewLine();
    int counter = 0;
    for (int i = 0; i < listData.length; i++) {
      counter = i + 1;
      item = listData[i];
      name = item.name;
      unitName2 = "";
      unitName = "";
      itemTotal = "";
      subTotal = "";
      if (item.procedureType == MedProcedures.medicationIdx) {
        procedure = item.drugType;
        unitName2 =
            helper.medicineIntake(item.intake, item.times, item.unit);
        qty = helper.daysCount(
            item.intake, item.times, item.continueForDays, 1);
        if (qty > 0) {
          unitName = qty.toString() + " " + days;

          // name = item.name;
        }
        if (item.continueForDays > 0) {
          subTotal = " (" +
              item.continueForDays.toString() +
              " " +
              item.unit +
              ")";
        }
      } else {
        procedure = plist[item.procedureType];
      }

      lft = unitName2;
      //subTotal = item.quantity * item.unitPrice;
      //itemTotal += subTotal;
      rgt = unitName;

      bluetooth.printCustom(
          counter.toString() + ") " + procedure + " - " + name, 0, 0);
      if (item.procedureType == MedProcedures.medicationIdx) {
        bluetooth.printCustom(subTotal + " " + unitName, 0, 0);
        //bluetooth.printCustom("Unit:" + item.unitName, 1, 0);
        bluetooth.printCustom(lft, 0, 0);
        bluetooth.printCustom(item.beforeAfterMealText, 0, 0);
        //bluetooth.printLeftRight(itemLine, "", 0);
        if (item.continueCondition.length > 0) {
          bluetooth.printCustom(item.continueCondition, 0, 0);
        }
      }
      bluetooth.printCustom(line2, 1, 1);
    }
    bluetooth.printCustom(line, 1, 1);
    // bluetooth.printLeftRight("Sub", itemTotal.toString(), 1);

    //bluetooth.printNewLine();

    bluetooth.printNewLine();
    bluetooth.printCustom("Thank you!", 2, 1);
    if (qrCode.length > 10) {
      bluetooth.printQRcode(qrCode, 250, 250, 1);
    }
    DateFormat printTimeFormat =
        DateFormat('dd/MM/yyyy').add_jm(); // DateFormat.yMd().add_jm();
    String printTime =
        printTimeFormat.format(DateTime.now()).toString().trim();
    bluetooth.printLeftRight(printTime, usernameMasked.trim(), 0);
    //bluetooth.printCustom(line, 1, 1);
    bluetooth.printCustom("MyPaaa a product from ExCode.Net", 0, 1);
    //bluetooth.printLeftRight(DateTime.now().toIso8601String(), '', 1);
    bluetooth.printNewLine();
    //bluetooth.printNewLine();
    bluetooth.paperCut();
  }
});

} }

========

THERE IS NO ERROR in my code but while try to load the page it throws the error

excode commented 3 years ago

Any update Mr @kakzaki kakzaki

Thank you

danieramiz commented 3 years ago

I have the same error

unger1984 commented 3 years ago

To fix it, replace default constructor in 34 line of blue_thermal_printer.dart from this:

  BlueThermalPrinter._() {
    _channel.setMethodCallHandler((MethodCall call) {
      _methodStreamController.add(call);
    } as Future<dynamic> Function(MethodCall)?);
  }

to this:

BlueThermalPrinter._() {
    _channel.setMethodCallHandler((MethodCall call) async{
      _methodStreamController.add(call);
    });
  }
vishnuagbly commented 3 years ago

@kakzaki your example app is not migrated to null safety that is why it is working fine their, use dart migrate to migrate your example app to null safety

mehdikazmii commented 2 years ago

have you found the solution? if yes can you please help me?

BLUECALF commented 2 years ago

same error type '(MethodCall) => Null' is not a subtype of type '(MethodCall) => Future' in type cast using bluetooth_print: PACKAGE.

please help if anyone knows .

BLUECALF commented 2 years ago

This package works with my bluetooth earphone, it was updated 3days ago. you can view this package if you need bluetooth printing. havent tested with printer. but it connects & thats progress. https://pub.dev/packages/blue_print_pos