Uncaught LateInitializationError: Field 'deviceToken' has not been initialized - flutter

Error: Uncaught LateInitializationError: Field 'deviceToken' has not been initialized.
Not sure what went wrong here.
late String deviceToken;
var registerRepo = GoogleSignInRepo();
FirebaseAuth auth = FirebaseAuth.instance;
Future<String> gettoken() async {
final String? token = await FirebaseMessaging.instance.getToken();
return token!;
}
#override
void initState() {
gettoken().then((value) {
deviceToken = value;
});
super.initState();
}

Well the error pretty much tells you the problem:
Error: Uncaught LateInitializationError: Field 'deviceToken' has not been initialized.
Flutter is null-safe, therefore if you define a variable you need to assign a value to it since the value by definition is not allowed to be null. Keep in mind that the late keyword only tells you that the variable will be initialized at runtime instead of compile time.
This means that some other part of your code probably accesses deviceToken before it was initialized in your Future.
You can solve it like this:
// Assign a value (empty string in this case).
String deviceToken = "";
Another solution would be to make your field nullable and this is probably the better solution in your case.
// Null is a valid value and will not cause a error.
String? deviceToken;
Or: Make sure the field was initialized before you access it.
For further reference this article might help you out:
https://dart.dev/null-safety/understanding-null-safety

Related

Field ‘#’ has not been initialized

Im using some code from a tutorial but putting it in my own app. I cant figure out the next warning and how to solve:
LateInitializationError: Field ‘_durationRemaining#585382383’ has not been initialized.
The code(piece of the whole code) where this error is from is:
late MapBoxNavigation _directions;
late MapBoxOptions _options;
bool _isMultipleStop = false;
late double _distanceRemaining, _durationRemaining;
late MapBoxNavigationViewController _controller;
bool _routeBuilt = false;
bool _isNavigating = false;
#override
void initState() {
super.initState();
initialize();
}
The error is about the rule:
late double _distanceRemaining, _durationRemaining;
Am i doing something wrong? Maybe because i have 2 fields behind the late double and not the right way?
If i delete the Late in front of double, then get this errors:
lib/main.dart:42:10: Error: Field ‘_distanceRemaining’ should be initialized because its type ‘double’ doesn’t allow null.
double _distanceRemaining, _durationRemaining;
^^^^^^^^^^^^^^^^^^
lib/main.dart:42:30: Error: Field ‘_durationRemaining’ should be initialized because its type ‘double’ doesn’t allow null.
double _distanceRemaining, _durationRemaining;
When defining any variable as late, it must be initialized with the specified type before accessing it. In your case, it should be initialized in the initState() function. If you don't want to use the late keyword, you could make your variable nullable by using the ? operator.
For Eg
double? _distanceRemaining, _durationRemaining;
This would make your double variable nullable meaning it could accept null values.
If I do that I get:
264:60: Error: Operator '/' cannot be called on 'double?' because it is potentially null.
? "${(_durationRemaining / 60).toStringAsFixed(0)} minutes"
272:60: Error: Operator '*' cannot be called on 'double?' because it is potentially null.
? "${(_distanceRemaining * 0.000621371).toStringAsFixed(1)} miles"
The code there is:
? "${(_durationRemaining / 60).toStringAsFixed(0)} minutes"
? "${(_distanceRemaining * 0.000621371).toStringAsFixed(1)} miles"
I have to change something there also I guess. Because there it cant be null?
When a variable is nullable, you are restricted to using the normal operations and function calls that can be used on non-nullable variables.
For eg
double? _durationRemaining;
var x = _durationRemaing + 10;
You cannot do this operation because _durationRemaing can be null. For this, you can use the ?? operator, which checks whether the variable is null or not.
var x = (_durationRemaing ?? 0) + 10;
This means that if the variable is null use 0 as the value. So you have to use the ?? operator in your code mentioned above.

Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used

I have assigned the variable inside the setUp() method but still its throwing error. The test is running successfully if I made the MockBuildContext nullable but it is not the correct approach. Is there anything I missed out or suggest a better way to solve this.
See my code:
void main(){
MockBuildContext mockBuildContext;
setUpGetIt(testing: true);
setUp((){
mockBuildContext = MockBuildContext();
});
group("banks test", (){
test("Calling fetchAllBanks returns instance of BanksModel list", () async {
banksBloc.init(mockBuildContext);
await banksBloc.fetchAllBanks();
banksBloc.allBanks?.listen((event) {
expect(event, isInstanceOf<List<BanksModel>>);
});
});
});
}
My error log:
C:\Src\flutter\bin\flutter.bat --no-color test --machine --start-paused test\unit_test\system\bank_configuration\banks_test.dart
Testing started at 18:52 ...
test/unit_test/system/bank_configuration/banks_test.dart:24:22: Error: Non-nullable variable 'mockBuildContext' must be assigned before it can be used.
banksBloc.init(mockBuildContext);
^^^^^^^^^^^^^^^^
add question mark MockBuildContext? to make it nullable or initialize it if it's non-nullable, or add late keyword in start late MockBuildContext mockBuildContext;
you can either initialize it with the declaration
i.e MockBuildContext mockBuildContext = MockBuildContext();
or you can add late before the declaration and initialize it as you are doing in the setup function
i.e late MockBuildContext mockBuildContext;

