简体   繁体   English

Flutter中的LateInitializationError如何解决?

[英]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:大家好,我遇到了以下问题,希望有人能帮助我:我正在尝试使用以下代码将相机包含在我的 flutter 应用程序中:

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. LateInitializationError:字段“控制器”尚未初始化。

I have already tried to add the whenComplete() method and used ?我已经尝试添加whenComplete()方法并使用? but it didnt work either.但它也没有用。

Does anyone have an idea?有人有想法吗?

I think the problem is that you are running 'setupCameras()' which is asynchronous inside the 'initState()' method which is not.我认为问题在于您正在运行“setupCameras()”,它在“initState()”方法中是异步的,而这不是。 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)
        );
      };
    );
  }
}

I am having the same problem and I can't find a perfect solution.我有同样的问题,我找不到完美的解决方案。

  • I don't think FutureBuilder will work in this case.我认为 FutureBuilder 在这种情况下不起作用。 You need to handle the dispose as well.您还需要处理处置。 This seems not what you can do using FutureBuilder.这似乎不是您使用 FutureBuilder 可以做的事情。

  • The reality is that, you may not be able to initialize CameraController successfully.实际情况是,您可能无法成功初始化 CameraController。 For whatever reasons the getCameras doesn't return you anything.无论出于何种原因,getCameras 都不会返回任何东西。 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.这意味着您的 CameraController 始终有可能是 null。因此,尝试调整代码以强制其成为非 null 类型是不正确的。

I ended up just change it to nullable type and do null check whenever necessary.我最终只是将其更改为可空类型,并在必要时进行 null 检查。 IMO, dart is going to far for null safety. IMO,dart 为了 null 的安全而走得很远。 It just make things more complicated.它只会让事情变得更复杂。 I love the way Python handle nullable using None.我喜欢 Python 使用 None 处理可为空的方式。

CameraController? _controller;

I see two problems:我看到两个问题:

  1. setupCameras() does: setupCameras()会:

     try { //... } on CameraException catch () { setState(() { isReady = false; }); } setState(() { isReady = true; });

    which means that if a CameraException is thrown, isReady will be set to false but then immediately be set to true .这意味着如果抛出CameraExceptionisReady将设置为false ,然后立即设置为true

  2. The build function does: build function 执行以下操作:

     if (.isReady &&._controller;value.isInitialized) { return Container(); }

    If isReady is false (which I assume should indicate that _controller isn't yet initialized), then you additionally check _controller.value.isInitialized even though _controller isn't initialized yet.如果isReady为假(我假设这应该表明_controller尚未初始化),那么即使_controller尚未初始化,您也会另外检查_controller.value.isInitialized You probably want ||你可能想要|| instead && .而是&&

Alternatively, consider just making _controller nullable instead of late .或者,考虑只使_controller可以为空而不是late If you need to check a boolean flag ( isReady ) before accessing _controller anyway, that's no better than making _controller nullable and checking _controller != null directly, which is more straightforward and less error-prone.如果您需要在访问_controller之前检查 boolean 标志( isReady ),这并不比使_controller为空并直接检查_controller != null ,这更简单,更不容易出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM