I want to get raw json data from GraphQL flutter.
here is part of the data I want to get:
{
"data": {
"countries": [
{
"name": "Andorra",
"code": "AD",
"native": "Andorra",
"phone": "376"
},
{
"name": "United Arab Emirates",
"code": "AE",
"native": "دولة الإمارات العربية المتحدة",
"phone": "971"
},
but this is the result that GraphQL returns to me:
{__typename: Query,
countries: [{__typename: Country, name: Andorra, code: AD, native: Andorra, phone: 376},
{__typename: Country, name: United Arab Emirates,
code: AE, native: دولة الإمارات العربية المتحدة, phone: 971},
the format is all wrong...
and this is my code:
void getCountryName() async {
pageState(AppState.loading);
String q = """
{
countries {
name
code
native
phone
}
}
""";
QueryResult res = await countriesClient.query(
QueryOptions(
document: gql(q),
optimisticResult: Country,
fetchPolicy: FetchPolicy.networkOnly,
),
);
}
print(res.data);
Related
This is the first time I am trying to use an HTTP Rest API with Post request, I am trying to use google Route API to compute direction, I follow the body from the google documentation however I keep getting this error
_CastError
Exception has occurred.
_CastError (type '_Map<String, Map<String, Map<String, double>>>' is not a subtype of type 'String' in type cast)
This is the first time I am trying a post request so I have no idea what is wrong
here' the code I use
import 'dart:async';
import 'dart:ffi';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'dart:convert' as convert;
class RouteAPI {
final String key = 'API_KEY_HERE';
Future<Void> getRoute() async {
final String Url =
'https://routes.googleapis.com/directions/v2:computeRoutes?KEY=$key';
var response = await http.post(Uri.parse(Url), body: {
"origin": {
"location": {
"latLng": {
"latitude": -6.2425120808113315,
"longitude": 106.85152720596324
}
},
},
"destination": {
"location": {
"latLng": {
"latitude": -6.2425120808113315,
"longitude": 106.85152720596324
}
},
},
"intermediates": {
"location": {
"latLng": {
"latitude": -6.178359098658539,
"longitude": 106.79219133887105
}
},
},
"travelMode": "DRIVE",
"routingPreference": "TRAFFIC_AWARE",
"polylineQuality": "HIGH_QUALITY",
"polylineEncoding": "ENCODED_POLYLINE",
//"departureTime": "",
"computeAlternativeRoutes": "FALSE",
"routeModifiers": {
"avoidTolls": false,
"avoidHighways": false,
"avoidFerries": false
},
"languageCode": "en-US",
"units": "IMPERIAL"
});
var json = convert.jsonDecode(response.body);
print(json.toString());
return json;
}
}
I tried to send a post body to request an encoded polyline from google route API
Don't include API keys directly in your project, use environment variables, once someone has your API key, this can end bad with a lot of debt. Make sure you reset your key.
flutter_dotenv.
You also need to include your API key in your request header, from what I read. Compute a route docs
You're receiving a type error because you're not encoding your body JSON into a string.
convert.jsonEncode({"example": "example"})
You then aren't setting the content type header to let the API know what kind of data you're sending, and the API Key, along with the field mask header.
headers: {
"Content-Type": "application/json",
"X-Goog-Api-Key": "API_KEY",
"X-Goog-FieldMask": "routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline"};
I've replaced your response section for you.
var response = await http.post(Uri.parse(url),
body: convert.jsonEncode({
"origin": {
"location": {
"latLng": {
"latitude": -6.2425120808113315,
"longitude": 106.85152720596324
}
},
},
"destination": {
"location": {
"latLng": {
"latitude": -6.2425120808113315,
"longitude": 106.85152720596324
}
},
},
"intermediates": {
"location": {
"latLng": {
"latitude": -6.178359098658539,
"longitude": 106.79219133887105
}
},
},
"travelMode": "DRIVE",
"routingPreference": "TRAFFIC_AWARE",
"polylineQuality": "HIGH_QUALITY",
"polylineEncoding": "ENCODED_POLYLINE",
//"departureTime": "",
"computeAlternativeRoutes": "FALSE",
"routeModifiers": {
"avoidTolls": false,
"avoidHighways": false,
"avoidFerries": false
},
"languageCode": "en-US",
"units": "IMPERIAL"
}),
headers: {
"Content-Type": "application/json",
"X-Goog-Api-Key": "API_KEY",
"X-Goog-FieldMask": "routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline"
});
For my Calendar i get the following data as JSON from the Backend (*JAVA-Type = Map<LocalDate, List<Event>>):
{
"2022-05-28": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
}
],
"2022-05-27": [
{
"id": 2,
"title": "Multi day Event",
"fromDate": "2022-05-27T12:22:03.873569",
"toDate": "2022-05-28T11:22:03.873569",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "sozial"
},
{
"id": 1,
"title": "Testevent",
"fromDate": "2022-05-27T11:21:04.573754",
"toDate": "2022-05-27T12:21:04.573754",
"room": {
"id": 1,
"name": "TestRoom",
},
"user": {
"id": 1,
"name": "Andi",
"city": "",
"email": "test#gmail.com",
},
"eventType": "normal"
}
],
}
My Event Class looks like:
Class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
}
Now i need the same structure i had in the Backend (Map<DateTime, <List<Event>>) for my Calendar widget and i have no real clue on how to do it. I know how to convert json data into an object if i get a list of an object, but how can i store the date as key of the resulting map?
My code by now:
Future<Map<DateTime, List<Event>>> getEvents(DateTime _fromDate, DateTime
_endDate) async {
String _from = _fromDate.toString().split('.').first;
String _end = _endDate.toString().split('.').first;
final response = await get('${_url}calendar/events/$_from/$_end',
headers: {HttpHeaders.authorizationHeader: 'Bearer $_bearer'});
if (response.status.hasError) {
return Future.error('${response.statusText}');
} else {
final parsed = jsonDecode(response.body);
return parsed;
}
}
You need to do something like that:
var json = {...}; // <-- json obj
// method to parse data to map with list Event
dynamic fromJson(Map<String, dynamic> json){
var map = new Map();
json.keys.forEach((key){
// key is the date
map[key] = json[key].map((e) => Event.fromJson(e)).toList(); // <- need to create a method fromJson in your Event class
});
return map;
}
(...)
class Event {
int id;
String title;
DateTime fromDate;
DateTime toDate;
Room room;
User user;
String eventType;
fromJson(Map<String, dynamic> json) => Event(...); // <- parse json to Event class
}
I have been trying to get a particular field in realtime database. The result is not the one I expected.
Version used Flutter - 3.0.0 firebase_core: ^1.17.0 firebase_database: ^9.0.14
This is the database
{
"patients_today": {
"VN76Y0TNM": {
"MMS07K5CCLT": {
"doctor": "Dr. John M A",
"doctor_id": "MMS07K5CCLT",
"patients": {
"MMXZV5F8A": {
"appointment_end": 1652709621742,
"appointment_start": 1652705121742,
"arrived_at": 1652705098791,
"dob": 712866600000,
"gender": "male",
"id": "MMXZV5F8A",
"mail": "min#min.c",
"mobile": "+919400490000",
"name": "Minhaz MA",
"status": "WAITING"
}
}
}
}
}
}
var ref = await FirebaseDatabase.instanceFor(app:Firebase.app()).ref()
.child("patients_today")
.child("VN76Y0TNM")//clinicId
.child("MMS07K5CCLT")//doctorId
.child("patients")
.child("MMXZV5F8A")//patientId
.get();
var data = ref.value;
The above code is returning the following
{
"MMS07K5CCLT": {
"doctor": "Dr. John M A",
"doctor_id": "MMS07K5CCLT",
"patients": {
"MMXZV5F8A": {
"appointment_end": 1652709621742,
"appointment_start": 1652705121742,
"arrived_at": 1652705098791,
"dob": 712866600000,
"gender": "male",
"id": "MMXZV5F8A",
"mail": "min#min.c",
"mobile": "+919400490000",
"name": "Minhaz MA",
"status": "WAITING"
}
}
}
}
Instead of the following patient object
{
"appointment_end": 1652709621742,
"appointment_start": 1652705121742,
"arrived_at": 1652705098791,
"dob": 712866600000,
"gender": "male",
"id": "MMXZV5F8A",
"mail": "min#min.c",
"mobile": "+919400490000",
"name": "Minhaz MA",
"status": "WAITING"
}
SUMMARY:
Structure - rtdb/"patients_today"/{$clinicId}/{$doctorId}/"patients"/{$patientId}/{patient-data}
Request - rtdb/"patients_today"/{$clinicId}/{$doctorId}/"patients"/{$patientId}
Returning - rtdb/"patients_today"/{$clinicId}
use var ref = await FirebaseDatabase.instance.ref("patients_today/VN76Y0TNM/MMS07K5CCLT/patients/MMXZV5F8A").get();
hope it will help you!
Consider the following data structure:
{
"company": {
"idCompany1": {
"data": {
"address": "",
"companyName": "Company 1",
"logo": "assets/Logo1.png",
"nit": "",
"phone": ""
}
},
"idCompany2": {
"data": {
"address": "",
"companyName": "Company 2",
"logo": "assets/Logo2.png",
"nit": "",
"phone": ""
}
},
"idCompany3": {
"data": {
"address": "",
"companyName": "Company 3",
"logo": "assets/Logo3.png",
"nit": "",
"phone": ""
}
}
},
"users": {
"idUser1": {
"data": "user1#test.com",
"companies": {
"idCompany1": true,
"idCompany3": true
}
},
"idUser2": {
"data": "user2#test.com",
"companies": {
"idCompany2": true
}
}
}
}
Basically what I need to do in the case of user1 is to read the data of the companies to which it belongs, this is Company 1 and Company 3. How can I do that?
The way I found, is by obtaining a list of IDs of those companies, which I have in listaIdEmpresas and then consulting each one through a forEach loop in the following way:
Future<List<EmpresaDatosModel>> cargarEmpresaDatosListado(List<String> listaIdEmpresas) async {
final List<EmpresaDatosModel> listaEmpresas = new List();
listaIdEmpresas.forEach((id) async {
Query resp = db.child('company/$id/data');
final snapshot = await resp.once();
final temp = EmpresaDatosModel.fromJson(Map<String,dynamic>.from(snapshot.value));
temp.idEmpresa = id;
listaEmpresas.add(temp);
print('${temp.companyName} up');
await resp.once().then((snapshot) {});
});
listaEmpresas.forEach((element) {print('Emp ${element.companyName}');});
return listaEmpresas;
}
However, this process is not efficient and I need to manage a delay for waiting the loop.
What would be the right way to do query data from a list of Ids directly?
I am trying to learn how to (and best practices) to integrate Stripe into my mobile app.
I know from another post (Why there is no billing address in stripe Checkout) that Stripe has deprecated Billing Address Support however, I'd still want to be able to add that functionality into my app.
Currently the code I have is:
Future<void> createPaymentMethod(BuildContext context,
Map<String, String> billingAddress, String name, String phoneNumber) async {
StripePayment.setStripeAccount(null);
// Here to add the credit Card
PaymentMethod paymentMethod = PaymentMethod();
paymentMethod = await StripePayment.paymentRequestWithCardForm(
CardFormPaymentRequest(),
).then((PaymentMethod paymentMethod) {
paymentMethod.billingDetails = BillingDetails.fromJson({
'address': billingAddress,
'name': name,
'phone': phoneNumber,
});
return paymentMethod;
}).catchError((e) {
print('Error Card: ${e.toString()}');
});
paymentMethod != null
? processPaymentAsDirectCharge(paymentMethod,
context)
: AwesomeDialog(
context: context,
title: 'Uh oh! A wild error has appeared!',
desc:
'Seems like we cant process this card. Please double check your input or try a different card',
animType: AnimType.SCALE,
dialogType: DialogType.WARNING,
btnOkOnPress: () {})
.show();
}
Where I have a button that does:
onPressed: () {
createPaymentMethod(
context,
{
'city': cityController.text,
'line1': streetAddressController.text,
'postal_code': zipcodeController.text, // **postal_code does not show up for some reason**
'state': stateController.text
},
fullNameController.text,
'8007897890');
}
And What I got back from the paymentMethod in my console is:
paymentMethod: {
created: 1599242290.0,
id: pm_someIdHereThatGotReplacedByThis,
livemode: false,
type: card,
billingDetails: {name: John Doe,
phone: phoneNumber,
address: {city: Doggo Town, line1: 555 Puppy Street, state: CA}},
card: {addressLine1: null, addressLine2: null, brand: visa, country: US, expMonth: 4,
expYear: 2024, funding: credit, last4: 4242}}
However, in my Logs in Stripe it shows:
{
"id": "pm_someIdHereThatGotReplacedByThis",
"object": "payment_method",
"billing_details": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": null,
"name": null,
"phone": null
},
"card": {
"brand": "visa",
"checks": {
"address_line1_check": null,
"address_postal_code_check": null,
"cvc_check": null
},
"country": "US",
"exp_month": 4,
"exp_year": 2024,
"funding": "credit",
"generated_from": null,
"last4": "4242",
"networks": {
"available": [
"visa"
],
"preferred": null
},
"three_d_secure_usage": {
"supported": true
},
"wallet": null
},
"created": 1599240880,
"customer": null,
"livemode": false,
"metadata": {
},
"type": "card"
}
my question is:
How do I setup my function so that the "checks" and "billing_details" fields will be filled with the information provided by the customer? Should I be adding something to the function
paymentMethod = await StripePayment.paymentRequestWithCardForm(
CardFormPaymentRequest()).then(...)
This is the field I am talking about:
"checks": {
"address_line1_check": null,
"address_postal_code_check": null,
"cvc_check": null
},
"billing_details": {
"address": {
"city": null,
"country": "US",
"line1": null,
"line2": null,
"postal_code": null,
"state": null
},
"email": null,
"name": null,
"phone": null
},
Thanks