Dart model throws error when mixing many data types - flutter

I made this simple model to work with an API
class BooksModel {
List<_Book> _books = [];
BooksModel.fromJson(Map<dynamic, dynamic> parsedJson) {
List<_Book> temp = [];
for (int i = 0; i < parsedJson['books'].length; i++) {
_Book book = _Book(parsedJson['books'][i]);
temp.add(book);
}
_books = temp;
}
List<_Book> get books => _books;
}
class _Book {
int _id;
String _name;
_Book(book) {
_id = book['id'];
_name = book['name'];
}
int get id => _id;
int get name => _name;
}
The problem is i have to turn all '_Book' class properties to 'String', if i made only one 'int' as given in the above example, it throws this error.
type 'String' is not a subtype of type 'int'
I don't even use that 'id' which is 'int' in my app, so it's not about the usage of it, the problem is in this model

Can you just show the example of your json, so that i can tell you that what your model should be or where it is going wrong.
So maybe your issue is not that big , id required is integer and you are passing the String.

Is book['id'] a string?
Try it:
// _id = book['id'];
_id = int.parse(book['id']);

Related

class object and property variation in dart

so i recently started learning dart and I've found something kinda interesting.
why do we use constructors and getters/setters when we can achieve same results without them? (atleast when used for basic things).
class v1{
var name;
int age;
v1(this.name, this.age);
info(){
print("my name is $name and i am $age");
}
}
class v2{
var name = "bash";
int age = 100;
info(){
print("my name is $name and i am $age");
}
}
class v3{
var namee;
int agee;
String get name => namee;
int get age => agee;
set name(String name) => this.namee = name;
set age(int age) => this.agee = age;
info(){
print("my name is $name and i am $age");
}
}
void main(){
var x = v1("bash", 100);
x.info(); //my name is bash am i am 100
var z = v2();
var Z = v2();
Z.name = "vert";
Z.age = 20;
z.info(); //my name is bash and i am 100
Z.info(); //my name is vert and i am 100
var y = v3();
y.name = "rizz";
y.age = 40;
y.info(); //my name is rizz and i am 40
}
Here's a more correct version of your class:
class User {
final bool _isMale;
String _name;
int _age;
User(this._isMale, this._name, this._age);
bool isMale => _isMale;
String get name => _name;
int get age => _age;
set name(String name) {
// Sometimes you may want to update other properties here.
// For example:
// _isUpdated = true;
_name = name;
}
set age(int age) {
_age = age;
}
void info() {
print("my name is $name and i am $age");
}
}
Constructors are useful when you want to assign initial values to the class fields. They are essential if you need to assign final fields, as they are assignable only on class initialization (see _isMale field).
Setters are useful when you want to update other fields along with the field that's being modified.
Getters protect the internal state from being modified outside. In this example, nobody can change _isMale field.
You don't need to use getters and setters unless you have to.
You use getters and setters if you need to store the data in a private field, or if you want to modify it when saving or returning the value.
class Abc {
String _field;
String _otherField;
String anotherField; // No getters and setters required for this.
String get field => _field;
set field(String field) => _field = field;
String get otherField => "The value of otherField is: " + _otherField;
set otherField(String otherField) => _otherField = "[String] " + otherField;
}
As for constructors, you use them to initialize the object with custom values. When you need to work with immutable objects (which use final variables), you'll have to use constructors to set their initial value. You can also modify the incoming value according to your need before storing it,
class Def {
final field; // Dart generates getters for this field, but it's value can't be modified once the object is instantiated.
final _otherField; // No getters for this.
Def(String field, String otherField) {
this.field = "[String] $field"
this._otherField = "[String] $otherField"
}
String describeMe() {
return "[Def]: field: $field, _otherField: $_otherField"
}
}

How to pass String to constructor from a map

