Flutter车牌识别插件license_plate_number的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter车牌识别插件license_plate_number的使用

1. 安装

首先,你需要在你的 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  license_plate_number: ^2.0.1

2. 基本使用

Flutter 包含两个主要的组件:PlateInputFieldPlateKeyboardPlateInputField 用于输入 车牌号。

Container(
  child: PlateInputField(
    placeHolder: '沪A12345',
    style: PlateStyle.light,
    inputFieldWidth: 40,
    inputFieldHeight: 54,
    onChange: (List<String> array, String value) {
      // e.g.
      // array ['沪', 'A', '1', '2', '3', '4', '5']
      // value 沪A12345
    },
  ),
  alignment: Alignment.center,
)

PlateKeyboard 通常不会直接使用,它由 PlateInputField 控制。但是,我们也可以通过 KeyboardController 来手动控制键盘的显示和隐藏。

/// KeyboardController
KeyboardController _keyboardController = KeyboardController();

/// Show keyboard
_keyboardController.showKeyboard(context);

/// Hide keyboard
_keyboardController.hideKeyboard();

/// Is keyboard showing
_keyboardController.isKeyboardShowing();

/// Modify plate number
_keyboardController.plateNumber = 'XXXXXXX';

你可以将 KeyboardController 传递给 PlateInputField

PlateInputField(
  /// Pass KeyboardController to PlateInputField
  keyboardController: _keyboardController,
);

3. 风格

默认提供了两种风格,同时也支持自定义风格。

/// 1. 使用构造函数。
PlateStyles(
  /// 文字样式
  plateInputFieldTextStyle: TextStyle(
    color: Color(0xFFFFFFFF),
    fontSize: 20,
    fontWeight: FontWeight.normal,
  ),
  /// 新能源车牌占位文字样式
  newEnergyPlaceHolderTextStyle: TextStyle(
    color: Color(0xFFDDDDDD),
    fontSize: 10,
    fontWeight: FontWeight.normal,
  ),
  /// 输入框背景颜色
  plateInputFieldColor: Color(0xFF4A4A4A),
  /// 输入框边框
  plateInputBorder: Border.fromBorderSide(BorderSide(
    color: Color(0xFFFFFFFF),
    width: 2,
    style: BorderStyle.solid,
  )),
  /// 焦点时的输入框边框
  plateInputFocusedBorder: Border.fromBorderSide(BorderSide(
    color: Color(0xFF2196F3),
    width: 2,
    style: BorderStyle.solid,
  )),
  /// 输入框圆角半径
  plateInputBorderRadius: const Radius.circular(8.0),
  /// 分隔符颜色
  plateSeparatorColor: Color(0xFFFFFFFF),

  /// 键盘背景颜色
  keyboardBackgroundColor: Color(0xFF1f),
  /// 键盘按钮文字颜色
  keyboardButtonTextColor: Color(0xFFFFFFFF),
  /// 键盘按钮背景颜色
  keyboardButtonColor: Color(0xFF4A4A4A),
  /// 键盘禁用按钮背景颜色
  keyboardButtonDisabledColor: Color(0x994A4A4A),
);

/// 2. 复制默认风格
PlateStyles.dark.copyWith(
  keyboardBackgroundColorDark: Color(0xFF000000),
);

示例代码

