How to call a List with Strings to make the call dynamic - flutter

I'm searching for create a dynamic form which contain DropDownButtons.
Before do that, I'm trying something on DartPad to know if it's possible to call a list with some Strings.
Below an example about what I want to do (maybe what I'm searching for is now possible) :
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},
{"name": "5A"}
];
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(listOfType);
}
In this case it print "listOf3AInitial" and I want to print the List {"name": "4A"},{"name": "5A"}.
How it is possible to do that ?
Regards

You have to map a string of it's value to do so. For example
List<Map<String, String>> listOf3AInitial = [{"name": "4A"}, {"name": "5A"}];
Map<String, List<Map<String, String>>> list3AInitialMap = {
"listOf3AInitial" : listOf3AInitial,
};
Now you can get a value from this map like
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(list3AInitialMap[listOfType]);

Your var listOfType returns a String. Unfortunately, you cannot use/convert String as a variable name.
In this case, you may want to use a map:
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},{"name": "5A"}];
List<Map<String, String>> listOf3BInitial = [{"name": "4B"},{"name": "5B"}];
String _listOf = "listOf";
String _yearA = "3A"; //A
String _yearB = "3B"; //B
String _type = "Initial";
//Reference your lists in a map
Map<String, dynamic> myLists = {
"listOf3AInitial": listOf3AInitial,
"listOf3BInitial": listOf3BInitial
};
//This returns your listOf3AInitial
var listOfType = myLists["$_listOf$_yearA$_type"];
print(listOfType);
//You may also access it directly
print(myLists["$_listOf$_yearB$_type"]);
}

Related

how to convert json string in dart flutter?

I have string response like this, I got only below response of my api.
{authToken: msadnmsandnasdn}
and I have to convert as below.
{"authToken": "msadnmsandnasdn"}
So how i can do this please Help me.
You can use various manipulation operations to do that manually:
import 'dart:convert';
void main() {
var s = "{authToken: msadnmsandnasdn, name:risheek}";
var kv = s.substring(0,s.length-1).substring(1).split(",");
final Map<String, String> pairs = {};
for (int i=0; i < kv.length;i++){
var thisKV = kv[i].split(":");
pairs[thisKV[0]] =thisKV[1].trim();
}
var encoded = json.encode(pairs);
print(encoded);
}
Output:
{"authToken":"msadnmsandnasdn"," name":"risheek"}
You need to use jsonDecode on that string like this:
var response = {authToken: msadnmsandnasdn....};
var result = jsonDecode(response);

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

Flutter Dart The getter '' was called on null

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

How to convert a list of numbers in a String to a list of int in dart

After reading a line from a file, I have the following String:
"[0, 1, 2, 3, 4]"
What is the best way to convert this String back to List<int>?
Just base on following steps:
remove the '[]'
splint to List of String
turn it to a int List
Sth like this:
List<int> list =
value.replaceAll('[', '').replaceAll(']', '')
.split(',')
.map<int>((e) {
return int.tryParse(e); //use tryParse if you are not confirm all content is int or require other handling can also apply it here
}).toList();
Update:
You can also do this with the json.decode() as #pskink suggested if you confirm all content is int type, but you may need to cast to int in order to get the List<int> as default it will returns List<dynamic> type.
eg.
List<int> list = json.decode(value).cast<int>();
You can convert String list to int list by another alternate method.
void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
stringList.map((e){
var intValue = int.tryParse(e);
intList.add(intValue!);
print(intList);
});
print(a);
}
Or by using for in loop
void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
for (var i in stringList){
int? value = int.tryParse(i);
intList.add(value!);
print(intList);
}
}

Nested Map operation in Dart

I have a Maps of type
Map<String,Map<String,bool>> outerMap;
Map<String,bool> innerMap_1 ,innerMap_2;
I need to nest innerMaps inside outerMap.
innerMap_1 = { 'time_1':true , 'time_2':false };
innerMap_1 = { 'time_3':false ,'time_4':true };
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
I need to store outerMap as a string on the Sqlite Database. When I try
jsonEncode(outerMap);
There is an error because it is nested.
How to effectively convert the outerMap to String and then convert that string back to Map ?
outerMap = { 'date_1':innerMap_1 , 'date_2':innerMap2 };
The thing is that you had a spelling error and therefore there was an error. But in my solution I fixed that.
Another thing to notice is that in order to use the jsonEncode function you have to import the dart:convert package.
import 'dart:convert';
void main() {
Map<String, Map<String, bool>> outerMap;
Map<String, bool> innerMap_1, innerMap_2;
innerMap_1 = {'time_1': true, 'time_2': false};
innerMap_2 = {'time_3': false, 'time_4': true};
outerMap = {'date_1': innerMap_1, 'date_2': innerMap_2};
String json = jsonEncode(outerMap);
print(json);
print(jsonDecode(json));
}
You can test your dart code on dartpad.dev.