Flutter Dart The getter '' was called on null - flutter

I'm sending response.body and country name with slash as like germany/ as parameter and converting it to Germany in parser and returning. But if i use parameter, i'm getting error of the getter 'vacTotal' was called on null. If i write "Germany"to countryDataVac["Germany"] the code works correctly. Is it the problem on {"Global": new CountryDataVac()}? The default value is "Global".
main.dart:
Map<String, CountryDataVac> countryDataVac = {"Global": new CountryDataVac()};
static Map<String, CountryDataVac> getCountryDataVac(String body, var countryname) {
Map<String, CountryDataVac> countryDataVac = {};
responseVac1Day = await http.get("https://disease.sh/v3/covid-19/vaccine/coverage?fullData=true&lastdays=1"); //vaccine number info
countryDataVac = Parser.getCountryDataVac(responseVac1Day.body, "germany/"); //vaccine number info
Parser.dart:
var usera = CountryDataVac.fromJson(jsonDecode(result));
countryDataVac[capitalize(countryname).replaceAll("/", "")] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //gives 'germany/' as 'Germany' but getting error if i get the countryname by parameter
countryDataVac["Germany"] = parseRowVac(usera.vacTotal,usera.vacDaily,usera.vactotalPerHundred,usera.vacdailyPerMillion); //works
}
CountryDataVac.dart (created by json to dart)
import 'dart:convert';
List<CountryDataVac> countryDataVacFromJson(String str) => List<CountryDataVac>.from(json.decode(str).map((x) => CountryDataVac.fromJson(x)));
String countryDataVacToJson(List<CountryDataVac> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CountryDataVac {
CountryDataVac({
this.vacTotal = 0,
this.vacDaily = 0,
this.vactotalPerHundred = 0,
this.vacdailyPerMillion = 0,
this.date = "",
});
int vacTotal = 0;
int vacDaily = 0;
int vactotalPerHundred = 0;
int vacdailyPerMillion = 0;
String date = "";
factory CountryDataVac.fromJson(Map<String, dynamic> json) => CountryDataVac(
vacTotal: json["total"],
vacDaily: json["daily"],
vactotalPerHundred: json["totalPerHundred"],
vacdailyPerMillion: json["dailyPerMillion"],
date: json["date"],
);
Map<String, dynamic> toJson() => {
"total": vacTotal,
"daily": vacDaily,
"totalPerHundred": vactotalPerHundred,
"dailyPerMillion": vacdailyPerMillion,
"date": date,
};
}

use
countryname.replaceFirst(countryname[0], countryname[0].toUpperCase()).replaceAll("/", "");
instead of
capitalize(countryname).replaceAll("/", "")
i think there is something wrong with your capitalize method

Related

how to get the server time in the Firestore in the map from the class

Adding to Firestore from a class instance
FirebaseFirestore.instance.collection('collection').add({'history':History(FieldValue.serverTimestamp(), 'action', 'who').makeMap()}).then((value) {
// ...
});
what type should the time field have?
class History{
FieldValue time = FieldValue.serverTimestamp();
String action = '';
String who = '';
var history = <FieldValue, Map<String, String>>{};
History(FieldValue time, String action, String who){
this.time = time;
this.action = action;
this.who = who;
}
Map<FieldValue, Map<String, String>> makeMap(){
var tempMap = <String, String>{
'action' : action,
'who' : who,
};
history[time] = tempMap;
return history;
}
}
How to get a string in this form?
{"time" : 'October 25, 2022 at 10:44:39 PM UTC+1' ,
{ "action": "action", "who": "who" }};
Try to store the value of time in timeStamp type and when to get also save in timeStamp then easily you can convert into string

dart null safety class initialization

I built two classes.
first class is the video Class.
second class is Player Class.
And one of Player variables is list of video class
and after dart null safety it is not allowed to add null varaiables
I should add initialization value to the class ( I don't want to add required ).
First Class - Video
import 'dart:convert';
VideoModel videoModelFromJson(String str) =>
VideoModel.fromJson(json.decode(str));
String videoModelToJson(VideoModel data) => json.encode(data.toJson());
class VideoModel {
VideoModel({
this.playerVideoId = -1,
this.playerIdId = -1,
this.videoLink = "Please Upload",
});
int playerVideoId;
int playerIdId;
String videoLink;
factory VideoModel.fromJson(Map<String, dynamic> json) => VideoModel(
playerVideoId: json["playerVideoId"],
playerIdId: json["playerId_id"],
videoLink: json["videoLink"],
);
Map<String, dynamic> toJson() => {
"playerVideoId": playerVideoId,
"playerId_id": playerIdId,
"videoLink": videoLink,
};
}
Second Class which contain error in defining videos
// To parse this JSON data, do
//
// final playerBasic = playerBasicFromJson(jsonString);
import 'dart:convert';
import 'package:sportive/pages/player/Model/Video_Model.dart';
PlayerBasic playerBasicFromJson(String str) =>
PlayerBasic.fromJson(json.decode(str));
String playerBasicToJson(PlayerBasic data) => json.encode(data.toJson());
class PlayerBasic {
PlayerBasic({
this.playerId = -1,
this.userIdId = -1,
this.playerFirstName = "",
this.playerLastName = "",
this.nationality = "",
this.birthday = "",
this.height = -1,
this.weight = -1,
this.currentCountry = "",
this.currentCity = "",
this.game = "",
this.image = "",
this.gender = "Male",
this.videos, // Error here Parameter The parameter 'videos' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
//Try adding either an explicit non-'null' default value or the 'required' modifier
});
int playerId;
int userIdId;
String playerFirstName;
String playerLastName;
String nationality;
String birthday;
int height;
int weight;
String currentCountry;
String currentCity;
String game;
String image;
String gender;
List<VideoModel> videos;
factory PlayerBasic.fromJson(Map<String, dynamic> json) => PlayerBasic(
playerId: json["playerId"],
userIdId: json["userId_id"],
playerFirstName: json["playerFirstName"],
playerLastName: json["playerLastName"],
nationality: json["nationality"],
birthday: json["birthday"],
height: json["height"],
weight: json["weight"],
currentCountry: json["currentCountry"],
currentCity: json["currentCity"],
game: json["game"],
image: json["image"],
gender: json['gender'],
videos: json['videos'],
);
Map<String, dynamic> toJson() => {
"playerId": playerId,
"userId_id": userIdId,
"playerFirstName": playerFirstName,
"playerLastName": playerLastName,
"nationality": nationality,
"birthday": birthday,
"height": height,
"weight": weight,
"currentCountry": currentCountry,
"currentCity": currentCity,
"game": game,
"image": image,
"gender": gender,
"videos": videos,
};
}
Sorry Iam Flutter beginner question.
Just change the videos declaration to
List<VideoModel>? videos;
Let's suppose you have this class and you want to provide a default value for bar in the constructor:
class Foo {
List<int> bar;
}
If you want to be able to modify bar later:
class Foo {
// Use this
Foo({List<int>? bar}) : bar = bar ?? [];
List<int> bar;
}
void main() {
Foo foo;
foo = Foo();
print(foo.bar);
// Outputs []
foo.bar.add(4);
print(foo.bar);
// Outputs [4]
foo = Foo(bar: [1, 2, 3]);
print(foo.bar);
// Outputs [1, 2, 3]
foo.bar.add(4);
print(foo.bar);
// Outputs [1, 2, 3, 4]
}
If you want to keep bar immutable (i.e. you won't use methods such as add or remove):
class Foo {
// Use this
Foo({this.bar = const []});
List<int> bar;
}
void main() {
Foo foo;
foo = Foo();
print(foo.bar);
// Outputs []
// foo.bar.add(4);
// It'll throw Uncaught Error: Unsupported operation: add
foo = Foo(bar: [1, 2, 3]);
print(foo.bar);
// Outputs [1, 2, 3]
foo.bar.add(4);
print(foo.bar);
// Outputs [1, 2, 3, 4]
}

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 insert a List<Class> into a Map<String, dynamic> in dart?

My problem is that I have a list of the following class:
class ingreso_Egreso_Dummy{
int tipo;
String monto;
String moneda;
String descripcion;
}
then I want to insert the data into a Map which later will be converted into a json and which I am creating like this:
Map<String, dynamic> body;
body = {
"Cod_Prom": "01",
"CodCli": "003526",
"Status": _index_status.toString(),
"NOMBRE": controller_nombre.text,
"APELLIDOS": controller_apellidos.text,
"solicitud":[{
"Cod_Solicit": 1.toString(),
"Fecha": DateFormat("y-d-M").format(DateTime.now()),
"Status_Solicit": "E",}],
"prestamo":[{
"Monto_Solicit":controller_monto_solic.text,
"Plazo":controller_plazo.text,
"Cod_TipoPlazo":_index_tipoplazo.toString(),
"Nombre_Resp":controller_nombreresp.text,
"Telf_Resp":controller_telefonoresp.text,}],
"Ingresos": [{
//// here I want create a loop that returns a map for each value
//// of the list like this:
//// "Descripcion": Listaingresos[i].descripcion;
})
}]
};
Every help is very appreciated, thank you.
// camelCaseStyle is a standard for class names for Dart
class IngresoEgresoDummy {
int tipo;
String monto;
String moneda;
String descripcion;
Map<String, dynamic> toJson(){
return {
'tipo': tipo,
'monto': monto,
'monedo': moneda,
'descripcion': descripcion
};
}
}
and after that
List<IngresoEgresoDummy> listaingresos= List();
Map<String, dynamic> body = {
// all your params
"Ingresos": listaingresos.map((ingreso) => ingreso.toJson()).toList()
// all your params
};

Parse a JSON array with multiple object types

Let's say I have a JSON array like this:
"videos": [
{
"id": 25182,
"game": 115653,
"name": "Trailer",
"video_id": "BdA22Lh6Rwk"
},
27749,
{
"id": 29188,
"game": 115653,
"name": "A New Team and New Rivals in Pokémon Sword and Pokémon Shield! ⚔️🛡️",
"video_id": "ZBiTpi8ecTE"
}
]
Normally if the item's JSON format in videos is like videos[0] or videos[2] then I was able to parse it to Video like this:
json['videos']?.cast<Map<String, dynamic>>()?.map<Video>((f) {
return Video.fromJson(f);
})?.toList();
My Video class:
class Video {
int id;
int game;
String name;
String videoId;
Video({this.id, this.game, this.name, this.videoId});
Video.fromJson(Map<String, dynamic> json) {
id = json['id'];
game = json['game'];
name = json['name'];
videoId = json['video_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['game'] = this.game;
data['name'] = this.name;
data['video_id'] = this.videoId;
return data;
}
}
But if something with the different structure like videos[1] is within the array then I ended up with Exception. How can I parse videos[1] to Video with video[1] as Video's id?
You have to know the different formats and figure out which one each entry is.
You can do that by checking the type of the entry: Is it an integer or a map?
Example:
List<Video> videosFromJson(List<Object> videoJson) {
var result = <Video>[];
for (int i = 0; i < videoJson.length; i++) {
var entry = videoJson[i];
if (entry is Map<String, dynamic>) {
result.add(Video.fromJson(entry));
} else if (entry is int) {
result.add(Video()..id = entry);
} else {
throw FormatException("Not a recognized video format", entry, i);
}
}
return result;
}