Non-nullable instance field '_dio' must be initialized Flutter

I am using Dio for Json parsing and i have created a class for simple Json parsing and serializing but i am getting the following error
Non-nullable instance field '_dio' must be initialized. (Documentation) Try adding an initializer expression, or add a field initializer in this constructor, or mark it 'late'.
Below is the code for my class
Dio _dio;
final baseUrl = "";
HttpService(){
_dio = Dio(BaseOptions(
baseUrl:
));
}
What might i be doing wrong
Your variable _dio is non-nullable which means it can never be null.
However when you put Dio _dio; it doesn't get a value.
You have 2 options:
Either make it nullable by putting a ? after the type: Dio? _dio;
or make it a late variable late Dio _dio; which means that it will shortly after get a value (hopefully _dio = Dio(BaseOptions(baseUrl:)); will do so) so that it can be treated as "never null" afterwards.
EDIT:
More on that topic: https://dart.dev/null-safety

What is the difference between using `late` keyword before the variable type or using `?` mark after the variable type it in the Flutter?

I think in new Dart rules the variables can not be declared/initialized as null. So we must put a late keyword before the variable type like below:
late String id;
Or a ? mark after the variable type like below:
String? id;
Are these two equal Or there are some differences?
A nullable variable does not need to be initialized before it can be used.
It is initialized as null by default:
void main() {
String? word;
print(word); // prints null
}
The keyword late can be used to mark variables that will be initialized later, i.e. not when they are declared but when they are accessed. This also means that we can have non-nullable instance fields that are initialized later:
class ExampleState extends State {
late final String word; // non-nullable
#override
void initState() {
super.initState();
// print(word) here would throw a runtime error
word = 'Hello';
}
}
Accessing a word before it is initialized will throw a runtime error.
when you use late keyword you can't let variable uninitialized when you called it with ? allows to you let variable uninitialized when you create it and call it
Null safety rules doesn't mean you can't use null. You can, but you should indicate that a variable might have the value null, by add "?" to its type declaration.
By use keyword late you indicate that variable has a non-nullable type, is not initialized yet, but will be initialized later.
Exception is thrown if try to acсess value of late variable before initialization.

Flutter-Non-nullable instance field ‘{0}’ must be initialized error

I have created a seperate class "DirectionDetails" which is;
class DirectionDetails{
int distanceValue;
int durationValue;
String distanceText;
String durationText;
String encodedPoints;
DirectionDetails(this.distanceValue, this.durationValue, this.distanceText, this.durationText, this.encodedPoints);
}
When I try to initialize that in the main class by DirectionDetails tripDirectionDetails;, it gives the
Non-nullable instance field 'tripDirectionDetails' must be initialized
error. But as it suggest, when I add "late" modifier - it dosen't show any errors but when i run the app it gives the,
LateInitializationError: Field 'tripDirectionDetails' has not been
initialized.
runtime error
There is an alternative method I tried, when i try to initialize tripDirectionDetails in main class using,
DirectionDetails tripDirectionDetails = new DirectionDetails();
and modify DirectionDetails class by,
class DirectionDetails{
int distanceValue;
int durationValue;
String distanceText;
String durationText;
String encodedPoints;
DirectionDetails({this.distanceValue = 0, this.durationValue = 0, this.distanceText = "", this.durationText = "", this.encodedPoints = ""});
}
App runs successfully, it retrieves all the vales in "DirectionDetails" class only for the initial reboot.
But when I exit the app and come back, it gives the following error.
LateInitializationError: Field 'tripDirectionDetails' has not been
initialized.
Your help is much appreciated.
Thank you
That is happening because you are trying to use tripDirectionDetails before initializing it. You should use late only for non null variables that will be initialized later before trying to use:
tripDirectionDetails != null /// This will trigger an error
You should initialize it before using it on build or in initState:
#override
void initState() {
tripDirectionDetails = DirectionDetails();
super.initState();
}
But as tripDirectionDetails can be null, it would be better to declare it like this:
DirectionDetails? tripDirectionDetails;
tripDirectionDetails != null /// Won't trigger an error