下面是一个完整的示例代码,展示了如何使用 license_plate_number 插件。

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:license_plate_number/license_plate_number.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Brightness _brightness = Brightness.light;
  PlateStyles _plateStyles = PlateStyles.light;
  final KeyboardController _keyboardController = KeyboardController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'License plate number Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
        brightness: _brightness,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('License plate number'),
          actions: [
            /// AppBar 弹出菜单
            PopupMenuButton(
              itemBuilder: (context) =&gt; [
                PopupMenuItem(child: Text('dark'), value: 'dark'),
                PopupMenuItem(child: Text('light'), value: 'light'),
              ],
              onSelected: (action) {
                switch (action) {

                  /// 切换成黑暗主题
                  case 'dark':
                    _plateStyles = PlateStyles.dark;
                    _brightness = Brightness.dark;
                    break;

                  /// 切换成明亮主题
                  case 'light':
                    _plateStyles = PlateStyles.light;
                    _brightness = Brightness.light;
                    break;
                }
                setState(() {});
              },
            ),
          ],
        ),
        body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          child: MyHomePage(
            plateStyles: _plateStyles,
            keyboardController: _keyboardController,
          ),
          onTap: () {
            /// 点击键盘外区域收起键盘
            _keyboardController.hideKeyboard();
          },
        ),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  MyHomePage({
    this.plateStyles,
    this.keyboardController,
  });

  final PlateStyles plateStyles;
  final KeyboardController keyboardController;

  [@override](/user/override)
  Widget build(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    double screenWidth = mediaQuery.size.width;
    double screenHeight = mediaQuery.size.height;
    double inputFieldWidth = min(screenWidth, screenHeight) / 10;
    double inputFieldHeight = inputFieldWidth * 4 / 3;
    if (screenWidth &lt; screenHeight) {
      SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top, SystemUiOverlay.bottom]);
    } else {
      SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
    }
    return Container(
      alignment: Alignment.topCenter,
      padding: EdgeInsets.only(top: 30),

      /// 车牌号输入框
      child: PlateInputField(
        styles: plateStyles,
        inputFieldWidth: inputFieldWidth,
        inputFieldHeight: inputFieldHeight,
        keyboardController: keyboardController,
        plateSeparatorPadding: 8,
        plateSeparatorSize: 6,
        onChanged: (List&lt;String&gt; array, String value) {
          debugPrint(array.toString());
          debugPrint(value);
        },
      ),
    );
  }
}

更多关于Flutter车牌识别插件license_plate_number的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter车牌识别插件license_plate_number的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用license_plate_number插件来进行车牌识别的代码示例。请注意,这里假设你已经有一个Flutter开发环境,并且已经添加了这个插件到你的pubspec.yaml文件中。

首先,确保在你的pubspec.yaml文件中添加依赖:

dependencies:
  flutter:
    sdk: flutter
  license_plate_number: ^最新版本号  # 请替换为实际的最新版本号

然后,运行flutter pub get来安装依赖。

接下来,是一个简单的Flutter应用示例,展示如何使用license_plate_number插件进行车牌识别:

import 'package:flutter/material.dart';
import 'package:license_plate_number/license_plate_number.dart';
import 'dart:io';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter License Plate Recognition',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LicensePlateRecognitionPage(),
    );
  }
}

class LicensePlateRecognitionPage extends StatefulWidget {
  @override
  _LicensePlateRecognitionPageState createState() => _LicensePlateRecognitionPageState();
}

class _LicensePlateRecognitionPageState extends State<LicensePlateRecognitionPage> {
  File? _imageFile;
  String? _recognizedPlateNumber;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('License Plate Recognition'),
      ),
      body: Column(
        children: <Widget>[
          Center(
            child: _imageFile == null
                ? Text('No image selected.')
                : Image.file(_imageFile!),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: _pickImage,
            child: Text('Select Image'),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: _recognizePlateNumber,
            child: Text('Recognize Plate Number'),
            enabled: _imageFile != null,
          ),
          SizedBox(height: 20),
          Text(
            _recognizedPlateNumber ?? 'No plate number recognized yet.',
            style: TextStyle(fontSize: 20),
          ),
        ],
      ),
    );
  }

  Future<void> _pickImage() async {
    final pickedFile = await ImagePicker().pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _imageFile = File(pickedFile.path);
        _recognizedPlateNumber = null;  // Reset recognized plate number
      });
    }
  }

  Future<void> _recognizePlateNumber() async {
    if (_imageFile == null) return;

    try {
      final result = await LicensePlateRecognizer.recognizePlateNumber(imagePath: _imageFile!.path);
      setState(() {
        _recognizedPlateNumber = result.plateNumber;
      });
    } catch (e) {
      print('Error recognizing plate number: $e');
      setState(() {
        _recognizedPlateNumber = 'Error recognizing plate number.';
      });
    }
  }
}

在这个示例中,我们做了以下几件事:

  1. 使用ImagePicker插件让用户从图库中选择一张图片。
  2. 使用license_plate_number插件对选择的图片进行车牌识别。
  3. 显示识别结果。

请注意,LicensePlateRecognizer.recognizePlateNumber方法是一个假设的方法调用,实际的插件可能有不同的API。你需要参考license_plate_number插件的官方文档来调整这部分代码。如果插件提供了不同的方法或参数,请确保按照文档进行相应的修改。

此外,这个示例没有处理错误和异常情况,比如用户取消选择图片或者图片文件无法读取等。在实际应用中,你可能需要添加更多的错误处理和用户反馈。

回到顶部