使用 signature 第三方库完成 flutter 的电子签名, 在 flutter3.0 中验证使用正常
安装
signature: ^5.3.2
使用
封装了 signature 可以直接使用的地方调用 MySigature(onClone(){get.back();})
import 'dart:developer';
import 'package:flutter/material.dart';
import "package:get/get.dart";
import "dart:convert";
import 'package:signature/signature.dart';
import 'dart:typed_data';
import '../controllers/global_controller.dart';
class MySigature extends StatefulWidget {
void Function() onClone; // 用于关闭弹窗
MySigature({super.key,required this.onClone});
@override
State<MySigature> createState() => _MySigatureState();
}
class _MySigatureState extends State<MySigature> {
GlobalController globalController = Get.find();
// 实例化签名函数
final SignatureController _controller = SignatureController(
penStrokeWidth: 2,
penColor: Colors.black,
exportBackgroundColor: Colors.white,
exportPenColor: Colors.black,
onDrawStart: () => log('onDrawStart called!'),
onDrawEnd: () => log('onDrawEnd called!'),
);
@override
void initState() {
super.initState();
_controller.addListener(() => log('Value changed'));
}
@override
void dispose() {
// IMPORTANT to dispose of the controller
_controller.dispose();
super.dispose();
}
Future<void> exportImage(BuildContext context) async {
if (_controller.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
key: Key('snackbarPNG'),
content: Text('请签字后保存'),
),
);
return;
}
final Uint8List? data = await _controller.toPngBytes(height: 500, width: 500);
final String dataStr = base64Encode(data!);
// 将扫码结果存放在 全局数据controller中,该参数是 Uint8List 需要转换成字符串类型然后在存放全局的controller
globalController.mockUphold[0]["userSign"] = dataStr;
widget.onClone();
setState(() => _controller.clear());
// print("数据响应中的签名存储 ${globalController.mockUphold[0]}",);
// final Uint8List decodedData = base64Decode(dataStr);
// print("逆解析 ${decodedData}");
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Signature(
key: const Key('signature'),
controller: _controller,
height: 300,
backgroundColor: Colors.grey[300]!,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
IconButton(
icon: const Icon(Icons.undo),
color: Colors.blue,
onPressed: () {
setState(() => _controller.undo());
},
tooltip: 'Undo',
),
IconButton(
icon: const Icon(Icons.redo),
color: Colors.blue,
onPressed: () {
setState(() => _controller.redo());
},
tooltip: 'Redo',
),
//CLEAR CANVAS
ElevatedButton(
key: const Key('clear'),
onPressed: () {
setState(() => _controller.clear());
},
child: const Text('清空'),
),
ElevatedButton(
key: const Key('exportPNG'),
onPressed: (){
exportImage(context);
} ,
child:const Text('保存图片'),
),
],
)
],
);
}
}