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
Related
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
I am working on a flutter app and wanted one of my classes to have the same id property. This is because I can have either an event or an exception, but I would like the same function to manage both. To do this, I have a switch statement that checks res.id to determine which type of event it is. The response can either be an Event instance or an Exception instance.
Exception is an import class and I'd rather not have to wrap it in an Event instance so I thought I could just hardcode id = EventIds.error. This way every error will have an id that matches an error event - thus it can be accessed and dealt with in the original switch statement.
My issue is I don't want to have to go all throughout my code and add a new argument to each instantiation. See the code below.
Exception.dart
class Exception {
/// Always initialize with id that is error id
/// This is for onCaptureEvent
int id = EventIds.error;
int code = 0;
String message = 'no error';
String? method;
String? details;
Exception(id, this.code, this.message, [this.method, this.details]);
}
Instantiation Current
Exception ex = new Exception(-93, 'Unable to validate')
I want to be able to have every instance of Exception have an id of EventIds.error WITHOUT having to go through every instantiation in my code and add it like so:
Exception ex = new Exception(EventIds.error, -93, 'Unable to validate')
Is this achievable in Flutter?
It was really simple. I just needed to write out my Exception class like so:
Exception.dart
class Exception {
/// Always initialize with id that is error id
/// This is for onCaptureEvent
int id = EventIds.error;
int code = 0;
String message = 'no error';
String? method;
String? details;
Exception(this.code, this.message, [this.method, this.details]);
}
This way the instances will always use the default value for id. This is also safer bc now the user cannot change the ID if they wanted to provide another argument (Exception(supplied_id, code, message)) because it will throw a syntax error saying the second argument is supposed to be a string.
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.
I want to build a method to dynamically save attributes on a specific object
given the attribute name and the value to save I call the "save()" function to update the global targetObj
var targetObj = targetClass();
save(String attribute, String value){
targetObj.attribute = value;
print(targetObj.attribute);
}
But I'm getting the following error:
Class 'targetClass' has no instance setter 'attribute='.
Receiver: Instance of 'targetClass'
Tried calling: attribute="Foo"
The only thing that I can think of is that "attribute" due to being type String results in an error.
That lead me to think if there is a way to read a String as code, something like eval for php.
As #Randal mentioned, you cannot create class..method at runtime. Still, you can try something like this.
A certain class
class Foo {
dynamic bar1;
dynamic bar2;
// ...
}
Your save method
save(Foo fooObject, String attribute, dynamic value) {
if ("bar1" == attribute) fooObject.bar1 = value;
else if ("bar2" == attribute) fooObject.bar2 == value;
// ...
}
Dart (and thus flutter) does not have a way to compile and execute code at runtime (other than dart:mirrors, which is deprecated). You can build additional code that derives from other code using the various builder mechanisms, although it can be rather complicated to implement (and use!).
i work with flutter framework
this part of the code use a operation "?." but idont understand
if (state is WeatherLoaded) {
final weather = state.weather;
final themeBloc = BlocProvider.of<ThemeBloc>(context);
themeBloc.dispatch(WeatherChanged(condition: weather.condition));
_refreshCompleter?.complete();
_refreshCompleter = Completer();
all code this link
The best way to demonstrate this is a simple example.
I have an object SomeObject with one method username.
I have made 2 instances of it:
aeonObject which is not null
someOtherObject which is null
class SomeObject {
String username() => "aeon";
}
void main() {
final aeonObject = SomeObject();
print(aeonObject.username());
SomeObject someOtherObject;
print(someOtherObject.username());
}
If I execute this snippet you'll see the following output.
The program will crash because we tried to execute a method on a null reference.
dart lib/main.dart
lib/main.dart: Warning: Interpreting this as package URI, 'package:sample/main.dart'.
aeon
Unhandled exception:
NoSuchMethodError: The method 'username' was called on null.
Receiver: null
Tried calling: username()
However if I call the print statement with the ?. aka Conditional member access operator.
print(someOtherObject?.username());
We instead get.
null
Check this link: Language tour
?.
Conditional member access
Like ., but the leftmost operand can be null; example: foo?.bar
selects property bar from expression foo unless foo is null (in which
case the value of foo?.bar is null)