I'm trying to create an Athlet Object from a DocumentSnapshot. In this DocumentSnapshot I have stored a map, that holds the values(i.E. "upperbody": 0), to this athletes favourite Categorys. But for the AthleteObject I only need the key, of the category with the highest Value.
This should work, but I get the following error. And I dont' know how to rewrite this for it to not complain.
The instance member 'getFavCategory' can't be accessed in an initializer. (Documentation) Try replacing the reference to the instance member with a different expression
Athlete.fromJSON(DocumentSnapshot parsedJSON):
_name = parsedJSON["name"],
_rank = parsedJSON['rank'],
_xp = parsedJSON['xp'],
_foot = parsedJSON['foot'],
_position = parsedJSON['position'],
_statsDate = parsedJSON['statsDate'],
_challengeCount = parsedJSON['challengeCount'],
_workoutCount = parsedJSON['workoutCount'],
_favCategory = getFavCategory(parsedJSON['favCategory']),
_shotsTaken = parsedJSON['shotsTaken'],
_shotsMade = parsedJSON['shotsMade'],
_passesTaken = parsedJSON['passesTaken'],
_passesMade = parsedJSON['passesMade'];
String getFavCategory(Map<String, dynamic> map){
String favCat;
int maxVal;
map.forEach((key, value) {
if(maxVal == null || value > maxVal){
maxVal = value;
favCat = key;
}
});
return favCat;
}
Your definition of getFavCategory states that it has to be called on an initialized instance of your Athlete class (which is not a case for your constructor).
The fastest you can do is simply turn your getFavCategory function in to static (since you are not using any class variables inside):
static String getFavCategory(Map<String, dynamic> map){
String favCat;
int maxVal;
map.forEach((key, value) {
if(maxVal == null || value > maxVal){
maxVal = value;
favCat = key;
}
});
return favCat;
}

How to declare a List type property for a class correctly in Dart?

