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

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

Related

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

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"]);
}

Google pay integration in Flutter: paymentResult from Google is not valid JSON?

I'm trying to integrate Google Pay in my Flutter App following this official tutorial from Google:
https://developers.googleblog.com/2021/05/google-pay-introduces-flutter-plugin-for-payments.html
It works so far that I receive the paymentResult that is mentioned at the very end of the tutorial:
// In your Stateless Widget class or State
void onGooglePayResult(paymentResult) {
// Send the resulting Google Pay token to your server or PSP
}
When I log the paymentResult (paymentResult.toString()) it looks like this:
{apiVersion: 2, apiVersionMinor: 0, paymentMethodData: {description: Visa7001, info: {billingAddress: {address1: myStreet 11, address2: , address3: , administrativeArea: , countryCode: DE, locality: myCity, name: myName, phoneNumber: myNumber, postalCode: myCode, sortingCode: }, cardDetails: myDetails, cardNetwork: VISA}, tokenizationData: {token: examplePaymentMethodToken, type: PAYMENT_GATEWAY}, type: CARD}}
This looks good, now I want to parse this response, but it doesn't work with a JSON decoding, because the keys are not in quotation marks (apiVersion instead of "apiVersion").
According to the tutorial I need the token value (=examplePaymentMethodToken), and for my app I also want to access the user information like name and address, so that my user doesn't have to type in everything himself.
What type is the paymentResult if it's not JSON? How can I parse it?
P.S. I know Google did no mistake here, but their tutorial could really be a bit longer...
I'm using the latest pay package: pay: ^1.0.10
UPDATE:
I found a way to transform the paymentResult to a Map, but when I iterate over the Map it never gets to the third entry:
void onGooglePayResult(paymentResult) {
Map<String, dynamic> resMap = Map<String, dynamic>.from(paymentResult);
MyPaymentResult gPay = new MyPaymentResult();
log('resMap entries: ' + resMap.entries.toString());
resMap.entries.forEach((element) {
log("next key: " + element.key);
if (element.key == "apiVersion") {
log("Api Version found: " + element.value.toString());
gPay.apiVersion = element.value;
} else if (element.key == "apiVersionMinor") {
log("apiVersionMinor found: " + element.value.toString());
gPay.apiVersionMinor = element.value;
} else if (element.key == "paymentMethodData") {
log("paymentMethodData found");
}
}
}
The log:
[log] resMap entries: (MapEntry(apiVersion: 2), MapEntry(apiVersionMinor: 0), MapEntry(paymentMethodData: {description: Visa •••• 7001, info: {billingAddress: {address1: ...... }, cardDetails: 7001, cardNetwork: VISA}, tokenizationData: {token: examplePaymentMethodToken, type: PAYMENT_GATEWAY}, type: CARD}))
[log] next key: apiVersion
[log] Api Version found: 2
[log] next key: apiVersionMinor
[log] apiVersionMinor found: 0
The third entry never gets logged, altough it's in the logged Map??
Is there a easier way to convert a map to an Object?
This works, but this can't be the best solution:
void onGooglePayResult(paymentResult) {
log("Received result!! ${paymentResult.toString()}");
Map<String, dynamic> resMap = Map<String, dynamic>.from(paymentResult);
int apiVersion = resMap['apiVersion'];
int apiVersionMinor = resMap['apiVersionMinor'];
Map<String, dynamic> paymentMethodDataMap =
Map<String, dynamic>.from(resMap['paymentMethodData']);
String description = paymentMethodDataMap['description'];
String type = paymentMethodDataMap['type'];
Map<String, dynamic> infoMap =
Map<String, dynamic>.from(paymentMethodDataMap['info']);
String cardDetails = infoMap['cardDetails'];
String cardNetwork = infoMap['cardNetwork'];
Map<String, dynamic> tokenizationDataMap =
Map<String, dynamic>.from(paymentMethodDataMap['tokenizationData']);
String token = tokenizationDataMap['token'];
String tokenType = tokenizationDataMap['type'];
Map<String, dynamic> billingAddressMap =
Map<String, dynamic>.from(infoMap['billingAddress']);
String address1 = billingAddressMap['address1'];
String address2 = billingAddressMap['address2'];
String address3 = billingAddressMap['address3'];
String administrativeArea = billingAddressMap['administrativeArea'];
String countryCode = billingAddressMap['countryCode'].toString();
String locality = billingAddressMap['locality'];
String name = billingAddressMap['name'];
String phoneNumber = billingAddressMap['phoneNumber'];
int postalCode = int.parse(billingAddressMap['postalCode']);
String sortingCode = billingAddressMap['sortingCode'];
BillingAddress billingAddress = new BillingAddress(
address1,
address2,
address3,
administrativeArea,
countryCode,
locality,
name,
phoneNumber,
postalCode,
sortingCode);
GPayInfo gPayInfo =
new GPayInfo(billingAddress, cardDetails, cardNetwork);
GPayTokenizationData tokenizationData =
new GPayTokenizationData(token, tokenType);
PaymentMethodData paymentMethodData =
new PaymentMethodData(description, gPayInfo, tokenizationData);
GooglePayPaymentResult gPay = new GooglePayPaymentResult(
apiVersion, apiVersionMinor, paymentMethodData, type);
log(gPay.paymentMethodData.tokenizationData.token);
}
Resulting log: [log] examplePaymentMethodToken (which is what I was searching for)

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 Adding New Data into JSON Dart?

I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}

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
};