Flutter app error - getter 'value' was called on null
我正在构建一个应用程序,需要在"相机"视图顶部显示一些内容。 这是我的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | 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--- ], ), ); } } |
每当我构建应用程序时,都会出现以下错误...
1 2 3 4 5 | 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 |
无法判断。 找出错误所在。
如果您已经为变量创建并分配了值,但仍显示
尝试
在
这意味着它可以为空。 因此,在
1 | (!this.controller?.value?.initialized ?? false) ? new Container() : cameraView , |
我之前遇到过此问题,并在
1 | aspectRatio: (this.controller?.value?.aspectRatio) ?? false |
大多数时候。