Getting and setting class attributes in Dart / Flutter - flutter

I would like to list a class's attributes and set them too. For example in a ListView when I tap on the value of an attribute I would like to increment it by 1.
Sample class:
class Person {
int age;
int height;
int weight;
Person({
this.age,
this.height,
this.weight,
});
}
Is it possible to list and set these values without writing getter and setter functions for each of the attributes?

In you code sample, you defined age, height, and weight as public. So, you don't need to define getters and setters. You can directly increment and decrement their values.
void main() {
final a = Person(age: 25, height: 210, weight: 90);
a.age++;
a.height++;
a.weight++;
print(a);
// This person is 26 years old, 211cm tall and weights 91kg
}
class Person {
int age;
int height;
int weight;
Person({
this.age = 0,
this.height = 0,
this.weight = 0,
});
toString() => 'This person is $age years old, ${height}cm tall and weights ${weight}kg';
}
However, you might encounter problems by mutating objects if later, you rely on state equality to rebuild a Widget. It's better to handle your State objects as being immutable.
Then, regarding listing the values, if you refer to [dart:mirrors][1], it's not supported by Flutter.

Related

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

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

How can I use variables collected in a class when an object is instantiated within functions held in the class?

in Dart (version 2.15.1). I have made a class to define a car.
I want to use some of the variables created when the 'car' object is instantiated in a class function, rather than have the user resupply the data a second time when calling the function. I cannot find a way to access the data I need in the function.
Here is my programme I have marked the lines that are not working:
// Programme to create a class to define a car.
//
class Car {
Car({
required this.make,
required this.colour,
required this.engineSize,
required this.cost,
required this.ageInYears,
required this.mileage,
required this.mpg,
});
final String make;
final String colour;
final int engineSize;
final double cost;
final int ageInYears;
final int mileage;
final double mpg;
}
double milesPerYear() {
double milesPerYear = ${this.mileage} / ${this.ageInYears};
return milesPerYear;
// this line does not work. Is it possible to use the 'mileage' and 'ageInYears' data
// from when the car object was instantiated/
}
void main() {
print("dart /car/main.dart");
final aCar = Car(
make: "Vaxhall",
colour: "Silver",
engineSize: 1400,
cost: 7000,
ageInYears: 19,
mileage: 60000,
mpg: 20);
// costPerYear(double cost, int age)
print(aCar.make);
print(costOfPurchase(7000, 19));
print(costPerMile(7000, 60000));
print(milesPerYear());
// a line to invoke the function 'milesPerYear'
print(milesPerYear());
// this line does not work. How can I invoke the function and have it use the data
// created when the object was instantiated?
}
Your milesPerYear() method is outside the class. Your Car class should instead be the following if you want to be able to call the method on car objects and have access to this (which points to the Car object the method is called on):
class Car {
Car({
required this.make,
required this.colour,
required this.engineSize,
required this.cost,
required this.ageInYears,
required this.mileage,
required this.mpg,
});
final String make;
final String colour;
final int engineSize;
final double cost;
final int ageInYears;
final int mileage;
final double mpg;
double milesPerYear() {
return mileage / ageInYears;
}
// Or the following if you want it even shorter:
// double milesPerYear() => mileage / ageInYears;
// Or really, it should just be a getter and not a method
// double get milesPerYear => mileage / ageInYears;
}
By having the method inside the class, you can then call the method on object instances of Car like: aCar.milesPerYear().

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.

Flutter Dart: Dynamic Relationship inside Model Class Field

I've used Laravel, where we can define relationships inside the model itself. So is that possible in Dart/Flutter?
I've built this Cart Model where Grand-total should be dynamic.
So whenever I create an instance of this Cart Model, grand total will be auto-calculated once we enter the total & discount. until then the default value 0.
code from the image above:
class Cart {
Cart({
this.total = 0,
this.discount = 0,
this.grandTotal, // I want this field dynamic: (grandtotal = total - discount)
});
int total;
int discount;
int? grandTotal;
}
define a getter method to calculate grandTotal.
Sample code:
int? get grandTotal {
// TODO: check for null cases here
return total - discount;
}

How can I get a default and a parameterized constructor inside the same class in Dart/Flutter?

I know that in C++ we could have both of the constructors without a problem. In Dart when I'm trying to write two constructors, it says "The default constructor is already defined"
class Human {
double height;
int age;
Human()
{
height = 0;
age = 0;
}
Human (double startingheight){ //The default constructor is already defined
height = startingheight;
}
}
Dart doesn't support methods/functions overload and will not have it in any visible future.
What you can do here is to make the parameters optional with default value:
Either as positional arguments:
class Human {
double height = 175;
Human([this.height]);
}
var human1 = Human();
var human = Human(180);
or named:
class Human {
final double height;
Human({this.height = 175});
}
var human1 = Human();
var human = Human(height: 180);
class Human{
Human(double height, int color) {
this._height = height;
this._color = color;
}
Human.fromHuman(Human another) {
this._height = another.getHeight();
this._color = another.getColor();
}
}
new Human.fromHuman(man);
This constructor can be simplified
Human(double height, int age) {
this._height = height;
this._age = age;
}
to
Human(this._height, this._age);
Named constructors can also be private by starting the name with _
Constructors with final fields initializer list are necessary:
class Human{
final double height;
final int age;
Human(this.height, this.age);
Human.fromHuman(Human another) :
height= another.height,
age= another.age;
}
Try these
//Using Default parameter values
Human({this.height = 0.0, this.age = 0});
// Named constructor
Human.startingHeight(double startingHeight){
height = startingHeight;
age = 0;//or don't use this if you want it null
}
For more info check out this page: https://dart.dev/guides/language/language-tour