Initialize all Flutter class instances with same ID and no need to provide argument - flutter

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.

Related

Set Duration from parameters in Flutter [duplicate]

Why does this code:
class _SequentialTextPageState {
String jsonTextPref = 'seqtext';
int jsonTextSuff = 10;
String jsonText = jsonTextPref + jsonTextSuff.toString();
}
generate these errors?
Error: The instance member 'jsonTextPref' can't be accessed in an initializer.
Error: The instance member 'jsonTextSuff' can't be accessed in an initializer.
It seems to me that concatenation between String and int is correct?
Dart initializes objects in multiple phases. Initializing members directly ("field initializers") occurs early in object initialization, before this becomes valid, so that phase cannot initialize members that depend on other parts of the object.
Dart provides multiple ways to initialize members, so if one member needs to depend on another, you can initialize it in a later phase by using a different mechanism. For example, you could do one of:
Add the late keyword to make the dependent member lazily initialized.
Move initialization of the dependent member into the constructor body.
In the case of a Flutter State subtype, you could initialize the dependent member in its initState method, which in some cases is more appropriate.
Note that in some cases you additionally can consider replacing the member variable with a read-only getter instead. For example, in your case, perhaps you could use:
String get jsonText => jsonTextPref + jsonTextSuff.toString();
That would be appropriate if jsonText should always depend on jsonTextPref and jsonTextSuff, would never need to have an independent value, and if it's acceptable for jsonText to return a new object every time it's accessed.
Dart does not allow field initializers to refer to the object itself. Fields must always be fully initialized before any access is given to the object begin created.
The initializers can only access static and top-level variables, not any instance variables on the object itself.
With null safety, you will be allowed to write late String jsonText = this.something + this.other;. That field will then not be initialized until it's first read or written, which is necessarily after the object itself has been created.
You can only use constant expressions as initializers. x=this.y is not constant.
The error was displayed when I did following:
class MyClass {
String id;
String[] imagePaths;
}
It will mark the String in the line String id; as error, but the error is in the next line, it should be List<String> imagePaths; instead of String[] imagePaths; then the error in the line above also disappears. This can be very confusing if you have a big class and the actual error is many lines underneath the first marked line (talking from experience...)

Flutter - variable getting assigned for once [duplicate]

Why does this code:
class _SequentialTextPageState {
String jsonTextPref = 'seqtext';
int jsonTextSuff = 10;
String jsonText = jsonTextPref + jsonTextSuff.toString();
}
generate these errors?
Error: The instance member 'jsonTextPref' can't be accessed in an initializer.
Error: The instance member 'jsonTextSuff' can't be accessed in an initializer.
It seems to me that concatenation between String and int is correct?
Dart initializes objects in multiple phases. Initializing members directly ("field initializers") occurs early in object initialization, before this becomes valid, so that phase cannot initialize members that depend on other parts of the object.
Dart provides multiple ways to initialize members, so if one member needs to depend on another, you can initialize it in a later phase by using a different mechanism. For example, you could do one of:
Add the late keyword to make the dependent member lazily initialized.
Move initialization of the dependent member into the constructor body.
In the case of a Flutter State subtype, you could initialize the dependent member in its initState method, which in some cases is more appropriate.
Note that in some cases you additionally can consider replacing the member variable with a read-only getter instead. For example, in your case, perhaps you could use:
String get jsonText => jsonTextPref + jsonTextSuff.toString();
That would be appropriate if jsonText should always depend on jsonTextPref and jsonTextSuff, would never need to have an independent value, and if it's acceptable for jsonText to return a new object every time it's accessed.
Dart does not allow field initializers to refer to the object itself. Fields must always be fully initialized before any access is given to the object begin created.
The initializers can only access static and top-level variables, not any instance variables on the object itself.
With null safety, you will be allowed to write late String jsonText = this.something + this.other;. That field will then not be initialized until it's first read or written, which is necessarily after the object itself has been created.
You can only use constant expressions as initializers. x=this.y is not constant.
The error was displayed when I did following:
class MyClass {
String id;
String[] imagePaths;
}
It will mark the String in the line String id; as error, but the error is in the next line, it should be List<String> imagePaths; instead of String[] imagePaths; then the error in the line above also disappears. This can be very confusing if you have a big class and the actual error is many lines underneath the first marked line (talking from experience...)

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

Can this class be reconfigured to accept named parameters in Flutter?

Background code
I have a class called Result that I'm using to pass on some error codes and error messages to an error screen.
class Result<T>{
Result._();
factory Result.loading(T msg) = LoadingState<T>;
factory Result.success(T value) = SuccessState<T>;
factory Result.error(T title, T msg, T errorcode) = ErrorState<T>;
}
class ErrorState<T> extends Result<T> {
final T title;
final T msg;
final T errorcode;
ErrorState(this.title, this.msg, this.errorcode) : super._();
//final T msg;
}
This class is called as follows:
return Result.error("Error","Status code not 200", 1);
My problem
Functionally it all works great.
The problem is I see myself in the future having to refer back to my class Result code to remember what each field represents which may become even more problematic if I want to add in more fields down the line
I'd rather convert this so that the fields are named
My question
Can this class be converted so that it is called like this (with a name describing the parameter):
return Result.error(title:"Error", msg:"Status code not 200", errorcode:1);
If you want to change Result.error to accept named parameters without breaking existing call sites, you can't do that. Parameters can be either positional or named, but not both.
If you're okay with breaking existing call sites, then you can just make them required named parameters. Since you're using redirecting constructors, you either will need to:
Change the signature of the redirectee constructor (in your case, ErrorState) to exactly match that of Result.error:
factory Result.error(
{required T title, required T msg, required T errorcode}) = ErrorState<T>;
...
ErrorState({required this.title, required this.msg, required this.errorcode})
: super._();
Or change Result.error to be a non-redirecting constructor:
factory Result.error(
{required T title, required T msg, required T errorcode}) {
return ErrorState<T>(title, msg, errorcode);
}
(If you do want to avoid breaking existing callers, you could add a separate named constructor (or static method) that uses named parameters, and you could optionally deprecate the old constructor.)
As an aside, it does not make sense that Result and ErrorState are generic classes. Do you really expect title and msg to not be Strings? Does it really make sense for the type of title, msg, and errorcode to be the same? (With the example you've shown, you'll end up with Result<Object>, which defeats the point of using a generic class.)

Dart: How to use the dot notation, uncaught TypeError Problem

I have the following code in dart, which decodes a string into a JSON object.
import 'dart:convert';
void main(){
var stringValue = "{\"last_supported\": \"2.00\", \"current\": \"2.00\"}";
var newValue = json.decode(stringValue);
print(newValue["last_supported"]);
}
The above code works fine, but when I change print statement to:
print(newValue.last_supported);
It gives me the following exception:
Uncaught TypeError: C.C_JsonCodec.decode$1(...).get$last_supported is not a function
Is it possible to use dot annotation to access properties, and how?
I'm guessing you come from a java-script background.
in dart object keys cannot be accessed through the . dot notation.
rather they are accessed like arrays with ['key_name'].
so that's why this line doesn't work
print(newValue.last_supported)
and this one does
print(newValue["last_supported"]);
dot notation in dart only works on class instances, not Map (similar to JavaScript objects).
look at the following :
class User {
final String name;
final int age;
// other props;
User(this.name, this.age);
}
Now when you create a new user object you can access its public attributes with the dot notation
final user = new User("john doe", 20); // the new keyword is optional since Dart v2
// this works
print(user.name);
print(user.age);
// this doesn't work because user is an instance of User class and not a Map.
print(user['name]);
print(user['age]);
For more about the new keyword you can read the v2 release notes here.