Browse Source

added barcodes page

pull/3/head
Khoren Markosyan 3 years ago
parent
commit
fc29a1c1cc
  1. 2
      example/lib/models/code.dart
  2. 6
      example/lib/models/encode.dart
  3. 82
      example/lib/pages/barcodes_page.dart
  4. 32
      example/lib/pages/creator_page.dart
  5. 6
      example/lib/pages/history_page.dart
  6. 5
      example/lib/pages/home_page.dart
  7. 35
      example/lib/utils/db_service.dart
  8. 53
      lib/flutter_zxing.dart
  9. 10
      lib/zxing_writer_widget.dart

2
example/lib/models/code.dart

@ -21,4 +21,6 @@ class Code extends HiveObject {
format = result.format; format = result.format;
text = result.textString; text = result.textString;
} }
String get formatName => FlutterZxing.formatName(format ?? 0);
} }

6
example/lib/models/encode.dart

@ -24,11 +24,13 @@ class Encode extends HiveObject {
Encode(); Encode();
Encode.fromEncodeResult(EncodeResult result) { Encode.fromEncodeResult(EncodeResult result, Uint8List? bytes) {
isValid = result.isValidBool; isValid = result.isValidBool;
format = result.format; format = result.format;
text = result.textString; text = result.textString;
data = result.bytes as Uint8List?; data = bytes;
length = result.length; length = result.length;
} }
String get formatName => FlutterZxing.formatName(format ?? 0);
} }

82
example/lib/pages/barcodes_page.dart

@ -0,0 +1,82 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_zxing_example/models/models.dart';
import 'package:flutter_zxing_example/utils/db_service.dart';
import 'package:flutter_zxing_example/utils/router.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hive_flutter/hive_flutter.dart';
class BarcodesPage extends StatefulWidget {
const BarcodesPage({
Key? key,
}) : super(key: key);
@override
State<BarcodesPage> createState() => _BarcodesPageState();
}
class _BarcodesPageState extends State<BarcodesPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Barcodes'),
),
body: _buildResultList(),
floatingActionButton: FloatingActionButton(
child: const Icon(FontAwesomeIcons.plus),
onPressed: () {
Navigator.of(context).pushNamed(AppRoutes.creator);
},
),
);
}
_buildResultList() {
return ValueListenableBuilder<Box<Encode>>(
valueListenable: DbService.instance.getEncodes().listenable(),
builder: (context, box, _) {
final results = box.values.toList().cast<Encode>();
return results.isEmpty
? const Center(
child: Text(
'Tap + to create a Barcode',
style: TextStyle(fontSize: 24),
))
: ListView.builder(
itemCount: results.length,
itemBuilder: (context, index) {
final result = results[index];
return ListTile(
leading: Image.memory(result.data ?? Uint8List(0)),
title: Text(result.text ?? ''),
subtitle: Text(result.formatName),
trailing: ButtonBar(
mainAxisSize: MainAxisSize.min,
children: [
// Copy button
TextButton(
child: const Text('Copy'),
onPressed: () {
Clipboard.setData(
ClipboardData(text: result.text));
},
),
// Remove button
IconButton(
icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () {
DbService.instance.deleteEncode(result);
setState(() {});
},
),
],
),
);
},
);
});
}
}

32
example/lib/pages/creator_page.dart

@ -3,6 +3,8 @@ import 'dart:typed_data';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_zxing/flutter_zxing.dart'; import 'package:flutter_zxing/flutter_zxing.dart';
import 'package:flutter_zxing_example/models/encode.dart';
import 'package:flutter_zxing_example/utils/db_service.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
@ -22,7 +24,7 @@ class _CreatorPageState extends State<CreatorPage> {
bool isAndroid() => Theme.of(context).platform == TargetPlatform.android; bool isAndroid() => Theme.of(context).platform == TargetPlatform.android;
// Write result // Write result
Uint8List? writeResult; Encode? encode;
@override @override
void initState() { void initState() {
@ -47,14 +49,14 @@ class _CreatorPageState extends State<CreatorPage> {
child: Column( child: Column(
children: [ children: [
ZxingWriterWidget( ZxingWriterWidget(
onSuccess: (result) { onSuccess: (result, bytes) {
setState(() { setState(() {
writeResult = result; encode = Encode.fromEncodeResult(result, bytes);
}); });
}, },
onError: (error) { onError: (error) {
setState(() { setState(() {
writeResult = null; encode = null;
}); });
ScaffoldMessenger.of(context).hideCurrentSnackBar(); ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@ -70,7 +72,7 @@ class _CreatorPageState extends State<CreatorPage> {
); );
}, },
), ),
if (writeResult != null) buildWriteResult(), if (encode != null) buildWriteResult(),
], ],
), ),
), ),
@ -81,19 +83,35 @@ class _CreatorPageState extends State<CreatorPage> {
return Column( return Column(
children: [ children: [
// Barcode image // Barcode image
Image.memory(writeResult ?? Uint8List(0)), Image.memory(encode?.data ?? Uint8List(0)),
const SizedBox(height: 20),
// Share button // Share button
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton( ElevatedButton(
onPressed: () { onPressed: () {
// Save image to device // Save image to device
final file = File(tempPath); final file = File(tempPath);
file.writeAsBytesSync(writeResult ?? Uint8List(0)); file.writeAsBytesSync(encode?.data ?? Uint8List(0));
final path = file.path; final path = file.path;
// Share image // Share image
Share.shareFiles([path]); Share.shareFiles([path]);
}, },
child: const Text('Share'), child: const Text('Share'),
), ),
ElevatedButton(
onPressed: () async {
if (encode != null) {
await DbService.instance.addEncode(encode!);
Navigator.of(context).pop();
}
},
child: const Text('Save'),
),
],
),
], ],
); );
} }

