Home > Net >  Why does it keep saying initialize variable?
Why does it keep saying initialize variable?

Time:07-16

Below is the code I wrote. I need to initialize a variable called verificationID for later use. But I keep getting a red squiggly line with the text -

  1. Final variable verificationID must be initialized
  2. Non-nullable instance field vdi must be initialized.

Is this not how you initialize - final [datatype] [name]

I am brand new to flutter and could use any help!

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
enum NumberVerification {
  SHOW_MOBILE_FORM_STATE,
  SHOW_OTP_FORM_STATE,
}

class LoginScreen extends StatefulWidget {
  final String verificationID;
  String vdi;
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

CodePudding user response:

All variables in Dart are getting the value null if nothing else are specified. This is a problem in your case since both verificationID and vdi are specified as non-nullable types (no ? after the type name). So Dart complains about this problem.

Another problem is your final variable which also should be provided a value since this is a read-only variable which can only be assigned a value when initialized.

You therefore need to do:

  • Change the types to allow null.
  • Or, provide default value other than null.
  • Or, make a constructor of your class which gives values to your variables. These values can come from parameters to the constructor.

CodePudding user response:

Because flutter and dart language are null safety. It means you should initialize your variables, and there will be no error regarding this in runtime. So when you write dart codes you must initialize them as follows:

1- In some cases you can init value directly as follows:

final String verificationID = 'value';

2- Or you can get the value from constructor of class.

final String verificationID;

LoginScreen(this.verificationID);

3- And also, you can declare that you will initialize the value later. This way you guarantee that you will initialize the value, so you should use it wisely.

late String verificationID;

verificationID = 'value';

4- Lastly, you may declare a value as nullable. This way, you don't need to initialize the variable directly.

String? verificationID;
  • Related