How do I solve the LateInitializationError in Flutter?

1,603

Solution 1

I think the problem is that you are running 'setupCameras()' which is asynchronous inside the 'initState()' method which is not. Try this:

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<Route02> {
  late List<CameraDescription> cameras;
  late CameraController _controller;


  Future<void> setupCameras() async {
    try {
      cameras = await availableCameras();
      _controller = new CameraController(cameras[0], ResolutionPreset.ultraHigh);
      await controller.initialize();
  }

  Widget build(BuildContext context) {
    return FutureBuilder(
      future: setupCameras(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return AspectRatio(
          aspectRatio: _controller.value.aspectRatio,
          child: CameraPreview(_controller)
        );
      };
    );
  }
}

Solution 2

I am having the same problem and I can't find a perfect solution.

  • I don't think FutureBuilder will work in this case. You need to handle the dispose as well. This seems not what you can do using FutureBuilder.

  • The reality is that, you may not be able to initialize CameraController successfully. For whatever reasons the getCameras doesn't return you anything. That means it is always possible that your CameraController can be null. So, trying to tweak the code to force this to be non null type is not right.

I ended up just change it to nullable type and do null check whenever necessary. IMO, dart is going to far for null safety. It just make things more complicated. I love the way Python handle nullable using None.

CameraController? _controller;
Share:
1,603
Bassir Ahmad
Author by

Bassir Ahmad

Updated on December 20, 2022

Comments

  • Bassir Ahmad
    Bassir Ahmad over 1 year

    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<Route02> {
      late List<CameraDescription> cameras;
      late CameraController _controller;
      bool isReady = false;
    
      @override
      void initState() {
        super.initState();
        setupCameras();
      }
    
      Future<void> 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?