Flutter二维码扫描插件cnic_scanner的使用
Flutter二维码扫描插件cnic_scanner的使用
cnic_scanner
是一个Flutter插件,允许你扫描身份证、银行卡等各种类型的卡片。以下是详细的使用指南。
安装
在 pubspec.yaml
文件中添加以下依赖,并在你的文件中导入相应的包:
dependencies:
cnic_scanner: latest version
image_picker: latest version
import 'package:cnic_scanner/cnic_scanner.dart';
请确保替换 latest version
为实际的最新版本号。
快速开始
首先创建一个 CnicModel
对象,然后调用 CnicScanner().scanImage(imageSource: imageSource)
方法来扫描图片。这里需要传递一个 ImageSource
参数,可以是相机或图库。
// 创建一个 CnicModel 对象
CnicModel _cnicModel = CnicModel();
// 调用扫描方法
await CnicScanner().scanImage(imageSource: imageSource);
自定义对话框
为了方便选择图片来源(相机或图库),你可以创建一个自定义对话框:
CustomDialogBox(
onCameraBTNPressed: () {
scanCnic(ImageSource.camera);
},
onGalleryBTNPressed: () {
scanCnic(ImageSource.gallery);
}
);
CnicModel 类
该类包含返回的参数:
class CardModel {
String _cnicNumber = "";
String _cnicIssueDate = "";
String _cnicHolderName = "";
String _cnicExpiryDate = "";
String _cnicHolderDateOfBirth = "";
}
示例 Demo
以下是一个完整的示例应用,展示了如何使用 cnic_scanner
插件。
main.dart
import 'package:cnic_scanner/model/cnic_model.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'src/app_color.dart';
import 'src/custom_dialog.dart';
import 'package:cnic_scanner/cnic_scanner.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'CNIC Scanner',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: false,
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController nameTEController = TextEditingController(),
cnicTEController = TextEditingController(),
dobTEController = TextEditingController(),
doiTEController = TextEditingController(),
doeTEController = TextEditingController();
CnicModel _cnicModel = CnicModel();
Future<void> scanCnic(ImageSource imageSource) async {
CnicModel cnicModel = await CnicScanner().scanImage(imageSource: imageSource);
setState(() {
_cnicModel = cnicModel;
nameTEController.text = _cnicModel.cnicHolderName;
cnicTEController.text = _cnicModel.cnicNumber;
dobTEController.text = _cnicModel.cnicHolderDateOfBirth;
doiTEController.text = _cnicModel.cnicIssueDate;
doeTEController.text = _cnicModel.cnicExpiryDate;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Container(
margin: const EdgeInsets.only(left: 20, right: 20, top: 50, bottom: 25),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 18),
Text('Enter ID Card Details', style: TextStyle(color: Color(kDarkGreyColor), fontSize: 23.0, fontWeight: FontWeight.bold)),
SizedBox(height: 5),
Text('To verify your Account, please enter your CNIC details.', style: TextStyle(color: Color(kLightGreyColor), fontSize: 15.0, fontWeight: FontWeight.w500)),
SizedBox(height: 35),
Expanded(
child: ListView(
padding: const EdgeInsets.all(0),
shrinkWrap: true,
children: [
_dataField(text: 'Name', textEditingController: nameTEController),
_cnicField(textEditingController: cnicTEController),
_dataField(text: 'Date of Birth', textEditingController: dobTEController),
_dataField(text: 'Date of Card Issue', textEditingController: doiTEController),
_dataField(text: 'Date of Card Expire', textEditingController: doeTEController),
SizedBox(height: 20),
_getScanCNICBtn(),
],
),
)
],
),
),
);
}
Widget _cnicField({required TextEditingController textEditingController}) {
return Card(
elevation: 7,
margin: const EdgeInsets.only(top: 2.0, bottom: 5.0),
child: Container(
margin: const EdgeInsets.only(top: 2.0, bottom: 1.0, left: 0.0, right: 0.0),
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
width: 3,
height: 45,
margin: const EdgeInsets.only(left: 3.0, right: 7.0),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [const Color(kDeepDarkGreenColor), const Color(kDarkGreenColor), const Color(kGradientGreyColor)]),
borderRadius: BorderRadius.circular(5),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('CNIC Number', style: TextStyle(color: Color(kDarkGreenColor), fontSize: 13.0, fontWeight: FontWeight.bold)),
SizedBox(height: 5),
Row(
children: [
Image.asset("assets/images/cnic.png", width: 40, height: 30),
Expanded(
child: TextField(
controller: textEditingController,
decoration: InputDecoration(hintText: '41000-0000000-0', hintStyle: TextStyle(color: Color(kLightGreyColor)), border: InputBorder.none, isDense: true, contentPadding: EdgeInsets.only(left: 5.0)),
style: TextStyle(color: Color(kDarkGreyColor), fontWeight: FontWeight.bold),
textInputAction: TextInputAction.done,
keyboardType: TextInputType.number,
textAlign: TextAlign.left,
),
)
],
)
],
),
),
],
),
),
),
);
}
Widget _dataField({required String text, required TextEditingController textEditingController}) {
return Card(
shadowColor: Color(kShadowColor),
elevation: 5,
margin: const EdgeInsets.only(top: 10, bottom: 5),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.only(left: 5),
child: Icon((text == "Name") ? Icons.person : Icons.date_range, color: Color(kDarkGreenColor), size: 17),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0, top: 5, bottom: 3),
child: Text(text.toUpperCase(), style: TextStyle(color: Color(kDarkGreenColor), fontSize: 12, fontWeight: FontWeight.bold)),
),
Padding(
padding: const EdgeInsets.only(left: 15.0, bottom: 5),
child: TextField(
controller: textEditingController,
decoration: InputDecoration(hintText: (text == "Name") ? "User Name" : 'DD/MM/YYYY', border: InputBorder.none, isDense: true, hintStyle: TextStyle(color: Color(kLightGreyColor), fontSize: 14, fontWeight: FontWeight.bold), contentPadding: EdgeInsets.all(0)),
style: TextStyle(color: Color(kDarkGreyColor), fontWeight: FontWeight.bold),
textInputAction: TextInputAction.done,
keyboardType: (text == "Name") ? TextInputType.text : TextInputType.number,
textAlign: TextAlign.left,
),
),
],
),
),
],
),
);
}
Widget _getScanCNICBtn() {
return ElevatedButton(
style: ElevatedButton.styleFrom(elevation: 5, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), textStyle: TextStyle(color: Colors.white), padding: EdgeInsets.all(0.0)),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return CustomDialogBox(onCameraBTNPressed: () { scanCnic(ImageSource.camera); }, onGalleryBTNPressed: () { scanCnic(ImageSource.gallery); });
}
);
},
child: Container(
alignment: Alignment.center,
width: 500,
decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(10.0)), gradient: LinearGradient(colors: <Color>[Color(kDeepDarkGreenColor), Color(kDarkGreenColor), Colors.green])),
padding: const EdgeInsets.all(12.0),
child: Text('Scan CNIC', style: TextStyle(fontSize: 18)),
),
);
}
}
更多关于Flutter二维码扫描插件cnic_scanner的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter二维码扫描插件cnic_scanner的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个使用 cnic_scanner
插件在 Flutter 中实现二维码扫描功能的示例代码。这个插件可以帮助你快速集成二维码扫描功能。
首先,你需要在你的 pubspec.yaml
文件中添加 cnic_scanner
依赖:
dependencies:
flutter:
sdk: flutter
cnic_scanner: ^最新版本号 # 请替换为实际最新版本号
然后运行 flutter pub get
来获取依赖。
接下来,创建一个新的 Flutter 项目或在现有项目中添加以下代码:
主应用代码(main.dart)
import 'package:flutter/material.dart';
import 'package:cnic_scanner/cnic_scanner.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ScanPage(),
);
}
}
class ScanPage extends StatefulWidget {
@override
_ScanPageState createState() => _ScanPageState();
}
class _ScanPageState extends State<ScanPage> {
String result = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("二维码扫描"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"扫描结果: $result",
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_startScanner();
},
child: Text("开始扫描"),
),
],
),
),
);
}
void _startScanner() async {
try {
String scanResult = await CnicScanner.scanQRCode();
setState(() {
result = scanResult;
});
} catch (e) {
print("扫描失败: ${e.toString()}");
setState(() {
result = "扫描失败";
});
}
}
}
权限配置(Android 和 iOS)
Android
在 android/app/src/main/AndroidManifest.xml
中添加相机权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
并在 MainActivity.kt
或 MainActivity.java
中请求权限(如果需要动态请求权限,可以使用 Flutter 的 permission_handler
插件)。
iOS
在 ios/Runner/Info.plist
中添加相机权限:
<key>NSCameraUsageDescription</key>
<string>需要访问相机以扫描二维码</string>
运行项目
确保所有配置正确后,你可以使用 flutter run
命令来运行你的 Flutter 应用。点击按钮后,应用将启动相机并尝试扫描二维码,扫描结果将显示在屏幕上。
这个示例展示了如何使用 cnic_scanner
插件进行二维码扫描。实际项目中,你可能需要根据具体需求进行调整和扩展。