sessiontoken - google map api not working as expected - google-maps

As per the Google documentation if we use a sessiontoken in the autocomplete API followed by placeDetails api then subsequent all the calls will be grouped together and it will be billed as a single request. But while using, it is actually not happening and Google counts all of the requests as individual.
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=s&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=st&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=sta&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=stat&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=stati&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=statio&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=station&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8&location=37.4220309%2C-122.0839848&radius=5000&strictbounds=true
I/flutter (12295): Get URI: https://maps.googleapis.com/maps/api/place/details/json?place_id=ChIJr3mngX66j4ARcUF6Ln6aAmk&key=<API_KEY>&sessiontoken=d7f1f97f-621d-45cf-b8fd-38d74c976fd8
I/flutter (12295): Instance of 'PlaceDetails'
In the above scenario, based on the documentation it should have counted as a single request but in the Google console - API usage, it's showing as 9 separate requests.
Is it the right way to use sessiontoken? Am I missing something?
Edit > Added logs for two search groups with placeDetails API. The sessiontoken are being refreshed after every the place details.
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=sta&key=<API_KEY>&sessiontoken=3dd4163e-c5aa-4504-a652-0c7861704efa&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=stat&key=<API_KEY>&sessiontoken=3dd4163e-c5aa-4504-a652-0c7861704efa&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=station&key=<API_KEY>&sessiontoken=3dd4163e-c5aa-4504-a652-0c7861704efa&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/details/json?place_id=<PLACE_DETAILS>&key=<API_KEY>&sessiontoken=3dd4163e-c5aa-4504-a652-0c7861704efa
I/flutter (17558): Instance of 'PlaceDetails'
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=sch&key=<API_KEY>&sessiontoken=a204cfe5-0824-4e2c-8fe6-5382ef542e76&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=scho&key=<API_KEY>&sessiontoken=a204cfe5-0824-4e2c-8fe6-5382ef542e76&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=schoo&key=<API_KEY>&sessiontoken=a204cfe5-0824-4e2c-8fe6-5382ef542e76&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/autocomplete/json?input=school&key=<API_KEY>&sessiontoken=a204cfe5-0824-4e2c-8fe6-5382ef542e76&location=22.863185%2C87.3552233&radius=5000&strictbounds=true
I/flutter (17558): Get URI: https://maps.googleapis.com/maps/api/place/details/json?place_id=<PLACE_DETAILS>&key=<API_KEY>&sessiontoken=a204cfe5-0824-4e2c-8fe6-5382ef542e76
I/flutter (17558): Instance of 'PlaceDetails'

Related

API json no values, The method '[]' was called on null

I'm using World Air Quality API. I need 3 values "AQI", "PM10" and "PM25". Some cities dosen't have value PM10 and my app is freezing on request with error:
E/flutter ( 1339): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 1339): Receiver: null
E/flutter ( 1339): Tried calling: []("v")
How I can add if statement for checking if this value [pm10][v] exist in json?
My code looks like this:
AirQuality(Map<String, dynamic> jsonBody){
aqi = int.tryParse(jsonBody['data']['aqi'].toString()) ??-1;
pm25 = int.tryParse(jsonBody['data']['iaqi']['pm25']['v'].toString()) ??-1;
pm10 = int.tryParse(jsonBody['data']['iaqi']['pm10']['v'].toString()) ??-1;
}

How to encode Map into Json in Dart?

I am trying to convert Map<DateTime,List> into json with following code:
String ecoded = json.encode({
DateTime.now(): ["Sample data", 3,true,"Example", 2],
});
But compiler give following error:
E/flutter (11773): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled
Exception: Converting object to an encodable object failed: _LinkedHashMap len:1
E/flutter (11773): #0 _JsonStringifier.writeObject
(dart:convert/json.dart:688:7)
E/flutter (11773): #1 _JsonStringStringifier.printOn
(dart:convert/json.dart:877:17)
E/flutter (11773): #2 _JsonStringStringifier.stringify
(dart:convert/json.dart:862:5)
E/flutter (11773): #3 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter (11773): #4 JsonCodec.encode (dart:convert/json.dart:172:45)
I converted many times Map into json but in all cases Map was something like that:
Map<String,dynamic>
This error is occurring because there is List
If anyone know how to convert Map<DateTime,List> into json then Answer this question.
Thanks
Json only supports Strings as keys. So if you want to use DateTimes as keys you have to manually convert it first:
String ecoded = json.encode({
DateTime.now().toString(): ["Sample data", 3,true,"Example", 2],
});
or
Map<String, dynamic> result = datetimeMap.map((k, v) => MapEntry('$k', v))
In dart programming, json.encode(DateTime.Now()) which is not possible. You need to convert by using Iso8601String() or toString()
String ecoded = json.encode({
DateTime.now().toIso8610String(): ["Sample data", 3,true,"Example", 2],
});

Fetching data from json file?

I am converting a XML file to JSON file using jsonDecode(jsonEncode(file)). The problem is when I try to Fetch data from the JSON file with an index number. It prints only one letter. I have inserted the code below. See if there is any problem with my code. If I try to fetch data with string it shows error.
My file is large. So, I am only inserting a small portion of the output.
I have already tried the xml2json package and I got the output.
But in dart without any package we can convert the XML file to JSON with import 'dart:convert';. With the documentation, I came to understand it only works for small files. If it also works for large files, I want to know the problem in this code and the solution.
And that is what I tried in the following code.
This is my code,
Future<String> decodexml() async {
final file =
await rootBundle.loadString('assets/xml_file/belovedskincare.xml');
final jsonData = jsonDecode(jsonEncode(file));
debugPrint('$jsonData');
return jsonData;
}
When I print $jsonData this is the output,
<rss version="2.0"
I/flutter (24058): xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
I/flutter (24058): xmlns:content="http://purl.org/rss/1.0/modules/content/"
I/flutter (24058): xmlns:wfw="http://wellformedweb.org/CommentAPI/"
I/flutter (24058): xmlns:dc="http://purl.org/dc/elements/1.1/"
I/flutter (24058): xmlns:wp="http://wordpress.org/export/1.2/"
I/flutter (24058): >
I/flutter (24058):
I/flutter (24058): <channel>
I/flutter (24058): <title>Beloved Skincare</title>
I/flutter (24058): <link>https://belovedskincare.com.my</link>
I/flutter (24058): <description>Food for your Skin</description>
I/flutter (24058): <pubDate>Sat, 02 Oct 2021 09:17:04 +0000</pubDate>
I/flutter (24058): <language>en-US</language>
I/flutter (24058): <wp:wxr_version>1.2</wp:wxr_version>
I/flutter (24058): <wp:base_site_url>https://belovedskincare.com.my</wp:base_site_url>
I/flutter (24058): <wp:base_blog_url>https://belovedskincare.com.my</wp:base_blog_url>
When I try to print some data from jsonData, this is the output I get,
code:
var json = jsonData['rss'];
debugPrint('$json');
output:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
code:
var json = jsonData[0];
debugPrint('$json');
output:
I/flutter (24058): <
code:
var json = jsonData[1];
debugPrint('$json');
output:
I/flutter (24058): r
To my understanding, It seems each letter from the json file saved separately in the jsonData variable.
I am already using the xml2json package.
No, you don't. There is no such thing in your code. You are just calling meaningless functions that act as if XMl data were json. It's not and that is why you get errors.
I suggest you actually read the example on the package you are using and then write your code accordingly. A package is not magic that you reference and then it works. You have to call their functions.

Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)

I was following this flutter beginner tutorial from net ninja here .But my timezone UTC +5:30 in Sri Lanka so i tried to add the half an hour but it keep getting this error that I cant fix. Please help me if you can!!.
Full Traceback error:
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 797ms.
E/flutter (31824): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)
E/flutter (31824): 5:3
E/flutter (31824): ^
E/flutter (31824):
E/flutter (31824): #0 int._throwFormatException (dart:core-patch/integers_patch.dart:131:5)
E/flutter (31824): #1 int._parseRadix (dart:core-patch/integers_patch.dart:142:16)
E/flutter (31824): #2 int._parse (dart:core-patch/integers_patch.dart:100:12)
E/flutter (31824): #3 int.parse (dart:core-patch/integers_patch.dart:63:12)
E/flutter (31824): #4 WorldTime.getTime (package:world_time_app/services/world_time.dart:24:39)
E/flutter (31824): <asynchronous suspension>
E/flutter (31824): #5 _LoadingState.SetupWorldTime (package:world_time_app/pages/loading.dart:14:3)
E/flutter (31824): <asynchronous suspension>
E/flutter (31824):
Code :
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'dart:convert';
class WorldTime{
String location;
String time;
String flag;
String url;
WorldTime({this.location, this.flag, this.url});
Future<void> getTime() async{
Response response = await get('https://www.worldtimeapi.org/api/timezone/$url');
Map data = jsonDecode(response.body.toString());
//print(data);
String datetime = data['datetime'];
String offset = data['utc_offset'].substring(2,5);
//print(dataTime);
//print(offset);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(hours: int.parse(offset)));
time = now.toString();
print(time);
}
}
In my case I was passing subroutes inside authority parameter, like this:
var response =
await http.get(Uri.https('https://favqs.com/api/quotes/', '4'), headers: {
'Content-Type': 'application/json',
'Authorization': "Token token='xxxxxxxxxxxxxxxx'",
});
but after removing https and moving /api/quotes/ in the second parameter, the issue got solved.
var response =
await http.get(Uri.https('favqs.com', '/api/quotes/4'), headers: {
'Content-Type': 'application/json',
'Authorization': "Token token='xxxxxxxxxxxxxxxx'",
});
You are trying to parse 5:3 as int, which causes the error.
The issue is in the substring that is returning an invalid number (5:3).
First you should do data['utc_offset'].substring(1,3) to get only the hour
And data['utc_offset'].substring(4,6) to get only the minutes.
After that, you can manipulate as you wish, like:
String offsetHours = data['utc_offset'].substring(1, 3);
String offsetMinutes = data['utc_offset'].substring(4, 6);
DateTime now = DateTime.parse(datetime);
now = now.add(Duration(
hours: int.parse(offsetHours),
minutes: int.parse(offsetMinutes)),
);

Mapping a class to json while calling an Api showing error in flutter

Map<String, dynamic> toJson() => {
"username": username,
"Event_date_time": eventDateTime,
"Event_name": eventName,
"Event_Address": eventAddress,
"Utensils": utensils,
"Hot_serve": hotServe,
"Carting": carting,
"Beverage ": List<dynamic>.from(Beverage.map((x) => x.toJson())),
};
class Beverage {
String beveragesitem;
String beveragesCount;
Beverage({
this.beveragesitem,
this.beveragesCount,
});
factory Beverage.fromJson(Map<String, dynamic> json) => Beverage(
beveragesitem: json["Beveragesitem"],
beveragesCount: json["Beverages_count"],
);
Map<String, dynamic> toJson() => {
"Beveragesitem": beveragesitem,
"Beverages_count": beveragesCount,
};
}
Error showing like below
Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null.
E/flutter ( 6308): Receiver: null
E/flutter ( 6308): Tried calling: length
E/flutter ( 6308): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 6308): #1 _Uri._uriEncode (dart:core-patch/uri_patch.dart:44:23)
E/flutter ( 6308): #2 Uri.encodeQueryComponent (dart:core/uri.dart:1103:17)
E/flutter ( 6308): #3 mapToQuery. (package:http/src/utils.dart:19:13)
E/flutter ( 6308): #4 CastMap.forEach. (dart:_internal/cast.dart:286:8)
E/flutter ( 6308): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
Can anyone help correcting this issue?
Where are you calling toJson()maybe there is the problem?
I have found the issue, may be this will help someone, I was trying to call an Api here with random values for testing purpose. some values were empty while I was testing, when the model class doesnot find value in the structure throwing error as 'length' was called on null, i.e, no value entered for that model variable. When I put all values for the model class it returned success
In short - while calling toJson method, no values should be null