不可为 null 的变量“cameras”;必须初始化
当我尝试使用相机变量时,我的代码中出现以下错误。如何纠正这个问题。感谢您对此的帮助。
The non-nullable variable 'cameras' must be initialized.
CameraScreen.dart
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
List <CameraDescription> cameras;
class CameraScreen extends StatefulWidget {
const CameraScreen({Key? key}) : super(key: key);
@override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
main.dartt
Future <void> main() async{
WidgetsFlutterBinding.ensureInitialized();
cameras =await availableCameras();
runApp(const MyApp());
}
I'm getting below error in my code when I'm trying to use cameras variable. how to correct this. appreciate your help on this.
The non-nullable variable 'cameras' must be initialized.
CameraScreeen.dart
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
List <CameraDescription> cameras;
class CameraScreen extends StatefulWidget {
const CameraScreen({Key? key}) : super(key: key);
@override
_CameraScreenState createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen> {
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
main.dartt
Future <void> main() async{
WidgetsFlutterBinding.ensureInitialized();
cameras =await availableCameras();
runApp(const MyApp());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是由于 Flutter 和 Dart 健全的 null 安全特性。
变量现在不能为空,如果您想接受
null
值,则必须使用?
使它们可为空,例如:
List? Camera;
如果您仍然不想使它们可为空,那么您可以使用
late
关键字,它允许我们稍后初始化值,但我们必须确保它之前已初始化正在某处使用。例如:
late List相机;
This is due to the sound null safety feature of Flutter and Dart.
Variables cannot be null now if you want to accept them
null
values you have to make them nullable using?
for example:
List <CameraDescription>? cameras;
If you still don't want to make them nullable then you can use a
late
keyword which allows us to initialize value later on but we have to make sure that it is initialized before is being used somewhere.for example:
late List <CameraDescription> cameras;
使相机可变。
喜欢:-
Make the cameras variable.
like:-
您不能在没有分配 dart null 安全性的情况下留下非空变量,不允许这样做。
您的全局变量相机未初始化
you can not leave a not null variable without assign dart null safety not allowing this..
Your Global variable camera is not initialized
您可以将
cameras List
设置为可为空,如下所示:或者,如果您不想使其可为空,则可以创建一个空相机列表,如下所示:
You can either make the
cameras List
nullable like this:OR if you don't want to make it nullable then you can make an empty cameras list like this: