Flutter 应用程序错误 - 在 null 上调用了 getter 'value'

Sur*_*esh 18 dart flutter

我正在构建一个应用程序,我需要在“相机”视图之上显示一些内容。这是我的代码。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';

List<CameraDescription> cameras;

void main() async {
  runApp(new MaterialApp(
    home: new CameraApp(),
  ));

}

class CameraApp extends StatefulWidget {
  @override
  _CameraAppState createState() => new _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  CameraController controller;
  var cameras;
  bool cameraGot = false;

  Future<Null> getCamera() async {
    cameras = await availableCameras();
    setState(() {
      this.cameras = cameras;
      this.cameraGot = true;
    });
  }

  @override
  void initState() {
    getCamera();
    super.initState();

    if(this.cameraGot) {
      controller = new CameraController(this.cameras[0], ResolutionPreset.medium);
      controller.initialize().then((_) {
        if (!mounted) {
          return;
        }
        setState(() {});
      });
    }

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    // camera widget
    Widget cameraView = new Container(
      child: new Row(children: [
          new Expanded(
            child: new Column(
                children: <Widget>[
                  new AspectRatio(
                    aspectRatio:
                        controller.value.aspectRatio,
                        child: new CameraPreview(controller)
                  )
                ]
            ),
          )
      ])
    );


    return new Scaffold(
      body: new Stack(
        children: <Widget>[
          !this.controller.value.initialized ? new Container() : cameraView,

           // ---On top of Camera view add one mroe widget---

        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

每当我构建应用程序时,我都会遇到以下错误...

I/flutter ( 6911): ??? EXCEPTION CAUGHT BY WIDGETS LIBRARY ????????????????????????????????????????????????????????????
I/flutter ( 6911): The following NoSuchMethodError was thrown building CameraApp(dirty, state: _CameraAppState#b6034):
I/flutter ( 6911): The getter 'value' was called on null.
I/flutter ( 6911): Receiver: null
I/flutter ( 6911): Tried calling: value
Run Code Online (Sandbox Code Playgroud)

想不出来 出了什么错误。

小智 23

如果您已创建变量并为其分配值,但它仍然显示getter 'value' was called on null,请尝试使用Run或Restart您的应用程序代替Hot Reload。因为Hot Reload不会调用initstate()(变量赋值的地方),它只会被Restarting应用程序调用。


Rém*_*let 8

在 中initState,您并不总是实例化控制器。

这意味着它可以null。因此在build方法内部,您需要检查 null 以防止崩溃

(!this.controller?.value?.initialized ?? false) ? new Container() : cameraView ,
Run Code Online (Sandbox Code Playgroud)