How to add positional parameter with default value in GetX Flutter - flutter

I'm trying to add a positional parameter with default value with GetX in Flutter but I got an error.
import 'package:get/get.dart';
class MainParentModel {
int id;
String name;
RxBool isSelected;
MainParentModel(this.id, this.name, {this.isSelected = false.obs});
}
Error: The default value of an optional parameter must be constant.dartnon_constant_default_value
How can I add this default value?
Thank you

.obs is a getter that returns an Rx<T> of whatever type you add it to. But it's not a constant value so that won't work. You'll notice that if you just use a regular bool and remove .obs the error goes away.
If it has to be type RxBool, then I'm pretty sure your only option is making it required and passing in false.obs whenever you create a new MainParentModel.
MainParentModel(this.id, this.name, {required this.isSelected});
Then a new instance would look like this.
final model = MainParentModel(1, 'Bob', isSelected: false.obs);

Another approach is creating reactive objects where you'll need, I never use classes with reactive variables, for example:
class MainParentModel {
int id;
String name;
bool isSelected;
MainParentModel(this.id, this.name, {this.isSelected = false});
}
In the controller:
Rx<MainParentModel> mainParentModel = MainParentModel().obs;
if you need to rebuild the page when changing isSelected variable:
mainParentModel.update((model){
model.isSelected = true;
});
or
mainParentModel.refresh();
This will trigger rebuild all Obx that you use mainParentModel.value.?

Related

Optional prop/property in Flutter

I'm in Flutter, and I know something about React Native. In React Native I create optional props like this:
foo?: boolean;
How do I do the same thing in Flutter?
I looked here and didn't find it.
The same way to you reproduce optional props in Flutter is something like this:
class MyClass {
final String myProperty;
final List<int> anotherProp;
final String? nullSafetyProp; //can be optional
late final String lateProp; // shold be initialized in Future. Before read the value
MyClass({
required this.myProperty,
required this.anotherProp,
this.nullSafetyProp, // optional property
required this.lateProp
});
}
about keyword final:
https://dart.dev/guides/language/language-tour#final-and-
about
nullsafety: https://dart.dev/null-safety
late variables: https://dart.dev/null-safety/understanding-null-safety#late-variables
late final variables: https://dart.dev/null-safety/understanding-null-safety#late-final-variables

Non-nullable instance field 'id' must be initialized

could anyone help me with how to manage this problem? I am new to Flutter, I am trying to code exactly likes the course's video, but I got this problem:
2. How could I change the 'status' item optional?
class Task {
int id;
String title;
DateTime date;
String priority;
int status; // 0 - Incomplete, 1 - Complete
Task({this.title, this.date, this.priority, this.status});
Task.withId({this.id, this.title, this.date, this.priority, this.status});
It's a null safety problem
solutions
make int nullable
int? id; // preferred
or
when calling constructor use required keyword
Task({required this.id})
or
initialize default value to id
int id = 0;
When you have named parameters constructors
Task({...});
and you do not specify required keyword in front of a variable the variable is optional. But, because your code is written in null-safety way, you must give it value or the other way it would be assigned null (which is illegal in this case).
Nullable var
If you want your value to be null-assignable you can write:
int? status;
Then you have to remember to check if the variable is null or not before you use it.
Default value
Another way is to use default value in the constructor:
Task({..., this.status = 0});
Required value
Or you can force developer to give it a value:
Task({..., required this.status});
Dartz
Another way is to use Option variable from Dartz package:
import 'package:dartz/dartz.dart';
...
Option<int> status;
Task({..., required this.status});
then you can pass none() or some(1) as a status.
Task(..., status: none());
Task(..., status: some(0));

Is required register a list of Objects in Hive?

This is my Hive model and I already generate the adapter:
#HiveType(typeId: 7)
class GoalModel {
#HiveField(0)
bool progessNotificaitons;
#HiveField(1)
List<DayModel> daysToWork;
#HiveField(2)
int amountGoal;
#HiveField(3)
DateTime initialDate;
GoalModel({
this.amountGoal,
this.daysToWork,
this.initialDate,
this.progessNotificaitons,
});
}
class DayModel {
String label;
int index;
bool gonnaWork;
DayModel({
this.gonnaWork,
this.index,
this.label,
});
}
The issue is that does not allow me save the daysToWork which is a list of the class DayModel which does not have an adapter. the question is: is required generate an adapter or any special config to save a list of a type of object?
Thanks in advance.
The response is YES, is required generate an register a new adapter even if you just are going to issue the object into a list of another object.

Riverpod create provider

I want to create provider that will return String with Riverpod. I'm using Provider as below. I'm getting an error The instance member 'name' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression. May someone tell me how should I create provider?
class LearnUser {
final String uid;
final String name;
final usernameProvider = Provider((ref) {
return name;
});
LearnUser({required this.uid});
}
I would separate the provider from the LearnUser class. It gives cleaner separation of concerns in my opinion. And what i understood from the Riverpod docs they are ment as global vars. Like the above poster mentioned your code won't work cause you are trying to access an instance variable.
Maybe something like this with a user service. I would also advice you look into StateNotifier with StateNotifierProvider you could use for example to create a user service.
// Creating the provider as global variable
final userNameProvider = Provider<String>((ref) =>
ref.watch(userService.state)?.user.name ?? '';
);
'name' is instance member. You need an instance to access a member variable.
You can try this
class LearnUser {
final String uid;
String name;
Provider usernameProvider;
LearnUser({#required this.uid}){
this.usernameProvider = Provider((ref) {
return this.name;
});
}
}

Flutter - How to use a class model

I'm learning flutter coming from a react background. I want to use my model in another class.
This is my model
class User {
final String id;
final String userName;
User({
this.id,
this.userName,
});
}
On my Widget i want to use the properties of that model, so i can get some type safe.
class _SignUpScreenState extends State<SignUpScreen> {
#override
Widget build(BuildContext context) {
final User _user; // I get an error on this line.
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
I get teh following error.
The value of the local variable '_user' isn't used.
Try removing the variable, or using it.dartunused_local_variable
The final variable '_user' must be initialized.
Try initializing the variable.
I'm a little bit confused how do you properly infer a model on class widget?
Think about the model as a template - the way you are initializing the model - means there is nothing in it, and using the final variable means it will never change.
This causes an error, because the object is effectively null, and always will be.
If you initialize a variable with final you need give it data:
final User _user = User(id: 1, userName: test);
print(_user);
//Prints: Instance of User
Otherwise, don't use the final variable, and you can assign data to _user later"
User _user;
_user = User(id: 1, userName: test);
print(_user);
//Prints: Instance of User
I will explain what your error means one by one.
Flutter will have a warning that you are creating a value that you aren't using.
The value of the local variable '_user' isn't used.
This is what they suggested:
Try removing the variable, or using it.dartunused_local_variable
These two error code is saying that your variable has to be instantiated:
The final variable '_user' must be initialized.
Try initializing the variable.
The solution to your problem is to instansiate User:
final User _user=User(id:"myId",userName:"myUserName");
Note that the final keyword is means that you are declaring a variable that will never have its value change.