A guide to adding C library to a Flutter project using Dart FFI with OpenCV as an example
What would you do if you wanted your Flutter app to be as much performant as possible, or there was no package in pub that you need? Probably, you would use native Java/Objective-C libraries and communicate with them using Platform Channels. But what if both platforms share the same business logic? Surely, nobody wants to write the same code twice in two different languages.
The purpose of this article is to help Flutter developers set up their project to use a native C or C++ library and write a single code base that uses it. As an example, the article describes the process of adding the OpenCV library to a Flutter app project.
Dart Foreign Function Interface (FFI) allows us to call native C/C++ functions on both iOS and Android platforms without using Platform Channels or making Java/Objective-C bindings. That leads to having a single code base written in C with zero platform-specific code.
OpenCV is a computer vision library that contains a lot of services used for image processing. It is mainly written in C++.
Even though it’s not required, it’s better to create a Flutter plugin to separate all task-specific stuff from the main application. Run flutter create — template=plugin native_opencv
command to create it.
Next, we need to update the app’s dependency list in pubspec.yaml with a newly created plugin and ffi package:
dependencies:
native_opencv:
path: native_opencv
ffi: ^0.1.3
ffi package comes in handy for working with C UTF-8/UTF-16 strings.
#flutter #dart #c