使用C++實現Flutter Windows插件

上週實現的Flutter條形碼插件已經發布到https://pub.dev/packages/flutter_barcode_sdk,平臺相關部分只包含了Android的Java代碼。這周新增用於Windows的C++代碼。後續計劃還包含iOS和Web。

Flutter開發Windows桌面程序

關於Dynamsoft C++ Barcode SDK

學習資源

Flutter桌面插件開發的資源比較少。可以從以下三個入手:

如何把C++條形碼SDK集成到Flutter Windows插件中

Flutter創建的Windows插件工程目錄結構如下:

bin
  /DynamsoftBarcodeReaderx64.dll

include

  /flutter_barcode_sdk

    /flutter_barcode_sdk_plugin.h

  /barcode_manager.h

  /DynamsoftBarcodeReader.h

  /DynamsoftCommon.h

lib
  /DBRx64.lib

CMakeLists.txt

flutter_barcode_sdk_plugin.cpp
  • CMakeLists.txt是CMake的配置文件。
  • flutter_barcode_sdk_plugin.cpp用於實現插件的C++代碼邏輯。
  • DynamsoftBarcodeReaderx64.dllDBRx64.libDynamsoftBarcodeReader.h,以及DynamsoftCommon.h可以從C++ SDK中獲取。
  • 爲了方便,條形碼接口調用的實現都放在barcode_manager.h中。

從Dart傳到C++的接口和參數,會在HandleMethodCall()中解析:

void FlutterBarcodeSdkPlugin::HandleMethodCall(
      const flutter::MethodCall<flutter::EncodableValue> &method_call,
      std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result)
  {
    const auto *arguments = std::get_if<EncodableMap>(method_call.arguments());

    if (method_call.method_name().compare("getPlatformVersion") == 0)
    {
      
    }
    else if (method_call.method_name().compare("setLicense") == 0)
    {
      
    }
    else if (method_call.method_name().compare("decodeFile") == 0)
    {
      
    }
    else if (method_call.method_name().compare("decodeFileBytes") == 0)
    {
      
    }
    else if (method_call.method_name().compare("decodeImageBuffer") == 0)
    {
      
    }
    else
    {
      result->NotImplemented();
    }
  }

} 

獲取參數,並轉換成C++類型:stringintvector<unsigned char>

std::string filename;
auto filename_it = arguments->find(EncodableValue("filename"));
if (filename_it != arguments->end())
{
  filename = std::get<std::string>(filename_it->second);
}


std::vector<unsigned char> bytes;
auto bytes_it = arguments->find(EncodableValue("bytes"));
if (bytes_it != arguments->end())
{
  bytes = std::get<vector<unsigned char>>(bytes_it->second);
}

int width = 0;
auto width_it = arguments->find(EncodableValue("width"));
if (width_it != arguments->end())
{
  width = std::get<int>(width_it->second);
}

返回的結果需要封裝成Flutter定義的類型:

EncodableList results;
result->Success(results);

接下來在barcode_manager.h中實現解碼和結果封裝。

這裏定義三個解碼接口:

EncodableList DecodeFile(const char * filename) 
{
    EncodableList out;   
    int ret = reader->DecodeFile(filename, "");

    if (ret == DBRERR_FILE_NOT_FOUND)
    {
        printf("Error code %d. %s\n", ret, CBarcodeReader::GetErrorString(ret));
        return out;
    }

    return WrapResults();
}

EncodableList DecodeFileBytes(const unsigned char * bytes, int size) 
{
    reader->DecodeFileInMemory(bytes, size, "");
    return WrapResults();
}

EncodableList DecodeImageBuffer(const unsigned char * buffer, int width, int height, int stride, int format) 
{
    ImagePixelFormat pixelFormat = IPF_BGR_888;
    switch(format) {
        case 0:
            pixelFormat = IPF_GRAYSCALED;
            break;
        case 1:
            pixelFormat = IPF_ARGB_8888;
            break;
    }

    reader->DecodeBuffer(buffer, width, height, stride, pixelFormat, "");

    return WrapResults();
}

獲取解碼結果,並封裝到Flutter的maplist中:

EncodableList WrapResults() 
{
    EncodableList out;
    TextResultArray *results = NULL;
    reader->GetAllTextResults(&results);
        
    if (results->resultsCount == 0)
    {
        printf("No barcode found.\n");
        CBarcodeReader::FreeTextResults(&results);
    }
    
    for (int index = 0; index < results->resultsCount; index++)
    {
        EncodableMap map;
        map[EncodableValue("format")] = results->results[index]->barcodeFormatString;
        map[EncodableValue("text")] = results->results[index]->barcodeText;
        map[EncodableValue("x1")] = results->results[index]->localizationResult->x1;
        map[EncodableValue("y1")] = results->results[index]->localizationResult->y1;
        map[EncodableValue("x2")] = results->results[index]->localizationResult->x2;
        map[EncodableValue("y2")] = results->results[index]->localizationResult->y2;
        map[EncodableValue("x3")] = results->results[index]->localizationResult->x3;
        map[EncodableValue("y3")] = results->results[index]->localizationResult->y3;
        map[EncodableValue("x4")] = results->results[index]->localizationResult->x4;
        map[EncodableValue("y4")] = results->results[index]->localizationResult->y4;
        out.push_back(map);
    }

    CBarcodeReader::FreeTextResults(&results);
    return out;
}

到此,用於Windows插件的C++代碼已經完成。最後一步就是配置CMakeLists.txt文件。

鏈接C++庫:

link_directories("${PROJECT_SOURCE_DIR}/lib/") 
target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin "DBRx64")

打包動態鏈接庫:

set(flutter_barcode_sdk_bundled_libraries
  "${PROJECT_SOURCE_DIR}/bin/"
  PARENT_SCOPE
)

這步很重要。如果沒有打包進去,應用程序會因爲缺少DLL無法運行。

用Flutter實現Windows桌面條碼識別程序

有了插件就可以快速實現桌面掃碼應用。

創建一個新工程,並在pubspec.yaml中添加依賴:

dependencies:
  flutter:
    sdk: flutter

  flutter_barcode_sdk:

創建SDK對象:

class _DesktopState extends State<Desktop> {
  String _platformVersion = 'Unknown';
  final _controller = TextEditingController();
  String _barcodeResults = '';
  FlutterBarcodeSdk _barcodeReader;
  bool _isValid = false;
  String _file = '';

  @override
  void initState() {
    super.initState();
    initPlatformState();
    initBarcodeSDK();
  }

  Future<void> initBarcodeSDK() async {
    _barcodeReader = FlutterBarcodeSdk();
    // Get 30-day FREEE trial license from https://www.dynamsoft.com/customer/license/trialLicense?product=dbr
    await _barcodeReader.setLicense('LICENSE-KEY');
  }
}

使用TextFieldImageMaterialButtonText構建UI:

@override
Widget build(BuildContext context) {
  return MaterialApp(
    home: Scaffold(
        appBar: AppBar(
          title: const Text('Dynamsoft Barcode Reader'),
        ),
        body: Column(children: [
          Container(
            height: 100,
            child: Row(children: <Widget>[
              Text(
                _platformVersion,
                style: TextStyle(fontSize: 14, color: Colors.black),
              )
            ]),
          ),
          TextField(
            controller: _controller,
            decoration: InputDecoration(
              labelText: 'Input an image path',
              errorText: _isValid ? null : 'File not exists',
            ),
          ),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  getDefaultImage(),
                  Text(
                    _barcodeResults,
                    style: TextStyle(fontSize: 14, color: Colors.black),
                  ),
                ],
              ),
            ),
          ),
          Container(
            height: 100,
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  MaterialButton(
                      child: Text('Decode Barcode'),
                      textColor: Colors.white,
                      color: Colors.blue,
                      onPressed: () async {
                        if (_controller.text.isEmpty) {
                          setState(() {
                            _isValid = false;
                            _barcodeResults = '';
                            _file = '';
                          });
                          return;
                        }
                        File file = File(_controller.text);
                        if (!file.existsSync()) {
                          setState(() {
                            _isValid = false;
                            _barcodeResults = '';
                            _file = '';
                          });
                          return;
                        } else {
                          setState(() {
                            _isValid = true;
                            _file = _controller.text;
                          });
                        }
                        Uint8List bytes = await file.readAsBytes();
                        List<BarcodeResult> results =
                            await _barcodeReader.decodeFileBytes(bytes);
                        setState(() {
                          _barcodeResults = getBarcodeResults(results);
                        });
                      }),
                ]),
          ),
        ])),
  );
}

圖片默認顯示資源包中的圖。如果輸入的圖片有效,顯示輸入的圖片:

Widget getDefaultImage() {
  if (_controller.text.isEmpty || !_isValid) {
    return Image.asset('images/default.png');
  } else {
    return Image.file(File(_file));
  }
}

要使用資源圖片,需要在pubspec.yaml中添加:

flutter:
  assets:
    - images/default.png

最後運行程序:

flutter run -d windows

源碼

https://github.com/yushulx/flutter_barcode_sdk

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章