Convert dart http.get request to match the constructor - dart

I have the following code in dart:
final uri = Uri.https('api.server', '/json/pages', queryParams);
final response =
await http.get(uri, headers: {"Accept": "application/json"});
However the app is throwing an exception citing:
type '_InternalLinkedHashMap<String, Object>' is not a subtype of type 'Map<String, String>'
How do I convert the response to a valid type expected by http.get's constructor or is there another workaround?
Thanks

You may need to fix the queryParams
Map<String, String> stringParams = {};
// or
var stringParams = <String, String>{};
Look at here

Related

Dart define generic function

I used the following code to define a function type
typedef DownloadCallback = Future<StreamedResponse> Function<T>(
BuildContext context,
T fileIdentifier,
);
And created a function that is similar to the type
Future<StreamedResponse> publicFileDownloader(
BuildContext context,
String url,
) {
final request = Request('GET', Uri.parse(url));
return Client().send(request);
}
But I have the following error
The argument type 'Future Function(BuildContext, String)' can't be assigned to the parameter type 'Future Function(BuildContext, T)'.
How can I fix the error without using dynamic type?
This is another case where trying to specify a type ends up making Dart more confused. The problem is that the following:
final DownloadCallback downloader = publicFileDownloader;
Actually means:
final DownloadCallback<dynamic> downloader = publicFileDownloader;
Therefore, what you should do is the following:
final DownloadCallback<String> downloader = publicFileDownloader;
Next problem is wrong use of generic when you are declaring your typedef. What you actually want are properly the following:
typedef DownloadCallback<T> = Future<StreamedResponse> Function(
BuildContext context,
T fileIdentifier,
);
So the complete code would be:
typedef DownloadCallback<T> = Future<StreamedResponse> Function(
BuildContext context,
T fileIdentifier,
);
Future<StreamedResponse> publicFileDownloader(
BuildContext context,
String url,
) {
final request = Request('GET', Uri.parse(url));
return Client().send(request);
}
final DownloadCallback<String> downloader = publicFileDownloader;

Did flutter methodchannel support return a List<Map<String, String>> value?

as title said, I wrote an plugin that return a List> value, but I can't get the result from my plugin, and there was no error.
Is any thing wrong?
How to implement the customized type returned by MethodChannel?
DO NOT:
List<Map<String, dynamic>> resp = await _channel.invokeMethod('returnAMapList');
DO:
List<Map> = await _channel.invokeMethod('returnAMapList');

How to resolve type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>

