Home > Mobile >  lateIntailizatationError and Nullcheckoperator
lateIntailizatationError and Nullcheckoperator

Time:12-07

when I compiled my app the error{LateInitializationError: Field 'contorller' has not been initialized} appeared and when I changed the Late keyword with ? operator and Put ! before the methods that depends on the variable like stackoverflow suggests another error appeared {Null check operator used on a null value} so how can I solved that

itis a statful class

class _MyHomePageState extends State<MyHomePage> {
BarcodeDetector ?labeler;
CameraController? controller;
bool isBusy = false;
String result = "";
File ?_image;
ImagePicker ?imagePicker;
CameraImage ?img;
void initState() {
super.initState();
labeler = FirebaseVision.instance.barcodeDetector();
  }
intializeCamera() async {
controller = CameraController(cameras[0], ResolutionPreset.medium);
await controller!.initialize().then((_) {
if (!mounted) {
return;
}
controller!.startImageStream((image) => {
if (!isBusy) {isBusy = true, img = image, doBarcodeScanning()}
});
});
  }



void dispose() {
controller!.dispose();
labeler!.close();
super.dispose();
  }



Center(
child: Container(
margin: EdgeInsets.only(top: 100),
height: 220,
width: 220,
child: AspectRatio(
aspectRatio: controller!.value.aspectRatio,
child: CameraPreview(controller),
),
),
),

CodePudding user response:

intializeCamera() is a future method, I will encourage you to use FutureBuilder in this case. It takes some time to initialize data being future.

Second case is controller is nullable, means it can receive null data, which is good to have. CameraController? controller;

But while using a null check on it, then handle the situation.

You can also just handle like this

  if (controller != null)
                  Center(
                    child: Container(
                      margin: EdgeInsets.only(top: 100),
                      height: 220,
                      width: 220,
                      child: AspectRatio(
                        aspectRatio: controller!.value.aspectRatio,
                        child: CameraPreview(controller),
                      ),
                    ),
                  ),

CodePudding user response:

Initialise your controllers in initState() before using them in build() and don't define controllers as null - rather use the late keyword.

  • Related