I am new to Flutter, and trying to declare a Folder class with one of the properties being a list of children Folders. I am not able to arrive to a correct declaration, the language gives me various errors. Someone can help me out with that?
class Folder {
final int id;
final String title;
final List<Folder> children;
Folder ({
this.id = 0,
this.title = '',
this.children
});
factory Folder.fromJson(Map<String, dynamic> parsedJson) {
Iterable i = parsedJson['children'];
return new Folder(
id: parsedJson['id'] ?? '',
title: parsedJson['title'] ?? '',
children: List<Folder>.from(i.map((model) => Folder.fromJson(model)))
);
}
}
This gives me for the children property the following error: The parameter 'children' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Sometimes the Folder doesn't have subfolders, so I wouldn't like to create a #required parameter, just an optional.
I guess you're using the latest version of Dart with the null-safety enabled ?
If that's the case, declaring your children var this way
List<Folder>? children;
should do the trick.
Another solution would be to update your constructor
Folder ({
this.id = 0,
this.title = '',
this.children = []
});
I cannot set a default value this.<List>propertyName = [] in the parameter because the value needs to be const. So I went with not declaring a default value and created a setter/getter.
Here's my example:
[batches.dart]
class Batches{
String? _batchName;
List<Trainees>? _trainees;
// Constructor
Batches({batchName, trainees}) {
this.batchName = batchName;
this.trainees = trainees;
}
// Getter Setter
String? get batchName => this._batchName;
set batchName(String? batchName) => this._batchName = batchName;
List<Trainees>? get trainees => this._trainees;
set trainees(List<Trainees>? traineeList) {
this._trainees = traineeList;
print("Added list of trainees to $batchName!");
}
}
Called the setter function in void main() and then set the existing List batch1_trainees to the setter of the function
[main.dart]
List<Trainees> batch1_trainees = [
Trainee("Trainee Wan"),
Trainee("Trainee Tiu"),
];
Batches batch1 = Batches(batchName: "first_batch");
batch1.trainees = batch1_trainees;
`
Trainees is a class that takes Full_Name as a positional parameter.
If the setter is called, the console should print Added list of trainees to first_batch!
PS.
The getter and setter were necessary in my example because the properties were set to private.

Flutter: Transferring items from one list into a different list

i have one List (growable) with an item (actually item 0:
items is of class Team
items[_id = 1, _team = "Team01", _note = "blabla"]
and I want to transfer it into another list with a different structure:
participants is of class User
participants[id = 1, name = "participant1"]
skipping the note and translating _id into id and so on.So at last the result would give me
participants[id = 1, name = "team01"]
(sorry for the writing, I describe it out of the debugger)
i tried something like this, but doesnt work with value:
List<TestTeam> participants;
for (var value in items) {
participants.add(new TestTeam(value.id, value.team));
}
my class Team is defined like this:
class Team {
int _id;
String _team;
String _note;
Team(this._team, this._note);
Team.map(dynamic obj) {
this._id = obj['id'];
this._team = obj['team'];
this._note = obj['note'];
}
int get id => _id;
String get team => _team;
String get note => _note;
Map<String, dynamic> toMap() {
var map = new Map<String, dynamic>();
if (_id != null) {
map['id'] = _id;
}
map['team'] = _team;
map['note'] = _note;
return map;
}
Team.fromMap(Map<String, dynamic> map) {
this._id = map['id'];
this._team = map['team'];
this._note = map['note'];
}
}
You should implement below way
void main() {
List<Team> teams=[];
List<User> participants=[];
for (var i = 0; i < 4; i++) {
teams.add(Team(i,'Team_$i','Note_$i'));
}
for (var value in teams){
participants.add(User(value.id,value.team));
}
for (var value in teams){
print(value.toString());
}
for (var value in participants){
print(value.toString());
}
}
class Team{
int id;
String team;
String note;
Team(this.id,this.team,this.note);
toString()=> 'Team Map :{id:$id,team:$team,note:$note}';
}
class User{
int id;
String team;
User(this.id,this.team);
toString()=> 'User Map :{id:$id,team:$team}';
}
Output
Team Map :{id:0,team:Team_0,note:Note_0}
Team Map :{id:1,team:Team_1,note:Note_1}
Team Map :{id:2,team:Team_2,note:Note_2}
Team Map :{id:3,team:Team_3,note:Note_3}
User Map :{id:0,team:Team_0}
User Map :{id:1,team:Team_1}
User Map :{id:2,team:Team_2}
User Map :{id:3,team:Team_3}

how to get a string for a class property name in dart?

i want to do use the model's properties such as:
Animal.id as a param to a function or use some extension method to be able to "id". similarly, i'd like to use Animal.title in that way to get "title" as a returned value. how could i do this with my class to get a string for any given property name?
int _id;
String _title;
Animal(this._id, this._title);
int get id => _id;
String get title => _title;
}
the usage case is being able to query without having autocomplete on my model's property names in a string for sql querying:
List<Map> results = await db.query("Animal",
columns: Set. ["id", "title"],
where: 'id = ?',
whereArgs: [id]);
Using the dart:mirrors package you can dynamically access your class properties and invoke methods using their string names.
https://api.dart.dev/stable/2.4.0/dart-mirrors/dart-mirrors-library.html
import 'dart:mirrors';
class Animal {
int _id;
String _title;
Animal(this._id, this._title);
int get id => _id;
String get title => _title;
}
main() {
var r = reflect(Animal(1, 'Dog'));
print(r.getField(Symbol('id')).reflectee);
print(r.getField(Symbol('title')).reflectee);
}
import 'dart:mirrors';
class MyClass {
int i, j;
void my_method() { }
int sum() => i + j;
MyClass(this.i, this.j);
static noise() => 42;
static var s;
}
main() {
MyClass myClass = new MyClass(3, 4);
InstanceMirror myClassInstanceMirror = reflect(myClass);
ClassMirror MyClassMirror = myClassInstanceMirror.type;
InstanceMirror res = myClassInstanceMirror.invoke(#sum, []);
print('sum = ${res.reflectee}');
var f = MyClassMirror.invoke(#noise, []);
print('noise = $f');
print('\nMethods:');
Iterable<DeclarationMirror> decls =
MyClassMirror.declarations.values.where(
(dm) => dm is MethodMirror && dm.isRegularMethod);
decls.forEach((MethodMirror mm) {
print(MirrorSystem.getName(mm.simpleName));
});
print('\nAll declarations:');
for (var k in MyClassMirror.declarations.keys) {
print(MirrorSystem.getName(k));
}
MyClassMirror.setField(#s, 91);
print(MyClass.s);
}
the output:
sum = 7
noise = InstanceMirror on 42
Methods:
my_method
sum
noise
All declarations:
i
j
s
my_method
sum
noise
MyClass
91