How to set New Variable value from Old Variable value, if New Variable value changed the Old Variable not follow the changes - flutter

As stated in the title
Look at this code Example:
void main() {
final Student student = Student('Lincoln', 29);
print('Student before $student');
final Student newStudent = student;
newStudent?.name = 'Abraham';
print('new Student $newStudent'); /// 'Abraham', 29
print('Student after $student'); /// 'Abraham', 29 - but I need this output still 'Lincoln', 29
}
class Student {
Student(this.name, this.age);
String? name;
int? age;
#override
String toString() => '$name, $age';
}
From the code above if we set newStudent and make changes, the student variable also follows the changes, but I don't want the student variable changed. How to solve this?

You should make a new Student instance for the new one. If you want it to have the same name as age as the old you could do this for example:
final Student newStudent = Student(student.name, student.age);

and also study this example..this will clear the concept...
final List<int> numbers=[1,2,3];
print(numbers);
final List<int> numbers2=numbers;
numbers2.add(100);//this will add also to numbers
print(numbers);
//so use following for keep original array as it was
final List<int> numbers3=[...numbers];//user this spread operator
numbers3.add(200);
print(numbers);
so what u have to focus is
we passing reference not value by this statement
Student newstudent=&student (like in C language, here & sign is not used in dart

Related

Flutter dart replace replace Json object with variables

In this case I have class. Where I took a variable. Also I have a Json map. So I want to change Json map object replace with variables. Here is my code example....
So how can I achieve that
I want replace Json object with dart variable
class Data {
late String slug;
Map<String, String> singleProductVariable = {"slug": "$slug"};
}
Firstly, there is no JSON in your code sample.
I assume that you would like to set the value of the corresponding key in your Map when setting the variable.
If so, you might want to use a setter in a next way:
class Data {
String _slug;
late Map<String, String> v = {"slug": _slug};
Data(String slug) : _slug = slug;
set slug(String str) => v['slug'] = str;
}
void main() {
final d = Data("slug");
print(d.v);
d.slug = "newSlug";
print(d.v);
}
The output of the code above will be:
{slug: val}
{slug: newVal}

Flutter how to convert List<Object> for using ObjectBox

I have a model like this code
class Folder {
int id;
String title;
Color? color;
List<Note> notes;
final user = ToOne<User>();
String? get dbNotes => json.encode(notes);
set dbNotes(String? value) {
notes = json.decode(value!);
}
// ...
}
and I have this error
Cannot use the default constructor of 'Folder': don't know how to initialize param notes - no such property.
How can I convert my List<Object> to store in ObjectBox?
You can define a Note entity and create a To-One relation to the Folder class just like you did with Folder -> User.
Please do this:
you define a default constructor and initialize the variable notes
Folder(){ notes = <Notes>[]; }

final variables can't be reassigned, but the object can be mutated in flutter

https://stackoverflow.com/a/55990137/462608
comment:
"Can't be changed after initialized" is ambiguous. final variables can't be reassigned, but the object can be mutated. –
jamesdlin
Feb 19 at 17:43
and https://stackoverflow.com/a/50431087/462608
a final variable's value cannot be changed. final modifies variables
What do both these statements mean? Please give examples.
Consider the following class:
class SampleObject {
int id;
String value;
SampleObject(this.id, this.value);
}
final variable can't be reassigned:
void main() {
final obj1 = SampleObject(1, "value1");
// the following line will gives error:
// The final variable 'obj1' can only be set once
obj1 = SampleObject(1, "value2");
}
But the object property can be changed (is mutable):
void main() {
final obj1 = SampleObject(1, "value1");
obj1.value = "value2";
print(obj1.value);
}
But it becomes an immutable object if you set all the property in the class to final:
class SampleObject {
final int id;
final String value;
SampleObject(this.id, this.value);
}
where it gives error when you're trying to reassign a value to its property:
void main() {
final obj1 = SampleObject(1, "value1");
// the following line will gives error:
// 'value' can't be used as a setter because it's final.
// Try finding a different setter, or making 'value' non-final
obj1.value = "value2";
}
Imagine the example below:
void main() {
final student = Student('Salih', 29);
print('Student before $student');
student.age = 30;
print('Student after $student');
}
class Student {
Student(this.name, this.age);
final String name;
int age;
#override
String toString() => 'Age is $age and name is $name';
}
One of the fields of the Student object is mutable. This way we can reassign it. What others mean above is that, the object reference of the final variables will be assigned first but internals of the object can be changed.
In our example, final would be preventing to re-assign something to student object but it will not prevent us to re-assign a value within the object.
You can run the code on dartpad.dev above and see the result as follows:
Student before Age is 29 and name is Salih
Student after Age is 30 and name is Salih

Correct declaring of a class in Dart

I am new to dart and I have some basicaly question to the language itself.
During the last days I started with classes in dart.
Now I have a short question about how to declare a class correct.
void main() {
Book harryPotter =
Book(title: "Goblet of Fire", author: "J. K. Rolling", pageCount: 300);
print(harryPotter._title); // 1 -> print "A" to the console
print(harryPotter._author); // 2 -> LateInitializationError: Field '_author#18448617' has not been initialized.
}
class Book {
String _title = "A";
late String _author;
late int _pageCount;
Book(
{required String title,
required String author,
required int pageCount}); // 3
}
Why can I access to the variable even if it's set to private?
Why does the late keyword throw an error, the variable is set during the constructor call?
Do I need to write in the constructor "Book({required String this.title});", or "Book({required String title});" like in the example? If it doesn't matter, why?
Thanks for helping!
Benjamin
Your constructor is not initializing the variables!
It should be:
Book({required String title, required String author, required int pageCount})
: _title = title,
_author = author,
_pageCount = pageCount;
Without that, the _author field is not set at all, and reading an unset late field is an error.
You can't use this.something because the fields have private names (_author) and named parameters cannot have private names. Otherwise that would have been the correct approach. Instead you need to have public-named parameters and then use the value to initialize the field in an initializer list.
With that change, the fields also don't need to be late and can instead be final:
class Book {
final String _title;
final String _author;
final int _pageCount;
Book({required String title, required String author, required int pageCount})
: _title = title,
_author = author,
_pageCount = pageCount;
}
You can access the private variables from inside the same library because Dart privacy is library based.

Creating and using Singleton in flutter dart

I am very new to flutter and dart and trying to use singleton instance for global state(?).
which is company info that gets from backend server.
When flutter app starts, send request to the server and get a response and build a singleton instance based on the response.
So I created class
class Company {
static final Company _instance = new Company._internal();
factory Company() {
return _instance;
}
#protected
String name;
#protected
String intro;
String get companyName => name;
String get companyIntro => intro;
void setCompany(String name, String intro) {
name = name;
intro = intro;
}
Company._internal();
}
in main.dart
// companyResult is the response from server
final String companyName = companyResult["name"];
final String companyIntro = companyResult["intro"];
// create singleton instance
var company = Company();
// set company info
company.setCompany(companyName, companyIntro);
// cheking
print(company.companyName)
prints null
What am I doing wrong?
Singletons are better avoided, I would recommend that you use Provider instead and inject a simple object reference on your widget tree, so you can grab that reference whenever you want.
The reason your example prints null is because you are wrongly referencing your variables on setCompany(), the variables name and intro are all the same variable, you are changing the variables internal to the function, not the class variables, in order to fix it change it to:
void setCompany(String name, String intro) {
this.name = name;
this.intro = intro;
}
Also, I would suggest you name your variables _name and _intro, as there's no sense in having a get for a variable that's no private.