How do I solve the LateInitializationError in Flutter?

Hey guys i am havin the following problem and i hope someone can help me: I am trying to include the camera in my flutter app by using the following code:

import ‘dart:async’;
import ‘package:flutter/material.dart’;
import ‘package:camera/camera.dart’;

class Route02 extends StatefulWidget {
@override
CameraState createState() => CameraState();
}

class CameraState extends State {
late List cameras;
late CameraController _controller;
bool isReady = false;

@override
void initState() {
super.initState();
setupCameras();
}

Future setupCameras() async {
try {
cameras = await availableCameras();
_controller = new CameraController(cameras[0], ResolutionPreset.ultraHigh);
await controller.initialize();
} on CameraException catch () {
setState(() {
isReady = false;
});
}
setState(() {
isReady = true;
});
}

Widget build(BuildContext context) {
if (!isReady && !_controller.value.isInitialized) {
return Container();
}
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
child: CameraPreview(_controller));
}
}

When accessing the camera part within the app the following error can be seen and afterwards the camera will start anyway:

LateInitializationError: Field ‘controller’ has not been initialized.

I have already tried to add the whenComplete() method and used ? but it didnt work either.

Does anyone have an idea?

Hello, I think it should be

with the underscore. Hth

Hey i already fixed that and it wasnt that. Still get the same error

No I didn’t say remove the ?. I’m saying IF you use late, you need to be sure to assign something to it before using it. Otherwise it is null and that’s an error. Try assigning it a value in the very beginning of the build() method, for example.

Someone write this at stackoverflow it’s about LateInitializationError too. And i dont quite understand. But perhaps it may help you ?

How did you fix it Bassir?

Can you please share that?

1 Like

How did you fix it Bassir?

Can you please share that?

I’d love for you to share the solution if you got it.