I am trying to fetch user data but getting below error while doing so:
Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>
I looked at various solutions for similar issue and changed my code accordingly (ex: used <String, dynamic> instead of <dynamic, dynamic>, but still am seeing this error.
Model snippet:
// Returns a Pro created from JSON
factory Pro.fromJson(Map<String, dynamic> json) {
Pro pro = Pro();
pro.uid = json['uid'];
pro.email = json['email'];
And fetching this data as below and calling this method in initState():
Future<Pro> _getPro() async {
await userDatabaseReference.once().then((DataSnapshot snapshot) {
Map<String, dynamic> values = snapshot.value;
values["uid"] = snapshot.key;
print(snapshot.key);
Pro fetchedUser = Pro.fromJson(values);
setState(() {
this.pro = fetchedUser;
});
});
}
If I use Map<String, dynamic> values, then I get error at same line and if I use Map<dynamic, dynamic> values, then I get error at:
Pro fetchedUser = Pro.fromJson(values)
Since, Pro.fromJson(values) has parameter type Map<String, dynamic> which is the same parameter type I used to declare values but still not sure why its throwing the error.
Please try as below where we convert values first into Map.from() and then use that with fromJson method of Pro model:
Future<Pro> _getPro() async {
await userDatabaseReference.once().then((DataSnapshot snapshot) {
Map<String, dynamic> values = snapshot.value;
values["uid"] = snapshot.key;
print(snapshot.key);
final mapJsonCategory = Map<String, dynamic>.from(values);
Pro fetchedUser = Pro.fromJson(mapJsonCategory);
setState(() {
this.pro = fetchedUser;
});
});
}

Cast json in to Map<String,Map<String,String>> Format

I need to convert the json string to nested Map and access the same.
Following Json String is in form of Map given below
Map<String,Map<String,String>>
{"0":{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"},"1":{"1551948649643":"0","1551948733576":"0","1551948601167":"0","1551948592816":"0","1551948699297":"0","1551874822043":"2","1551948681513":"0","1551948531568":"0","1551948577374":"0","1551948719758":"0","1552370125650":"0","1551948549863":"0","1551948564519":"0","1551948631000":"0","1551953956716":"0"},"2":{"1551875011432":"0","1551875020618":"0","1551874991952":"0","1551875091300":"0","1551875073622":"0","1551875032851":"0","1551874827691":"0","1551948658122":"0","1551874846523":"0","null":"0","1552545417127":"0","1551875083856":"0","1551874929076":"0","1552545972738":"0"},"3":{"1552651031695":"0"},"4":{"1551875144268":"0","1551875157028":"0","1551875115211":"0","1551875124660":"0"}}
Getting following error while trying using my code:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast
Map offlineExeStatus = jsonDecode(prefs.getString("offlineExeStatus"));
Map<String,Map<String,String>> exeStatusFinalJson = new Map();
exeStatusFinalJson = offlineExeStatus.cast<String,Map<String,String>();
Need to cast the given json in "exeStatusFinalJson" Map and access like:
exeStatusFinalJson["0"] should give the output like:
{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"}
Try to declare your map as Map<String, dynamic> rather than Map<String, Map<String, String>>.
Finally figured out the way to do it!
Map offlineExeStatus = jsonDecode(prefs.getString("onlineExeStatus"));
Map<String, dynamic> exeStatusJson = new Map();
Map<String, Map<String, String>> exeStatusFinalJson = new Map();
List<String> mapKeyExe = new List();
mapKeyExe = offlineExeStatus.keys.cast<String>().toList();
exeStatusJson = offlineExeStatus.cast<String, dynamic>();
for (int i = 0; i < mapKeyExe.length; i++) {
Map<String, String> exeStatusInsideJson = new Map();
exeStatusInsideJson = offlineExeStatus[mapKeyExe[i].toString()]
.cast<String, String>();
exeStatusFinalJson[i.toString()] = exeStatusInsideJson;
print(exeStatusFinalJson);
}

flutter dart error when installing google api calendar

I will display a list of events from Google Calendar.
I followed the example already in the following link : How to use Google API in flutter?
and my script is as follows :
import 'package:http/http.dart' as http;
assumed I was logged in.
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: <String>[
'email',
'https://www.googleapis.com/auth/contacts.readonly',
'https://www.googleapis.com/auth/calendar'
],
);'
class GoogleHttpClient extends http.BaseClient {
Map<String, String> _headers;
GoogleHttpClient(this._headers) : super();
#override
Future<http.StreamedResponse> send(http.BaseRequest request) =>
super.send(request..headers.addAll(_headers)); //have error 'the method 'send' is always abstract in the supertype'
#override
Future<http.Response> head(Object url, {Map<String, String> headers}) =>
super.head(url, headers: headers..addAll(_headers));
}
void getCalendarEvents() async {
final authHeaders = _googleSignIn.currentUser.authHeaders;
final httpClient = new GoogleHttpClient(authHeaders); //have error "The argument type 'Future<Map<String, String>>' can't be assigned to the parameter type 'Map<String, String>'"
var calendar = new Calendar.CalendarApi(new http.Client());
var calEvents = calendar.events.list("primary");
calEvents.then((Calendar.Events events) {
events.items.forEach((Calendar.Event event) {print(event.summary);});
});
}
the above script cannot run because of an error.
the method 'send' is always abstract in the supertype
can someone help me?
If your code is based on How to use Google API in flutter? you'll see that I have a #override Future<StreamedResponse> send(...) in my code.
GoogleHttpClient extends abstract class IOClient that is missing an implementation of send, so the concrete subclass needs to implement it.
That's what the error message is about.
Replace StreamedResponse with IOStreamedResponse
add IOClient library
replace class GoogleHttpClient extends IOClient with class GoogleHttpClient extends http.BaseClient
1 This is error
//have error "The argument type 'Future<Map<String, String>>' can't be assigned to the parameter type 'Map<String, String>'"
fixed: add await ahead
Like below:
final authHeaders = await _googleSignIn.currentUser.authHeaders;
2: Change like below
var calendar = new Calendar.CalendarApi(new http.Client());
to
var calendar = new Calendar.CalendarApi(httpClient);
======> Final:
void getCalendarEvents() async {
final authHeaders = await _googleSignIn.currentUser.authHeaders;
final httpClient = new GoogleHttpClient(authHeaders);
var calendar = new Calendar.CalendarApi(httpClient);
var calEvents = calendar.events.list("primary");
calEvents.then((Calendar.Events events) {
events.items.forEach((Calendar.Event event) {print(event.summary);});
});
}
It worked for me.

Resources