6
example/lib/pages/history_page.dart

@ -41,7 +41,7 @@ class _HistoryPageState extends State<HistoryPage> {
final result = results[index]; final result = results[index];
return ListTile( return ListTile(
title: Text(result.text ?? ''), title: Text(result.text ?? ''),
subtitle: Text(result.format.toString()), subtitle: Text(result.formatName),
trailing: ButtonBar( trailing: ButtonBar(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@ -57,8 +57,8 @@ class _HistoryPageState extends State<HistoryPage> {
IconButton( IconButton(
icon: const Icon(Icons.delete, color: Colors.red), icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () { onPressed: () {
// DbService.instance.deleteCode(result); DbService.instance.deleteCode(result);
// setState(() {}); setState(() {});
}, },
), ),
], ],

5
example/lib/pages/home_page.dart

@ -1,5 +1,6 @@
import 'package:convex_bottom_bar/convex_bottom_bar.dart'; import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_zxing_example/pages/barcodes_page.dart';
import 'package:flutter_zxing_example/pages/creator_page.dart'; import 'package:flutter_zxing_example/pages/creator_page.dart';
import 'package:flutter_zxing_example/pages/history_page.dart'; import 'package:flutter_zxing_example/pages/history_page.dart';
import 'package:flutter_zxing_example/pages/scanner_page.dart'; import 'package:flutter_zxing_example/pages/scanner_page.dart';
@ -16,14 +17,14 @@ class HomePage extends StatefulWidget {
class _HomePageState extends State<HomePage> { class _HomePageState extends State<HomePage> {
var selectedIndex = 2; var selectedIndex = 2;
final creatorPage = const CreatorPage(); final barcodesPage = const BarcodesPage();
final historyPage = const HistoryPage(); final historyPage = const HistoryPage();
final scannerPage = const ScannerPage(); final scannerPage = const ScannerPage();
final helpPage = Container(); final helpPage = Container();
final settingsPage = const SettingsPage(); final settingsPage = const SettingsPage();
dynamic pages() => [ dynamic pages() => [
creatorPage, barcodesPage,
historyPage, historyPage,
scannerPage, scannerPage,
helpPage, helpPage,

35
example/lib/utils/db_service.dart

@ -9,42 +9,53 @@ class DbService {
Future<void> initializeApp() async { Future<void> initializeApp() async {
await Hive.initFlutter(); await Hive.initFlutter();
Hive.registerAdapter(CodeAdapter()); Hive.registerAdapter(CodeAdapter());
Hive.registerAdapter(EncodeAdapter());
await Hive.openBox<Code>('codes'); await Hive.openBox<Code>('codes');
await Hive.openBox<Encode>('encodes'); await Hive.openBox<Encode>('encodes');
// Hive.box('codes').close();
} }
Box<Code> getCodes() => Hive.box<Code>('codes'); Box<Code> getCodes() => Hive.box<Code>('codes');
Future deleteCodes() async { Future deleteCodes() async {
var codes = getCodes(); var items = getCodes();
await codes.deleteAll(codes.keys); await items.deleteAll(items.keys);
return; return;
} }
Future addCode(Code value) async { Future addCode(Code value) async {
var codes = getCodes(); var items = getCodes();
if (!codes.values.contains(value)) { if (!items.values.contains(value)) {
return codes.add(value); return items.add(value);
}
return;
} }
Future<void> deleteCode(Code value) async {
var items = getCodes();
await items.delete(value.key);
return; return;
} }
Box<Encode> getEncodes() => Hive.box<Encode>('encodes'); Box<Encode> getEncodes() => Hive.box<Encode>('encodes');
Future deleteEncodes() async { Future deleteEncodes() async {
var encodes = getEncodes(); var items = getEncodes();
await encodes.deleteAll(encodes.keys); await items.deleteAll(items.keys);
return; return;
} }
Future addEncode(Encode value) async { Future addEncode(Encode value) async {
var encodes = getEncodes(); var items = getEncodes();
if (!encodes.values.contains(value)) { if (!items.values.contains(value)) {
return encodes.add(value); return items.add(value);
} }
return; return;
} }
Future<void> deleteEncode(Encode value) async {
var items = getEncodes();
await items.delete(value.key);
return;
}
} }

53
lib/flutter_zxing.dart

@ -51,6 +51,8 @@ class FlutterZxing {
} }
static int get _logEnabled => logEnabled ? 1 : 0; static int get _logEnabled => logEnabled ? 1 : 0;
static String formatName(int format) => _formatNames[format] ?? 'Unknown';
} }
// Getting a library that holds needed symbols // Getting a library that holds needed symbols
@ -79,23 +81,42 @@ extension CodeExt on CodeResult {
bool get isValidBool => isValid == 1; bool get isValidBool => isValid == 1;
String? get textString => String? get textString =>
text == nullptr ? null : text.cast<Utf8>().toDartString(); text == nullptr ? null : text.cast<Utf8>().toDartString();
String get formatString => CodeFormat.formatName(format); String get formatString => FlutterZxing.formatName(format);
} }
extension EncodeExt on EncodeResult { extension EncodeExt on EncodeResult {
bool get isValidBool => isValid == 1; bool get isValidBool => isValid == 1;
String? get textString => String? get textString =>
text == nullptr ? null : text.cast<Utf8>().toDartString(); text == nullptr ? null : text.cast<Utf8>().toDartString();
String get formatString => CodeFormat.formatName(format); String get formatString => FlutterZxing.formatName(format);
Uint32List get bytes => data.asTypedList(length); Uint32List get bytes => data.asTypedList(length);
String get errorMessage => error.cast<Utf8>().toDartString(); String get errorMessage => error.cast<Utf8>().toDartString();
} }
extension CodeFormat on Format { extension CodeFormat on Format {
static String formatName(int format) => formatNames[format] ?? 'Unknown'; String get name => _formatNames[this] ?? 'Unknown';
String get name => formatNames[this] ?? 'Unknown';
static final writerFormats = [
Format.QRCode,
Format.DataMatrix,
Format.Aztec,
Format.PDF417,
Format.Codabar,
Format.Code39,
Format.Code93,
Format.Code128,
Format.EAN8,
Format.EAN13,
Format.ITF,
Format.UPCA,
Format.UPCE,
// Format.DataBar,
// Format.DataBarExpanded,
// Format.MaxiCode,
];
}
static final formatNames = { final _formatNames = {
Format.None: 'None', Format.None: 'None',
Format.Aztec: 'Aztec', Format.Aztec: 'Aztec',
Format.Codabar: 'CodaBar', Format.Codabar: 'CodaBar',
@ -116,24 +137,4 @@ extension CodeFormat on Format {
Format.OneDCodes: 'OneD', Format.OneDCodes: 'OneD',
Format.TwoDCodes: 'TwoD', Format.TwoDCodes: 'TwoD',
Format.Any: 'Any', Format.Any: 'Any',
}; };
static final writerFormats = [
Format.QRCode,
Format.DataMatrix,
Format.Aztec,
Format.PDF417,
Format.Codabar,
Format.Code39,
Format.Code93,
Format.Code128,
Format.EAN8,
Format.EAN13,
Format.ITF,
Format.UPCA,
Format.UPCE,
// Format.DataBar,
// Format.DataBarExpanded,
// Format.MaxiCode,
];
}

10
lib/zxing_writer_widget.dart

@ -12,7 +12,7 @@ class ZxingWriterWidget extends StatefulWidget {
this.onError, this.onError,
}) : super(key: key); }) : super(key: key);
final Function(Uint8List)? onSuccess; final Function(EncodeResult, Uint8List)? onSuccess;
final Function(String)? onError; final Function(String)? onError;
@override @override
@ -48,7 +48,7 @@ class _ZxingWriterWidgetState extends State<ZxingWriterWidget>
items: _supportedFormats items: _supportedFormats
.map((format) => DropdownMenuItem( .map((format) => DropdownMenuItem(
value: format, value: format,
child: Text(CodeFormat.formatName(format)), child: Text(FlutterZxing.formatName(format)),
)) ))
.toList(), .toList(),
onChanged: (format) { onChanged: (format) {
@ -84,16 +84,16 @@ class _ZxingWriterWidgetState extends State<ZxingWriterWidget>
final text = _textController.value.text; final text = _textController.value.text;
const width = 300; const width = 300;
const height = 300; const height = 300;
final result = FlutterZxing.encodeBarcode( var result = FlutterZxing.encodeBarcode(
text, width, height, _codeFormat, 5, 0); text, width, height, _codeFormat, 5, 0);
String? error; String? error;
if (result.isValidBool) { if (result.isValidBool) {
try { try {
final img = final img =
imglib.Image.fromBytes(width, height, result.bytes); imglib.Image.fromBytes(width, height, result.bytes);
final resultBytes = final encodedBytes =
Uint8List.fromList(imglib.encodeJpg(img)); Uint8List.fromList(imglib.encodeJpg(img));
widget.onSuccess?.call(resultBytes); widget.onSuccess?.call(result, encodedBytes);
} on Exception catch (e) { } on Exception catch (e) {
error = e.toString(); error = e.toString();
} }

Loading…
Cancel
Save