Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // import 'dart:io';
- // import 'dart:typed_data';
- import 'dart:async';
- import 'package:te111/models/store.dart';
- import 'package:te111/models/transactionMember.dart';
- import 'package:te111/models/transaction_product.dart';
- import 'package:te111/models/user.dart';
- import 'package:te111/utils/database_helper.dart';
- import 'package:te111/utils/rupiah.dart';
- import 'package:intl/intl.dart';
- // import 'package:flutter/services.dart';
- // import 'package:path_provider/path_provider.dart';
- // import 'package:pdf/pdf.dart';
- // import 'package:pdf/widgets.dart' as pdf;
- // import 'dart:ui' as ui;
- import 'package:flutter/material.dart';
- import 'package:flutter/rendering.dart';
- // import 'package:printing/printing.dart';
- import 'package:blue_thermal_printer/blue_thermal_printer.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import '../../models/member.dart';
- GlobalKey<State<StatefulWidget>> previewContainer = GlobalKey();
- class PrintStrukPage extends StatefulWidget {
- static const routeName = '/printStrukPage';
- PrintStrukPageArgument? argument;
- PrintStrukPage({this.argument});
- @override
- _PrintStrukPageState createState() => _PrintStrukPageState();
- }
- class _PrintStrukPageState extends State<PrintStrukPage> {
- TransactionModel? historyTransaction = TransactionModel();
- Member? chooseMember = Member();
- TransactionModel transactionModel = TransactionModel();
- BlueThermalPrinter bluetooth = BlueThermalPrinter.instance;
- final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
- String? pathImage, qtyBrg, hrgBrg, totalNet;
- BlueThermalPrinter con = BlueThermalPrinter.instance;
- List<TransactionProduct>? transactionProduct = [];
- User user = User();
- Store? storedata;
- String? addRessPrint = '', namaPrinter = '';
- DatabaseHelper dbHelper = DatabaseHelper();
- List<BluetoothDevice> _devices = [];
- BluetoothDevice? _device;
- bool _connected = false, isLoading = false;
- Future<Store?> getStoreData() async {
- final result = await dbHelper.getStoreDetail();
- if (result != null) {
- setState(() {
- storedata = result;
- });
- }
- return result;
- }
- getUser() async {
- final result = await dbHelper.getUserList();
- if (result != null) {
- setState(() {
- user = result.first;
- });
- }
- }
- getPrinter() async {
- SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
- setState(() {
- addRessPrint = (sharedPreferences.getString('print')! ?? "");
- namaPrinter = (sharedPreferences.getString('printer_name')! ?? "");
- });
- print('kendy ' + addRessPrint! ?? '');
- // kon();
- }
- void kon() async {
- setState(() {
- // if (pConnected == 1) {
- if (namaPrinter != '' && addRessPrint != '') {
- print("Printer terhubung ke " + namaPrinter!);
- _device = BluetoothDevice(namaPrinter, addRessPrint);
- connect();
- } else {
- _device = null;
- }
- // print("Konek ke $namaPrinter $addRessPrint");
- // }
- });
- }
- void connect() {
- if (_device == null) {
- } else {
- con.isConnected.then((isConnected) async {
- if (!isConnected!) {
- await con.connect(_device!).catchError((error) {
- setState(() => _connected = false);
- });
- setState(() => _connected = true);
- }
- });
- }
- }
- @override
- void initState() {
- super.initState();
- getStoreData();
- // getUser();
- getPrinter();
- transactionProduct = widget.argument!.transactionProduct;
- chooseMember = widget.argument!.member;
- historyTransaction = widget.argument!.transactionModel;
- }
- _disconnect() async {
- await bluetooth.disconnect();
- setState(() => _connected = true);
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- key: _scaffoldKey,
- appBar: AppBar(
- actions: <Widget>[
- IconButton(
- icon: Icon(Icons.print),
- tooltip: "Cetak Struk",
- onPressed: tesKoneksi,
- )
- ],
- elevation: 0.0,
- backgroundColor: Colors.blue,
- title: Text(
- 'Cetak Struk',
- style: TextStyle(
- fontWeight: FontWeight.w600, color: Colors.white, fontSize: 16.0),
- ),
- automaticallyImplyLeading: true,
- iconTheme: IconThemeData(
- color: Colors.white, //change your color here
- ),
- ),
- body: SingleChildScrollView(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- SingleChildScrollView(
- physics: ClampingScrollPhysics(),
- child: Padding(
- padding: EdgeInsets.all(10),
- child: Card(
- elevation: 5.0,
- color: Colors.white,
- child: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.start,
- children: <Widget>[
- Column(
- children: <Widget>[
- Container(
- width: double.infinity,
- // height: 50,
- child: Align(
- alignment: Alignment.topCenter,
- child: Text(
- "${storedata?.storeName ?? ""}",
- style: TextStyle(
- fontWeight: FontWeight.w600,
- fontSize: 20))),
- ),
- Container(
- width: double.infinity,
- // height: 50,
- child: Align(
- alignment: Alignment.topCenter,
- child: Text(
- storedata?.storeAddress != null &&
- storedata!.storeAddress!
- .isNotEmpty
- ? storedata!.storeAddress!
- : '',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16))),
- ),
- Container(
- width: double.infinity,
- // height: 50,
- child: Align(
- alignment: Alignment.topCenter,
- child: Text(
- storedata?.storePhoneNumber !=
- null
- ? storedata!.storePhoneNumber!
- : '',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16))),
- ),
- Container(
- width: double.infinity,
- // height: 50,
- child: Align(
- alignment: Alignment.topCenter,
- child: Text(
- "======================================================",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 12))),
- ),
- ],
- ),
- Container(
- // color: Colors.green,
- width: double.infinity,
- padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
- child: Align(
- alignment: Alignment.center,
- child: Text(
- historyTransaction!.noteNumber! +
- " / " +
- " / " +
- DateFormat('dd-MM-yyyy').format(
- DateTime.parse(
- historyTransaction!
- .transactionDate!)) +
- ' ' +
- DateFormat('HH:mm')
- .format(DateTime.now()),
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 14))),
- ),
- Container(
- width: double.infinity,
- // height: 50,
- child: Align(
- alignment: Alignment.topCenter,
- child: Text(
- "======================================================",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 12))),
- ),
- buildListItem(),
- Container(
- width: double.infinity,
- // height: 50,
- child: Align(
- alignment: Alignment.topCenter,
- child: Text(
- "======================================================",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 12))),
- ),
- Container(
- width: double.infinity,
- padding: EdgeInsets.fromLTRB(25, 2, 25, 2),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Text("Grand Total",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 14)),
- Text(
- 'Rp ${rupiah(historyTransaction!.transactionTotalPrice!.toInt() + historyTransaction!.transactionUserDiscount!.toInt())}',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16)),
- ],
- ),
- ),
- historyTransaction!.transactionUserDiscount! > 0
- ? Container(
- width: double.infinity,
- padding:
- EdgeInsets.fromLTRB(25, 2, 25, 2),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Text("Diskon",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 14)),
- Text(
- 'Rp ${rupiah(historyTransaction!.transactionUserDiscount!.toInt())}',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16)),
- ],
- ),
- )
- : SizedBox(height: 1),
- historyTransaction!.transactionUserDiscount! > 0
- ? Container(
- width: double.infinity,
- padding:
- EdgeInsets.fromLTRB(25, 2, 25, 2),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Text("TOTAL",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 14)),
- Text(
- 'Rp ${rupiah(historyTransaction!.transactionTotalPrice!.toInt())}',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16)),
- ],
- ),
- )
- : SizedBox(height: 1),
- Container(
- width: double.infinity,
- padding: EdgeInsets.fromLTRB(25, 2, 25, 2),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Text("TUNAI",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 14)),
- Text(
- 'Rp ${rupiah(historyTransaction!.transactionUserPayment!.toInt() * 100)}',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16)),
- ],
- ),
- ),
- Container(
- width: double.infinity,
- padding: EdgeInsets.fromLTRB(25, 2, 25, 2),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Text("Kembalian",
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 14)),
- Text(
- 'Rp ${rupiah(historyTransaction!.transactionUserReturnChange!.toInt() * 100)}',
- style: TextStyle(
- fontWeight: FontWeight.w500,
- fontSize: 16)),
- ],
- ),
- ),
- ]),
- ))))
- ],
- ),
- ),
- );
- }
- Container buildListItem() {
- return Container(
- alignment: Alignment.centerRight,
- width: double.infinity,
- padding: EdgeInsets.fromLTRB(25, 2, 25, 2),
- // height: 50,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.start,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: List.generate(transactionProduct!.length, (index) {
- return Container(
- alignment: Alignment.center,
- margin: EdgeInsets.only(bottom: 8.0),
- padding: EdgeInsets.only(bottom: 8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- crossAxisAlignment: CrossAxisAlignment.center,
- children: <Widget>[
- Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Text(
- transactionProduct![index]
- .transactionProductName!
- .length >
- 25
- ? transactionProduct![index]
- .transactionProductName!
- .substring(0, 25)
- : transactionProduct![index]
- .transactionProductName!,
- style: TextStyle(
- fontSize: 14.0,
- fontWeight: FontWeight.w500)),
- SizedBox(
- height: 5.0,
- ),
- Text(
- '${transactionProduct![index].transactionQuantity} x Rp ${rupiah(transactionProduct![index].transactionSinglePrice! ~/ 1)} / ${transactionProduct![index].transactionMeasureUnit}',
- style: TextStyle(
- fontSize: 12.0,
- fontWeight: FontWeight.w500)),
- ],
- ),
- Text(
- 'Rp ${rupiah(((transactionProduct![index].transactionQuantity! * transactionProduct![index].transactionSinglePrice!).toInt()))}',
- style: TextStyle(
- fontSize: 16.0,
- fontWeight: FontWeight.w500)),
- ],
- ));
- }))),
- ],
- ),
- );
- }
- void tesKoneksi() async {
- getPrinter();
- print(addRessPrint);
- kon();
- showCustomDialog(storedata, historyTransaction, chooseMember, context);
- }
- void _tesPrint() async {
- //SIZE
- // 0- normal size text
- // 1- only bold text
- // 2- bold with medium text
- // 3- bold with large text
- //ALIGN
- // 0- ESC_ALIGN_LEFT
- // 1- ESC_ALIGN_CENTER
- // 2- ESC_ALIGN_RIGHT
- bluetooth.isConnected.then((isConnected) {
- if (isConnected!) {
- if (storedata != null) {
- if (storedata!.storeName != null &&
- storedata!.storeName!.isNotEmpty) {
- bluetooth.printCustom("${storedata!.storeName}", 0, 1);
- }
- if (storedata!.storeAddress != null &&
- storedata!.storeAddress!.isNotEmpty) {
- bluetooth.printCustom("${storedata!.storeAddress}", 0, 1);
- }
- if (storedata!.storePhoneNumber != null &&
- storedata!.storePhoneNumber!.isNotEmpty) {
- bluetooth.printCustom("${storedata!.storePhoneNumber}", 0, 1);
- }
- }
- bluetooth.printCustom("================================", 1, 1);
- if (user != null) {
- String noKasir = historyTransaction!.noteNumber! +
- "/" +
- "/" +
- DateFormat('dd-MM-yy').format(
- DateTime.parse(historyTransaction!.transactionDate!)) +
- ' ' +
- DateFormat('HH:mm').format(DateTime.now());
- bluetooth.printCustom("$noKasir", 1, 1);
- }
- bluetooth.printCustom("================================", 1, 1);
- transactionProduct!.map((product) {
- qtyBrg = product.transactionQuantity.toString();
- hrgBrg = rupiah(product.transactionSinglePrice?.toInt()) +
- ' / ' +
- product.transactionMeasureUnit!;
- // double subtotal = product.transactionQuantity *
- // product.transactionSinglePrice.toDouble();
- String subtotal = rupiah(
- ((product.transactionQuantity! * product.transactionSinglePrice!)
- .toInt()));
- // String subtot = rupiah(subtotal.toInt());
- String? namaProd;
- if (product.transactionProductName!.length > 23) {
- namaProd = product.transactionProductName!.substring(0, 23);
- } else {
- namaProd = product.transactionProductName;
- }
- bluetooth.printCustom("$namaProd", 1, 0);
- bluetooth.printLeftRight("$qtyBrg x $hrgBrg", "$subtotal", 1);
- }).toList();
- bluetooth.printCustom("--------------------------------", 1, 1);
- double grndTot = historyTransaction!.transactionTotalPrice! +
- historyTransaction!.transactionUserDiscount!.toInt();
- String grandTotal = rupiah(grndTot.toInt());
- bluetooth.printLeftRight(
- " Grand Total",
- "$grandTotal",
- // "${rupiah(historyTransaction.transactionTotalPrice + historyTransaction.transactionUserDiscount.toInt())}",
- 1);
- if (historyTransaction!.transactionUserDiscount! > 0) {
- bluetooth.printLeftRight(
- " DISKON",
- "${rupiah(historyTransaction!.transactionUserDiscount!.toInt())}",
- 1);
- double ttlNet = historyTransaction!.transactionTotalPrice!;
- totalNet = rupiah(ttlNet.toInt());
- bluetooth.printLeftRight(" TOTAL", "$totalNet", 1);
- }
- int tunai = historyTransaction!.transactionUserPayment!.toInt() * 100;
- String tunaiStr = rupiah(tunai);
- bluetooth.printLeftRight(" TUNAI", "$tunaiStr", 1);
- // " TUNAI", "${rupiah(historyTransaction.transactionUserPayment.toInt())}", 1);
- bluetooth.printLeftRight(
- " Kembalian",
- "${rupiah(historyTransaction!.transactionUserReturnChange!.toInt() * 100)}",
- 1);
- bluetooth.printCustom("--------------------------------", 1, 1);
- if (chooseMember != null && chooseMember!.memberName != null) {
- String brsMember = chooseMember!.memberNo! +
- " | " +
- chooseMember!.memberName! +
- " | " +
- (historyTransaction!.transactionPointReward.toString());
- bluetooth.printCustom(brsMember, 1, 1);
- bluetooth.printCustom("--------------------------------", 1, 1);
- }
- bluetooth.paperCut();
- _disconnect();
- Navigator.of(context).pop();
- }
- });
- }
- void showCustomDialog(
- storedata, historyTransaction, chooseMember, BuildContext context) async {
- var status = await showDialog(
- context: context,
- builder: (context) {
- return AlertDialog(
- content: Text('Cetak Struk ?'),
- actions: <Widget>[
- RaisedButton(
- child: Text('Batal'),
- elevation: 5.0,
- color: Colors.red,
- onPressed: () {
- Navigator.of(context).pop();
- },
- ),
- RaisedButton(
- child: Text('Cetak'),
- elevation: 5.0,
- color: Colors.blue,
- onPressed: () {
- _tesPrint();
- },
- )
- ],
- );
- });
- }
- // List<DropdownMenuItem<BluetoothDevice>> _getDeviceItems() {
- // List<DropdownMenuItem<BluetoothDevice>> 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) {
- // bluetooth.connect(_device).catchError((error) {
- // setState(() => _pressed = false);
- // });
- // setState(() => _pressed = true);
- // }
- // });
- // }
- // }
- // void _disconnect() {
- // bluetooth.disconnect();
- // setState(() => _pressed = true);
- // }
- // Future<void> 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));
- // _scaffoldKey.currentState.showSnackBar(
- // new SnackBar(
- // content: new Text(
- // message,
- // style: new TextStyle(
- // color: Colors.white,
- // ),
- // ),
- // duration: duration,
- // ),
- // );
- // }
- // Future<void> printScreen() async {
- // final RenderRepaintBoundary boundary = previewContainer.currentContext.findRenderObject();
- // final ui.Image im = await boundary.toImage();
- // final ByteData bytes = await im.toByteData(format: ui.ImageByteFormat.rawRgba);
- // print('Print Screen ${im.width}x${im.height} ...');
- // Printing.layoutPdf(onLayout: (PdfPageFormat format) {
- // final pdf.Document document = pdf.Document();
- // final PdfImage image =
- // PdfImage(document.document, image: bytes.buffer.asUint8List(), width: im.width, height: im.height);
- // document.addPage(pdf.Page(
- // pageFormat: format,
- // build: (pdf.Context context) {
- // return pdf.Center(
- // child: pdf.Expanded(
- // child: pdf.Image(image),
- // ),
- // ); // Center
- // })); // Page
- // return document.save();
- // });
- // }
- int getTotal() {
- int total = 0;
- for (int i = 0; i < transactionProduct!.length; i++) {
- total += transactionProduct![i].transactionQuantity!;
- }
- return total;
- }
- String parseToDate(String dateTimeFormat) {
- DateTime date = DateTime.parse(dateTimeFormat);
- DateFormat dateFormat = DateFormat("dd MMMM yyyy");
- return dateFormat.format(date);
- }
- }
- class PrintStrukPageArgument {
- final Member? member;
- final List<TransactionProduct>? transactionProduct;
- final TransactionModel? transactionModel;
- // final TransactionModel historyTransaction;
- PrintStrukPageArgument({
- this.member,
- this.transactionProduct,
- this.transactionModel,
- // this.historyTransaction,
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement