Dart FormatException: Unexpected character (at character 1) in empty json - json

Basically what the title says, simply trying to implement a condition that either writes to a an existing file or decodes the json and then writes to the same file.
code:
import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';
void main() async{
print("hello");
int prio1;
print("Title:");
String? title1 = stdin.readLineSync();
print("description:");
String? des = stdin.readLineSync();
ToDo test = new ToDo(title1, des, 0, false);
String test11 = jsonEncode(test);
print(test11);
final filename = 'vault.json';
if(File(filename).length == 0)
{
new File(filename).writeAsString("["+test11+"]");
}
else{
String test = await jsonDecode(filename);
String test2 = test.substring(0, test.length - 1);
String test3 = ","+test2 +"]";
new File(filename).writeAsString(test3);
}
}
my json file "vault.json" is empty, yet I get this error:
Unhandled exception:
FormatException: Unexpected character (at character 1)
vault.json
^
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1272:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:937:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:40:10)
#4 JsonDecoder.convert (dart:convert/json.dart:612:36)
#5 JsonCodec.decode (dart:convert/json.dart:216:41)
#6 jsonDecode (dart:convert/json.dart:155:10)
#7 main (file:///D:/Code/dart/json/json.dart:23:27)
#8 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#9 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
any help appreciated!
edit:added ToDo.dart in case you want to run the program
class ToDo {
String? title,description;
int prio;
bool completed;
ToDo(this.title, this.description, this.prio, this.completed);
ToDo.fromJson(Map<String,dynamic> json):
title = json['title'],
description = json['description'],
prio = json['prio'],
completed = json['completed'];
Map<String,dynamic> toJson() => {
'title':title,
'description':description,
'prio':prio,
'completed':completed,
};
}

I am not exactly sure what you want to achieve but this snippets lets you read and write into that json file.
Please notice that we have to read the json from the file first with readAsLinesSync before decoding. This caused your error, since you didn't try to decode the json object (for example [{"title":"test","description":"test","prio":0,"completed":false}] but just the file name (vault.json), which of course isn't a valid json.
import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';
void main() async{
const filename = 'vault.json';
print('Enter title');
String? title = stdin.readLineSync();
print('Enter description');
String? description = stdin.readLineSync();
final file = File(filename);
final fileIsEmpty = await file.length() == 0;
if(fileIsEmpty)
{
// create a test ToDO
ToDo testToDo = ToDo(title, description, 0, false);
String test11 = jsonEncode(testToDo);
// write to File
await File(filename).writeAsString(test11);
}
else {
// read the ToDO from the file
final json = File(filename).readAsLinesSync();
final encode = jsonDecode(json.first);
ToDo storedToDo = ToDo.fromJson(encode);
print(storedToDo);
}
}
Also consider using snake case for your file names, which is best practice.
Happy coding!

Related

flutter json decode and file append not working on second run

I was wondering if someone could help? I'm trying to load a file with json content, decode it, convert to a model/object add another element.
The way I'm trying to do this is as follows:
Flow 1: Check file exists = true -> return file object -> decode string to json -> convert to model/object -> add element -> back to json -> to string -> save file.
Flow 2: Check file exists = false -> create file -> add a json template -> return file object -> decode string to json -> convert to model/object -> add element -> back to json -> to string -> save file.
This is working on the first run (flow 1), it'll create the file, add the template then add the first new element. However, when I run it a second time (flow 2), I always get an throwback.
As we speak with the code below, the error is:
E/flutter (13140): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
E/flutter (13140): #0 FileController.writeSingleResponseToFile (package:reefcommander/controllers/FileController.dart:33:39)
E/flutter (13140): <asynchronous suspension>
E/flutter (13140):
This is the code I'm using.
FileController.dart
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:intl/intl.dart';
import 'package:reefcommander/models/ReadingsData.dart';
import 'package:reefcommander/models/SingleDataReqResponse.dart';
import 'dart:convert';
class FileController {
static String date = DateFormat("dd-MM-yyyy").format(DateTime.now());
static String template =
'{"name": "_NAME_", "friendlyName": "_FNAME_", "results": []}';
static final Map<String, String> nameDefenitions = {
'ec': 'EC',
'ph': 'pH',
'atoDayRate': 'Evap Rate',
'sumpTemp': 'Temp (sump)',
'tankTemp': 'Temp (tank)'
};
static Future<File> checkFileExists(String type) async {
readFile(type);
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
return file;
}
static writeSingleResponseToFile(SingleDataReqResponse resp) async {
final File file = await checkFileExists(resp.name.toString());
var r = Map<String, dynamic>.from(jsonDecode(await file.readAsString()));
print(r.runtimeType);
ReadingsData existingdata = ReadingsData.fromJson(r[0]);
//ReadingsData existingdata =
// r.map<ReadingsData>((json) => ReadingsData.fromJson(json));
print(existingdata);
existingdata.results!.add(Results(stamp: resp.stamp, value: resp.value));
print('DATA: ${existingdata.toJson().toString()}');
file.writeAsString(jsonEncode(existingdata.toJson().toString()));
}
static Future<void> deleteFile(String type) async {
try {
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
if (file.existsSync()) {
await file.delete();
} else {}
} catch (e) {
// Error in getting access to the file.
}
}
static Future<String> readFile(String type) async {
String text = '';
try {
final Directory? directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory();
final String filename = '${directory!.path}/${date}_$type.json';
final File file = File(filename);
if (file.existsSync()) {
text = await file.readAsString();
} else {
file.create(recursive: true);
String tempbase = template;
String write = tempbase
.replaceAll('_NAME_', type.toString())
.replaceAll('_FNAME_', nameDefenitions[type]!);
await file.writeAsString(write);
text = await file.readAsString();
}
} catch (e) {
print("Read error");
}
return text;
}
}
ReadingsData.dart
import 'dart:convert';
class ReadingsData {
String? name;
String? friendlyName;
List<Results>? results;
ReadingsData(
{required this.name, required this.friendlyName, required this.results});
ReadingsData.fromJson(Map<String, dynamic> json) {
name = json['name'];
friendlyName = json['friendlyName'];
if (json['results'] != null) {
results = <Results>[];
json['results'].forEach((v) {
results!.add(Results.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['friendlyName'] = friendlyName;
if (results != null) {
data['results'] = results!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Results {
String? stamp;
String? value;
Results({required this.stamp, required this.value});
Results.fromJson(Map<String, dynamic> json) {
stamp = json['stamp'];
value = json['value'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['stamp'] = stamp;
data['value'] = value;
return data;
}
}
Test code
FileController.writeSingleResponseToFile(
SingleDataReqResponse(name: "test", stamp: "10:22:00", value: "2222"));
For anyone else in my situation, I've resolved it. Solution below.
static writeSingleResponseToFile(SingleDataReqResponse resp) async {
final File file = await checkFileExists(resp.name.toString());
ReadingsData existingdata =
ReadingsData.fromJson(jsonDecode(await file.readAsString()));
existingdata.results!.add(Results(stamp: resp.stamp, value: resp.value));
file.writeAsString(jsonEncode(existingdata.toJson()));
}

Flutter: Unhandled Exception: type 'Null' is not a subtype of type 'String' when trying to run app

Trying to bulild app but it keeps crashing! When I click on the error it is leading me to two files video.dart and video_controller.dart.
It is pointing me on specific lines but when I click on them there is no specific error explanation of error I get. I tried to look for solution online but I can't understand what is this error telling me! If u know the solution please let me know!
ERROR:
/flutter ( 5006): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Null' is not a subtype of type 'String'
E/flutter ( 5006): #0 Video.fromSnap
package:tiktok_project/models/video.dart:48
E/flutter ( 5006): #1 VideoController.onInit.<anonymous closure>
package:tiktok_project/controllers/video_controller.dart:19
video.dart :
import 'package:cloud_firestore/cloud_firestore.dart';
class Video {
String username;
String uid;
String id;
List likes;
int commentCount;
int shareCount;
String songName;
String caption;
String videoUrl;
String thumbnail;
String profilePhoto;
Video({
required this.username,
required this.uid,
required this.id,
required this.likes,
required this.commentCount,
required this.shareCount,
required this.songName,
required this.caption,
required this.videoUrl,
required this.profilePhoto,
required this.thumbnail,
});
Map<String, dynamic> toJson() => {
"username": username,
"uid": uid,
"profilePhoto": profilePhoto,
"id": id,
"likes": likes,
"commentCount": commentCount,
"shareCount": shareCount,
"songName": songName,
"caption": caption,
"videoUrl": videoUrl,
"thumbnail": thumbnail,
};
static Video fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return Video(
username: snapshot['username'],
uid: snapshot['uid'],
id: snapshot['id'],
likes: snapshot['likes'],
commentCount: snapshot['commentCount'],
shareCount: snapshot['shareCount'],
songName: snapshot['songName'],
caption: snapshot['caption'],
videoUrl: snapshot['videoUrl'],
profilePhoto: snapshot['profilePhoto'],
thumbnail: snapshot['thumbnail'],
);
}
}
video_controller.dart:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:tiktok_project/const.dart';
import 'package:tiktok_project/models/video.dart';
class VideoController extends GetxController {
final Rx<List<Video>> _videoList = Rx<List<Video>>([]);
List<Video> get videoList => _videoList.value;
#override
void onInit() {
super.onInit();
_videoList.bindStream(
firestore.collection('videos').snapshots().map((QuerySnapshot query) {
List<Video> retVal = [];
for (var element in query.docs) {
retVal.add(
Video.fromSnap(element),
);
}
return retVal;
}));
}
likeVideo(String id) async {
DocumentSnapshot doc = await firestore.collection('videos').doc(id).get();
var uid = authController.user.uid;
if ((doc.data() as dynamic)['likes'].contains(uid)) {
await firestore.collection('videos').doc(id).update({
'likes': FieldValue.arrayRemove([uid])
});
} else {}
await firestore.collection('videos').doc(id).update({
'likes': FieldValue.arrayUnion([uid])
});
}
}
That's a null safety error.
You need to do something like this
username: snapshot['username'] ?? '',
For each element that is String, or use the type "String?" with the interrogation point telling the compiler that this field may be null
Apparently I can't reproduce the error since I don't have access to your firestore documents, but I am pretty certain that the problem occurs in
...
for (var element in query.docs) {
retVal.add(
Video.fromSnap(element),
);
}
...
where you attempt to translate element JSON into a Video. In fromSnap, before returning, try printing out snapshot. You should see that it is missing one or more attributes (which is why it was complaining about having a Null when it should be a String), or have some incorrect attributes.

Flutter throws FormatException error when JSON string is inputted correctly

Flutter is giving me this error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected end of input (at character 88586)
[ ] E/flutter ( 5286): ...820457458, -0.09168463200330734, 0.9341723918914795, 0.9910492897033691]}",
This is how I am inflating the list (that is later written to a JSON file):
for(var i = 0 ; i <=32; ++i) {
String entry = '{contents: ['
'${contentList.content[i].x.toString()}, '
'${contentList.content[i].y.toString()}, '
'${contentList.content[i].z.toString()}, '
'${contentList.content[i].visibility.toString()}, '
'${contentList.content[i].presence.toString()}]}';
content_collector.add(entry);
}
content_collector is then passed to this function to write to a JSON file:
Future<File> saveToJSONFile(List<String> contents_list, String filename) async {
String encodedContents = jsonEncode(contents_list);
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path + '/' + filename;
return await File(appDocPath).writeAsString(encodedContents);
}
and I have this function to read the generated JSON file:
void readJSON(String path) async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path + '/' + path;
String response = await File(appDocPath).readAsString();
final data = await json.decode(response.toString());
}
So really, it is the readJSON function that throws this error.
This part is not valid JSON
{contents: [
it should be
{"contents": [
Most likely the other parts needs to be surrounded with " as well
As #julemand101 mentioned, this is not a proper approach, but also looking at the code, the string you are crating, is not being concatenated either. Try this:
String entry = "{'contents': [
'${contentList.content[i].x.toString()}',
'${contentList.content[i].y.toString()}',
'${contentList.content[i].z.toString()}',
'${contentList.content[i].visibility.toString()}',
'${contentList.content[i].presence.toString()}'
]}";

Why am I getting an error when trying to call a method with flutter chopper and built value?

I'm getting The below ERROR,I believe it's because of null safety, this means that no data has been received or getSignedInUser() method is incorrect or class BuiltValueConverter is the cause.
(I tested the token with Postman and retrieved the data)
E/flutter (21792): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: Unhandled error Null check operator used on a
null value occurred in Instance of 'AuthBloc'. E/flutter (21792): #0
BuiltValueConverter._deserialize
package:todo_list_app/…/auth/built_value_converter.dart:51 E/flutter
(21792): #1 BuiltValueConverter._convertToCustomObject
package:todo_list_app/…/auth/built_value_converter.dart:36 E/flutter
(21792): #2 BuiltValueConverter.convertResponse
package:todo_list_app/…/auth/built_value_converter.dart:25
I'm using chopper with built_value Pubs. i'm trying to convert the coming json to object.
Example:
{
"userName": "Jack",
"email": "jack2066#gmail.com",
"userRole": "USER",
"created_at": "2021-07-03T16:49:56.774Z",
"updated_at": "2021-07-03T16:49:56.774Z" }
the below code where the error start also explained in this Tutorial Converters & Built Value Integration
import 'package:built_collection/built_collection.dart';
import 'package:chopper/chopper.dart';
import 'package:todo_list_app/infrastructure/remote/auth/models/serializers.dart';
class BuiltValueConverter extends JsonConverter {
#override
Request convertRequest(Request request) {
return super.convertRequest(
request.copyWith(
body: serializers.serializeWith(
serializers.serializerForType(request.body.runtimeType)!,
request.body,
),
),
);
}
#override
Response<BodyType> convertResponse<BodyType, SingleItemType>(
Response response,
) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody =
_convertToCustomObject<SingleItemType>(dynamicResponse.body);//
return dynamicResponse.copyWith<BodyType>(body: customBody);
}
dynamic _convertToCustomObject<SingleItemType>(dynamic element) {
if (element is SingleItemType) return element;
if (element is List)
return _deserializeListOf<SingleItemType>(element);
else
return _deserialize<SingleItemType>(element);
}
BuiltList<SingleItemType> _deserializeListOf<SingleItemType>(
List dynamicList,
) {
// Make a BuiltList holding individual custom objects
return BuiltList<SingleItemType>(
dynamicList.map((element) => _deserialize<SingleItemType>(element)),
);
}
SingleItemType _deserialize<SingleItemType>(Map<String, dynamic> value,) {
// We have a type parameter for the BuiltValue type, which should be returned after deserialization.
return serializers.deserializeWith(
serializers.serializerForType(SingleItemType)!, // Error Start
value,
);
}
}
Here is my Chopper service code, getSignedInUser throw the error.
I don't know if the implementation of the getSignedInUser method is correct or not.
import 'package:chopper/chopper.dart';
import 'package:injectable/injectable.dart';
import 'package:todo_list_app/infrastructure/remote/auth/built_value_converter.dart';
import 'package:todo_list_app/infrastructure/remote/auth/models/auth_built_model.dart';
import 'package:todo_list_app/infrastructure/remote/core/constants.dart';
part 'auth_service.chopper.dart';
#singleton
#ChopperApi()
abstract class AuthService extends ChopperService {
#factoryMethod
static AuthService create() {
final client = ChopperClient(
baseUrl: AUTH_BASE_URL_External,
services: [
_$AuthService(),
],
converter: BuiltValueConverter(),
errorConverter: JsonConverter(),
interceptors: [
HttpLoggingInterceptor()
],
);
return _$AuthService(client);
}
#Post(path: '/signup')
Future<Response> signUp(#Body() RegisterRequestModel body);
#Post(path: '/signin')
Future<Response<LoginResponseModel>> singIn(#Body() LoginRequestModel body);
//headers: {AUTH_HEADER:BEARER+'authValue'}
#Get(path: '/auth', )//authValue='Bearer Token'
Future<Response<UserResponseModel>> getSignedInUser(#Header("Authorization") String authValue);//error Unhandled error Null check operator used on a null value
}
Any idea how to solve this Error?
also Is there a good documentation for Chopper or alternative pub with a good documentation?
Thanks
I think you are missing values in your "serielizers.dart" file it should be as followed :
#SerializersFor(const[RegisterRequestModel,LoginRequestModel,UserResponseModel])
final Serializers serializers =
(_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build();
Yeah, as you said it's because of null safety. Your _deserialize returns a non-null value whereas the serializers.deserializeWith can return a null value. Either you can change the return type to be nullable, or handle the null case for serializers.deserializeWith. If you want you can use the below BuiltValueConverter. It is from the example which they have given which is generic, with minor changes.
import 'package:built_collection/built_collection.dart';
import 'package:built_value/serializer.dart';
import 'package:chopper/chopper.dart';
import 'package:graphical_representation/app/serializers.dart';
class BuiltValueConverter extends JsonConverter {
T? _deserialize<T>(dynamic value) => serializers.deserializeWith<T>(
(serializers.serializerForType(T) as Serializer<T>),
value,
);
BuiltList<T> _deserializeListOf<T>(Iterable value) => BuiltList(
value.map((value) => _deserialize<T>(value)).toList(growable: false),
);
dynamic _decode<T>(entity) {
/// handle case when we want to access to Map<String, dynamic> directly
/// getResource or getMapResource
/// Avoid dynamic or unconverted value, this could lead to several issues
if (entity is T) return entity;
try {
if (entity is List) return _deserializeListOf<T>(entity);
return _deserialize<T>(entity);
} catch (e) {
print(e);
return null;
}
}
#override
Response<ResultType> convertResponse<ResultType, Item>(Response response) {
// use [JsonConverter] to decode json
final jsonRes = super.convertResponse(response);
final body = _decode<Item>(jsonRes.body);
return jsonRes.copyWith<ResultType>(body: body);
}
#override
Request convertRequest(Request request) => super.convertRequest(
request.copyWith(
body: serializers.serialize(request.body),
),
);
}

Is directions Api not accepting negative values for coordinates ? Flutter

I'm sending a direction request to an API and I'm facing this problem.
With coordinates as flutter: start location is :latitude 37.33101308, longitude -122.03065487 and end location is :latitude 37.33097983, longitude -122.03063943 the - symbol creates a problem.
When sending the resulting request
http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=37.33101308&flon=-122.03065487&tlat=37.33097983&tlon=-122.03063943&geometry=1&instructions=1&lang=it
I get an error that I'm not yet able to understand:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
FormatException: Unexpected character (at character 1) ^
0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1261:9)
2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:926:22)
3 _parseJson (dart:convert-patch/convert_patch.dart:31:10)
4 JsonDecoder.convert (dart:convert/json.dart:495:36)
5 JsonCodec.decode (dart:convert/json.dart:153:41)
6 jsonDecode (dart:convert/json.dart:96:10)
7 DirectionsRepository.postRequest (package:fixit_cloud_biking/directions/directions_repository.dart:39:26)
8 DirectionsBloc.getDirections (package:fixit_cloud_biking/directions/directions_bloc.dart:46:12)
9 _AsyncStarStreamController.runBody (dart:async-patch/async_patch.dart:155:5)
10 _rootRun (dart:async/zone.dart:1122:3<…>
Is it because of a json formatting issue or does it means that www.yournavigation.org/api doesn't accept negative coordinates values ?
This error doesn't happen if the sent request has positive coordinates as this
'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it'
Just for testing I tried just making them positive coordinates with .abs(). but of course the results is a wrong location on the map.
Is there another coordinate system that has all positive values?
Thank you very much for your help.
This is the class I'm sending the request from:
import 'package:http/http.dart';
import 'package:latlong/latlong.dart';
import 'dart:convert' as convert;
import 'dart:math';
class DirectionsRepository {
Future<List<LatLng>> postRequest(LatLng start, LatLng end) async {
print('postRequest() called');
print(
'start location is :latitude ${start.latitude}, longitude ${start.longitude}');
print(
'end location is :latitude ${end.latitude}, longitude ${end.longitude}');
// NORMAL NEGATIVE LONGITUDE THROWS = API ERROR:
// format error [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
String flat = (start.latitude).toString();
String flon = (start.longitude).toString();
String tlat = (end.latitude).toString();
String tlon = (end.longitude).toString();
// ALL POSITIVE VALUES DON'T THROW AN ERROR BUT IS WRONG PLACE
// String flat = (start.latitude).abs().toString();
// String flon = (start.longitude).abs().toString();
// String tlat = (end.latitude).abs().toString();
// String tlon = (end.longitude).abs().toString();
final request =
'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=$flat&flon=$flon&tlat=$tlat&tlon=$tlon&geometry=1&instructions=1&lang=it';
print('final request is $request');
// working properly
// final request =
// 'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';
// Await the http get response, then decode the json-formatted response.
var response = await get(request);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
print('${jsonResponse.runtimeType} : $jsonResponse');
List<dynamic> coordinates = jsonResponse['coordinates'];
print('coordinates are : $coordinates');
print('coordinates are: ${coordinates.length}');
Map<String, dynamic> properties = jsonResponse['properties'];
// print('properties are $properties');
String distance = properties['distance'];
print('Route is $distance Km long.');
String instructions = properties['description'];
print('instructions are $instructions');
List<LatLng> suggestedRoute = [];
for (int i = 0; i < (coordinates.length); i++) {
dynamic coordinate = coordinates[i];
LatLng position = LatLng(coordinate[1], coordinate[0]);
suggestedRoute.add(position);
print('position is $position');
print(i);
}
print('postRequest() suggestedRoute is $suggestedRoute');
return suggestedRoute;
} else {
print(
'postRequest() Request failed with status: ${response.statusCode}.');
}
}
}
After a few tries, I've nailed down the problem to be a direction API server problem. So, request is fine, but method's json decoding just fails because gets a 242 response status code which passes the check but fails as the response body does not match what's handled in the method.