YOLOv8/9 object detection in Flutter with TensorFlow Lite (.tflite) 2024
Object detection is a technique used in computer vision for the identification and localization of objects within an image or a video. Image Localization is the process of identifying the correct location of one or multiple objects using bounding boxes, which correspond to rectangular shapes around the objects.
This process is sometimes confused with image classification or image recognition, which aims to predict the class of an image or an object within an image into one of the categories or classes.
YOLO developers frame the object detection problem as a regression problem instead of a classification task by spatially separating bounding boxes and associating probabilities to each of the detected images using a single convolutional neural network (CNN) as shown here.

Some of the reasons why YOLO is leading the competition include its:
- Speed
- Detection accuracy
- Good generalization
- Open-source
Deploying YOLO model into flutter app to recognize objects by the phone camera:
- Create new project & Setup Your Environment:
In android/app/build.gradle, add the following setting in android block.
android{
aaptOptions {
noCompress 'tflite'
noCompress 'lite'
}
}In the same path of android/app/build.gradle, adjust “minSdkVersion”, “targetSdkVersion” and “compileSdkVersion” in android block as following:

android/app/build.gradle --> android blockIn android/build.gradle, adjust “ext.kotlin_version” buildscript block to be as this:
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}- Add your Yolov8 model into the project environment:
The model must be exported in form of “.tflite” to easy deployed on edge-device like the mobile phone. If you want to train your custom Yolov model in Python and export it in .tflite instead of .pt, you must follow the instructions here. I’ll insert here a ready pre-trained Yolov8 model for object detection for testing.
In your Flutter project:
1. Create a assets folder and place your labels file and model file in it. In pubspec.yaml add:
assets: - assets/labels.txt - assets/yolov8n.tflite
2. Import the required Packages flutter_vision / camera:
import 'package:flutter_vision/flutter_vision.dart';
import 'package:camera/camera.dart';- Start Coding:
- Initialize the camera in your project as the following:
late List<CameraDescription> camerass;2. Create “YoloVideo” class:
class YoloVideo extends StatefulWidget {
const YoloVideo({Key? key}) : super(key: key);
@override
State<YoloVideo> createState() => _YoloVideoState();
}
class _YoloVideoState extends State<YoloVideo> {
// Here we start writing our code.
}3. In “YoloVideo” class, declare the needed variables:
late CameraController controller;
late FlutterVision vision;
late List<Map<String, dynamic>> yoloResults;
CameraImage? cameraImage;
bool isLoaded = false;
bool isDetecting = false;
double confidenceThreshold = 0.5;
4. Initialize the model and the camera:
@override
void initState() {
super.initState();
init();
}
init() async {
camerass = await availableCameras();
vision = FlutterVision();
controller = CameraController(camerass[0], ResolutionPreset.high);
controller.initialize().then((value) {
loadYoloModel().then((value) {
setState(() {
isLoaded = true;
isDetecting = false;
yoloResults = [];
});
});
});
}
@override
void dispose() async {
super.dispose();
controller.dispose();
await vision.closeYoloModel();
}
5. Simple UI and determine Video Stream size
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
if (!isLoaded) {
return const Scaffold(
body: Center(
child: Text("Model not loaded, waiting for it"),
),
);
}
return Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
AspectRatio(
aspectRatio: controller.value.aspectRatio,
child: CameraPreview(
controller,
),
),
...displayBoxesAroundRecognizedObjects(size),
Positioned(
bottom: 75,
width: MediaQuery.of(context).size.width,
child: Container(
height: 80,
width: 80,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
width: 5, color: Colors.white, style: BorderStyle.solid),
),
child: isDetecting
? IconButton(
onPressed: () async {
stopDetection();
},
icon: const Icon(
Icons.stop,
color: Colors.red,
),
iconSize: 50,
)
: IconButton(
onPressed: () async {
await startDetection();
},
icon: const Icon(
Icons.play_arrow,
color: Colors.white,
),
iconSize: 50,
),
),
),
],
),
);
}6. Loading of our model
Future<void> loadYoloModel() async {
await vision.loadYoloModel(
labels: 'assets/CLASSES.txt',
modelPath: 'assets/curr_float32.tflite',
modelVersion: "yolov8",
numThreads: 1,
useGpu: true);
setState(() {
isLoaded = true;
});
}
// Real-time object detection function by yoloOnFrame
Future<void> yoloOnFrame(CameraImage cameraImage) async {
final result = await vision.yoloOnFrame(
bytesList: cameraImage.planes.map((plane) => plane.bytes).toList(),
imageHeight: cameraImage.height,
imageWidth: cameraImage.width,
iouThreshold: 0.4,
confThreshold: 0.4,
classThreshold: 0.5);
if (result.isNotEmpty) {
setState(() {
yoloResults = result;
});
}
}7. functions of Starting Video Stream & Start or Stop detection
Future<void> startDetection() async {
setState(() {
isDetecting = true;
});
if (controller.value.isStreamingImages) {
return;
}
await controller.startImageStream((image) async {
if (isDetecting) {
cameraImage = image;
yoloOnFrame(image);
}
});
}
Future<void> stopDetection() async {
setState(() {
isDetecting = false;
yoloResults.clear();
});
}8. Bounding boxes around the detected objects
List<Widget> displayBoxesAroundRecognizedObjects(Size screen) {
if (yoloResults.isEmpty) return [];
double factorX = screen.width / (cameraImage?.height ?? 1);
double factorY = screen.height / (cameraImage?.width ?? 1);
Color colorPick = const Color.fromARGB(255, 50, 233, 30);
return yoloResults.map((result) {
double objectX = result["box"][0] * factorX;
double objectY = result["box"][1] * factorY;
double objectWidth = (result["box"][2] - result["box"][0]) * factorX;
double objectHeight = (result["box"][3] - result["box"][1]) * factorY;
speak() {
String currentResult = result['tag'].toString();
DateTime currentTime = DateTime.now();
if (currentResult != previousResult ||
currentTime.difference(previousSpeechTime) >= repeatDuration) {
tts.flutterSpeak(currentResult);
previousResult = currentResult;
previousSpeechTime = currentTime;
}
}
speak();
return Positioned(
left: objectX,
top: objectY,
width: objectWidth,
height: objectHeight,
child: Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(10.0)),
border: Border.all(color: Colors.pink, width: 2.0),
),
child: Text(
"${result['tag']} ${(result['box'][4] * 100)}",
style: TextStyle(
background: Paint()..color = colorPick,
color: const Color.fromARGB(255, 115, 0, 255),
fontSize: 18.0,
),
),
),
);
}).toList();
}
}Finally, you can call the YoloVideo class as a function in Main.dart to start video stream and real-time object detection when starting the application to as the following:
main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(
const MaterialApp(
home: YoloVideo(),
),
);
}
Sources & Materials:
- flutter_vision | Flutter package (pub.dev)
- https://drive.google.com/drive/folders/15LU4lWiMx8DjBXE7q7Efx65OF4Zb-5ZA?usp=sharing
- YOLO Object Detection Explained: A Beginner’s Guide | DataCamp
- camera | Flutter package (pub.dev)
- Flutter AI | Flutter Realtime Object Detection | Flutter Deep Learning | Flutter TensorFlow | TFlite (youtube.com)
- TFLite — Ultralytics YOLOv8 Docs
- https://github.com/AarohiSingla/Object-Detection-Android-App





