Home > Mobile >  The non-nullable variable 'cameras' must be initialized
The non-nullable variable 'cameras' must be initialized

Time:02-24

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());
}

CodePudding user response:

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;

CodePudding user response:

Make the cameras variable. like:-

List <CameraDescription>? cameras;

CodePudding user response:

you can not leave a not null variable without assign dart null safety not allowing this..

Your Global variable camera is not initialized

List<> camera;//for global it is not acceptable

you can make List<>? camera;// now it is acceptable but you must need to initialize first before using it other wise it will throw exception 

CodePudding user response:

You can either make the cameras List nullable like this:

List<CameraDescription>? cameras;

OR if you don't want to make it nullable then you can make an empty cameras list like this:

List<CameraDescription> cameras = List<CameraDescription>.empty(growable: true);
  • Related