I can not access values on map in dart - dart

I have the following code where I work with a map generated from the json.decode() function:
for (var i = 0; i < data[0]["conversation"].length; i++) {
print(data[0]["conversation"][i]["conversationID"]);
print(data[0]["conversation"][i]["startDate"]);
print(data[0]["conversation"][i]["lastActivity"]);
print(data[0]["conversation"][i]["messageCount"]);
for (var j = 0; j < int.parse( data[0]["conversation"][i]["messageCount"] ); j++) {
print(data[0]["conversation"][i]["messages"]["message"][j]);
}
print("\n");
}
in the most external "for" everything works well, the problem is in the internal "for" where I receive an error when trying to access a value:
for (var j = 0; j < int.parse( data[0]["conversation"][i]["messageCount"] ); j++) {
print(data[0]["conversation"][i]["messages"]["message"][j]["body"]);
}
This is the error:
E/flutter ( 1650): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter ( 1650): NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 1650): Receiver: null
E/flutter ( 1650): Tried calling: []("body")
E/flutter ( 1650): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 1650): #1 ChatScreenState.obtenerMensajesArchivados (file:///home/fenrir/Documents/api/lib/chat/chat_page.dart:115:67)
E/flutter ( 1650): <asynchronous suspension>
E/flutter ( 1650): #2 ChatScreenState.initState.<anonymous closure> (file:///home/fenrir/Documents/api/lib/chat/chat_page.dart:157:7)
E/flutter ( 1650): #3 _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter ( 1650): #4 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter ( 1650): #5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter ( 1650): #6 Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter ( 1650): #7 Future._complete (dart:async/future_impl.dart:476:7)
E/flutter ( 1650): #8 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 1650): #9 _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async/runtime/libasync_patch.dart:33:20)
E/flutter ( 1650): #10 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 1650): #11 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
Example of
data[0]["conversation"][i]["messages"]["message"][j] :
{conversationID: 230, from: 123#localhost, to: 456#localhost, sentDate: 2018-10-18T12:48:05.039Z, body: aloha, roomEvent: false}
print(data[0]["conversation"][i]["messages"]["message"][j].runtimeType); return:
_InternalLinkedHashMap<String, dynamic>
I do not know what the error may be since in the first "for" it works for me but in the second one it does not :(

The error is using ["body"] on null, so for some j value, data[0]["conversation"][i]["messages"]["message"][j] must be null.
Try finding the i and j that makes this throw, then check that the "message" listthe expected number of elements, and that none of them are null.

Related

How to handle http errors (FormatException: Unexpected end of input (at character 1))

How to handle this kind of error message? Why is it coming? Is that issue? I called below method every 10 seconds.
checkQuick(String url, String token) async {
result =
(await HelperDatabase1().displayGetUserPreference()).elementAt(0)?.data;
final response = await http.get(
'$url/nativeapi/v1.0/User/GetUserPreference',
headers: {'Authorization': 'Bearer $token'},
);
final jsonResponse = json.decode(response.body);
GetUserPreference model = GetUserPreference.fromJson(jsonResponse);
var data = GetUserPreference(data: model.data);
//result = data.data;
if (result != data.data) {
// await HelperDatabase1().updateGetUserPreference(1, data.data);
print('inside');
await HelperDatabase1().deleteGetUserPreference();
await HelperDatabase1().storeGetUserPreference(url, token);
}
}
below error message coming some times.
E/flutter ( 7148): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
E/flutter ( 7148):
E/flutter ( 7148): ^
E/flutter ( 7148):
E/flutter ( 7148): #0 _ChunkedJsonParser.fail
(dart:convert-patch/convert_patch.dart:1392:5) E/flutter ( 7148): #1
_ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:510:7) E/flutter ( 7148): #2 _parseJson
(dart:convert-patch/convert_patch.dart:30:10) E/flutter ( 7148): #3
JsonDecoder.convert (dart:convert/json.dart:493:36) E/flutter ( 7148):
4 JsonCodec.decode (dart:convert/json.dart:151:41) E/flutter ( 7148): #5 _ListPageState.checkQuick
(package:reborn_next_job02/ui/AssetRegisters.dart:153:31) E/flutter (
7148): E/flutter ( 7148): #6
_ListPageState.initState. (package:reborn_next_job02/ui/AssetRegisters.dart:47:7) E/flutter (
7148): #7 _rootRunUnary (dart:async/zone.dart:1132:38) E/flutter
( 7148): #8 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter ( 7148): #9 _CustomZone.runUnaryGuarded
(dart:async/zone.dart:931:7) E/flutter ( 7148): #10
_CustomZone.bindUnaryCallbackGuarded. (dart:async/zone.dart:968:26) E/flutter ( 7148): #11 _rootRunUnary
(dart:async/zone.dart:1136:13) E/flutter ( 7148): #12
_CustomZone.runUnary (dart:async/zone.dart:1029:19) E/flutter ( 7148): #13 _CustomZone.bindUnaryCallback. (dart:async/zone.dart:952:26) E/flutter ( 7148): #14
_Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19) E/flutter ( 7148): #15 _Timer._handleMessage
(dart:isolate-patch/timer_impl.dart:416:5) E/flutter ( 7148): #16
_RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
Check the response.statusCode before if it is 200.
Looks like the response.body is empty because the call failed, so json.decode(response.body) throws an exception.
It might be from the server end. I used to work with a ruby backend that requires '.json' added at the end of url path. Give that a try.

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

UPDATE: Thanks to #Rjulcaa answer My map is now a List, however the List wasn't displayed on the UI. I turns that I needed to handle the future with a FutureBuilder, so in case anyone faces this problem remember to add a FutureBuilder to the body of your UI and on the builder return the widget you want to be displayed.
I'm making a todo list tutorial, I'm trying to add the feature of encoding on a JSON my todoList the save it on a sharedPreferences, and when I start the app retrieve it on the screen
This is my TODO class
class Todo {
Todo ({this.title,this.isDone = false});
String title;
bool isDone;
//Decode method to convert a Json String into a Dynamic object
Todo.fromJson(Map <String, dynamic> json)
: title = json ["title"],
isDone = json ["isDone"];
Map <String,dynamic> toJson() =>
{
"title" : title,
"isDone" : isDone
};
}
This is my screen
class _TodoListScreenState extends State<TodoListScreen> {
List<Todo> todos = [];
#override
void initState() {
super.initState();
_getTodoFromSharedPreferences();
}
//updates the state of the checkbox and reflects it on the UI
_toggleTodo(Todo todo, bool isChecked) {
setState(() {
todo.isDone = isChecked;
});
}
_addTodo() async {
final todo = await showDialog<Todo>(
context: context,
builder:(BuildContext context) { // <- Here you draw the Dialog
return NewTodoDialog();
},
);
if (todo != null) {
setState(() {
todos.add(todo);
_saveTodo(todos);
print(todos.length);
});
}
}
_saveTodo(List<Todo> todo) async{
final String newTodo = jsonEncode(todo);
setSharedPreferences(newTodo);
}
_getTodoFromSharedPreferences () async {
final prefs = await SharedPreferences.getInstance();
final savedTodo = prefs.getString("savedTodo");
if (savedTodo == null) {return null;} else {
Map MapofTodos = jsonDecode(savedTodo);
for (var i = 0; i < MapofTodos.length; ++i) {
var o = MapofTodos[i];
setState(() {
Todo todo = Todo.fromJson(o);
todos.add(todo);
});
}
}
}
setSharedPreferences (String newTodo ) async{
final prefs = await SharedPreferences.getInstance();
await prefs.setString("savedTodo", newTodo );
print(newTodo);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor:Colors.deepPurple[900] ,
title: Text('Todo List')),
body: TodoList(
todos: todos,
onTodoToggle: _toggleTodo,
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.purpleAccent[700],
child: Icon(Icons.add),
onPressed: _addTodo,
),
);
}
}
when I run the app i get this error
E/flutter ( 7476): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)]
Unhandled Exception: type 'List<dynamic>' is not a subtype of type
'Map<dynamic, dynamic>'
E/flutter ( 7476): #0
_TodoListScreenState._getTodoFromSharedPreferences
(package:flutter_todo/UI/todo_list_screen.dart:70:11)
E/flutter ( 7476): <asynchronous suspension>
E/flutter ( 7476): #1 _TodoListScreenState.initState
(package:flutter_todo/UI/todo_list_screen.dart:29:6)
E/flutter ( 7476): #2 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3851:58)
E/flutter ( 7476): #3 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #4 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #5 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #6 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #7 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #8 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #9 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #10 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #11 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #12 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #13 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #14 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #15 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #16 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #17 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #18 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #19 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #20 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #21 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #22 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #23 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #24 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #25 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #26 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #27 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #28 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #29 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #30 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #31 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #32 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #33 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #34 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #35 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #36 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #37 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #38 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #39 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #40 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #41 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #42 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #43 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #44 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #45 Ele
I tried to change the List to a Map but didn't succeed
I have succeeded on everything except returning the widget to the screen.
Help me, please :c
I faced this problem before because I wanted to save an array object in shared preferences. You can try this.
//Save you array object as an array of Strings in Shared Preferences
void _saveTodo(List<Todo> todo) async{
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setStringList("savedTodo", _mapTodoData(todo));
}
}
Transform the JSON into an array of Strings
List<String> _mapTodoData(List<dynamic> todos) async{
try {
var res = todos.map((v) => json.encode(v)).toList();
return res;
} catch (err) {
// Just in case
return [];
}
}
}
if you want to get and transform the data in a List of Todo objects
void loadData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final todoArray = _decodeTodoData(sharedPreferences.getStringList("savedTodo"))
//This is your array :) -> todoArray
}
List<Todo> _decodeTodoData(List<String> todos) {
try {
//Transforming List<String> to Json
var result = todos.map((v) => json.decode(v)).toList();
//Transforming the Json into Array<Todo>
var todObjects = result.map((v) => Todo.fromJson(v)).toList();
return todObjects;
} catch (error) {
return [];
}
}
}
This worked for me, I really struggled with this problem.
I Hope this works for you too.
Here you're trying to iterate over a Map which is not possible because only possible Iterables objects are Set,List and Queue.
// Map MapofTodos = jsonDecode(savedTodo);
//Try to debug it first first and see what type it's returning
print(jsonDecode(savedTodo).runtimeType);
I faced the same issue during app development in dart. The issue with json decoding techniques or might be json conversion.
I have done work around for creating the method as passing the parameter as
getCardData(data[0]["cardContent"][0]["cardData"] as List),
List<String> getCardData(data) {
List<String> _cardInfo = [];
for (int i = 0; i < data.length; i++) {
_cardInfo.add(data[i] as String);
}
return _cardInfo;
}

Flutter Unexpected end of input (at character 1)

How to fix this error
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception:
FormatException: Unexpected end of input (at character 1) E/flutter
(11841): E/flutter (11841): ^ E/flutter (11841): E/flutter (11841):
0 _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1357:5) E/flutter (11841):
1 _ChunkedJsonParser.close (dart:convert/runtime/libconvert_patch.dart:510:7) E/flutter (11841):
2 _parseJson (dart:convert/runtime/libconvert_patch.dart:30:10) E/flutter (11841): #3 JsonDecoder.convert
(dart:convert/json.dart:491:36) E/flutter (11841): #4
JsonCodec.decode (dart:convert/json.dart:149:41) E/flutter (11841): #5
storeSync (package:reborn_next_job02/Cache/syncApi.dart:19:29)
E/flutter (11841): E/flutter (11841): #6
_ListPageState.initState. (package:reborn_next_job02/ui/AssetRegisters.dart:54:9) E/flutter
(11841): #7 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (11841): #8 _CustomZone.runUnary
(dart:async/zone.dart:1029:19) E/flutter (11841): #9
_CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7) E/flutter (11841): #10 _CustomZone.bindUnaryCallbackGuarded. (dart:async/zone.dart:968:26) E/flutter (11841): #11
_rootRunUnary (dart:async/zone.dart:1136:13) E/flutter (11841): #12 _CustomZone.runUnary (dart:async/zone.dart:1029:19) E/flutter (11841): #13 _CustomZone.bindUnaryCallback. (dart:async/zone.dart:952:26) E/flutter (11841): #14
_Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19) E/flutter (11841): #15 _Timer._handleMessage
(dart:isolate/runtime/libtimer_impl.dart:416:5) E/flutter (11841): #16
_RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
syncApi.dart
storeSync(String url, String token) async {
final response = await http.get(
'$url/v1.0/SyncDataTable',
headers: {'Authorization': 'Bearer $token'},
);
final jsonResponse = json.decode(response.body);
SyncModel model = SyncModel.fromJson(jsonResponse);
int length = model.data.length;
HelperSync().display()).elementAt(i)?.syn_ChangeSequence,
for (int i = 0; i < length; i++) {
if ((await HelperSync().display()).elementAt(i)?.syn_TableName == model.data[i].syn_TableName) {
if ((await HelperSync().display()).elementAt(i)?.syn_ChangeSequence != model.data[i].syn_ChangeSequence) {
switch (i) {
case 21:
{
await HelperDatabase1().storeRegister(url, token);
}
break;
}
}
}
}
}
"FormatException" errors are usually caused by encoding issues. To solve this issue, you can cast response.body as a HashMap to look for the resulting Map<String, dynamic> before decoding.
// final jsonResponse = json.decode(response.body); // we can skip
SyncModel model = SyncModel.fromJson(response.body as Map<String, dynamic>>);

type 'int' is not a subtype of type 'String' in type cast when sending a post request

I have a weird error showing up when sending a post request.
// this map is passed to a function
final Map<String, dynamic> activityData = {
"userId": 1,
"name": activityName.text,
"description": activityDescription.text,
"startAt": activityStartAt.text,
"endsAt": activityEndAt.text,
"lat": _latitude,
"long": _longitude,
"category": 2,
"status": "pending"
};
// this code bellow is inside a async function
final http.Response response =
await http.post(Uri.encodeFull(url), body: activityData);
this is the error :
E/flutter (32582): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (32582): type 'int' is not a subtype of type 'String' in type cast
E/flutter (32582): #0 CastMap.forEach.<anonymous closure> (dart:_internal/cast.dart:286:25)
E/flutter (32582): #1 __InternalLinkedHashMap&_HashVMBase&MapMixin&_LinkedHashMapMixin.forEach (dart:collection/runtime/libcompact_hash.dart:370:8)
E/flutter (32582): #2 CastMap.forEach (dart:_internal/cast.dart:285:13)
E/flutter (32582): #3 mapToQuery (package:http/src/utils.dart:17:7)
E/flutter (32582): #4 Request.bodyFields= (package:http/src/request.dart:128:17)
E/flutter (32582): #5 BaseClient._sendUnstreamed (package:http/src/base_client.dart:163:17)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #6 BaseClient.post (package:http/src/base_client.dart:54:7)
E/flutter (32582): #7 post.<anonymous closure> (package:http/http.dart:70:16)
E/flutter (32582): #8 _withClient (package:http/http.dart:166:20)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #9 post (package:http/http.dart:69:5)
E/flutter (32582): #10 _MainModel&Model&ConnectedModel&UsersModel&ActivitiesModel.createActivity (package:activmap/scoped-models/connectedModel.dart:62:15)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #11 _NewActivityState.save (package:activmap/pages/newActivity.dart:271:11)
E/flutter (32582): <asynchronous suspension>
E/flutter (32582): #12 _NewActivityState.build.<anonymous closure> (package:activmap/pages/newActivity.dart:248:30)
E/flutter (32582): #13 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter (32582): #14 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter (32582): #15 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter (32582): #16 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter (32582): #17 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
E/flutter (32582): #18 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
E/flutter (32582): #19 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
E/flutter (32582): #20 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
E/flutter (32582): #21 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19)
E/flutter (32582): #22 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter (32582): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter (32582): #24 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter (32582): #25 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter (32582): #26 _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter (32582): #27 _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
I have it working fine on another screen the only difference that I can see is that the one that's working only have Strings, while this one has int, double and String.
To fix your issue you just have to encode the data before sending.
import 'dart:convert';
...
final http.Response response =
await http.post(Uri.encodeFull(url), body: json.encode(activityData));
If your API doesn't support JSON, then you just have to pass all your data as String.
final Map<String, dynamic> activityData = {
"user_id": "1",
"name": activityName.text,
"description": activityDescription.text,
"startAt": activityStartAt.text,
"endsAt": activityEndAt.text,
"lat": "$_latitude",
"long": "$_longitude",
"category": "2",
"status": "pending"
};
final http.Response response =
await http.post(Uri.encodeFull(url), body: activityData);
Step 1: use "content-type": "application/json" in header
Step 2: encode your body like
jsonEncode( {"param1": 10, "param2":20,"param3": "abc","param4": true})
Example Code Like
headers: {
"content-type": "application/json",
},
body:jsonEncode( {
"qualificationId": 10,
"year":2001,
"instituteName": "example",
"isActive": true
})
Check out requests - a flutter library to make http requests (inspired by python requests module)
Posting application/x-www-form-urlencoded:
var r = await Requests.post(
"https://reqres.in/api/users", body: {
"userId": 10,
"id": 91,
"title": "aut amet sed",
},
bodyEncoding: RequestBodyEncoding.FormURLEncoded);
r.raiseForStatus();
dynamic json = r.json();
print(json['id']);
Posting application/json:
var r = await Requests.post("https://reqres.in/api/users", json: {
"userId": 10,
"id": 91,
"title": "aut amet sed",
"body": "libero voluptate eveniet aperiam sed\nsunt placeat suscipit molestias\nsimilique fugit nam natus\nexpedita consequatur consequatur dolores quia eos et placeat",
});
r.raiseForStatus();
dynamic body = r.json();
print(json['id']);
For flutter version 2.0.6 and http dart package ^0.13.3, you will need to parse the URL and encode your payload using json.encode from the dart:convert library like so:
import 'package:http/http.dart' as http;
import 'dart:convert';
-------
var url = Uri.parse('http://10.0.2.2:8000/api/test');
var response = await http.post(url, body: json.encode({ 'name': 'mac', 'password': 'test' }));
print(response.body);

type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic> Flutter

I am using Event Channels in Flutter to return beacon data from Native SDK to Flutter. This was working fine until a recent Flutter upgrade.Now, I am getting the following error.
type '(PlatformException) => void' is not a subtype of type '(Object) => FutureOr<dynamic>
with the following stack trace:
#0 _registerErrorHandler (dart:async/async_error.dart:22:60)
#1 _BufferingStreamSubscription.onError (dart:async/stream_impl.dart:146:16)
#2 new _BufferingStreamSubscription (dart:async/stream_impl.dart:113:10)
#3 new _ControllerSubscription (dart:async/stream_controller.dart)
#4 new _BroadcastSubscription (dart:async/broadcast_stream_controller.dart)
#5 _BroadcastStreamController._subscribe (dart:async/broadcast_stream_controller.dart:212:46)
#6 _ControllerStream._createSubscription (dart:async/stream_controller.dart:817:19)
#7 _StreamImpl.listen (dart:async/stream_impl.dart:466:9)
#8 _MyHomePageState.initPlatformState.<anonymous closure>.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:95:43)
#9 _RootZone.runUnary (dart:async/zone.dart:1381:54)
#10 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#12 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#13 Future._complete (dart:async/future_impl.dart:467:7)
#14 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#15 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart)
<asynchronous suspension>
#16 _MyHomePageState.initPlatformState.<anonymous closure> (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:89:24)
<asynchronous suspension>
#17 _RootZone.runUnary (dart:async/zone.dart:1381:54)
#18 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
#19 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:633:45)
#20 Future._propagateToListeners (dart:async/future_impl.dart:662:32)
#21 Future._complete (dart:async/future_impl.dart:467:7)
#22 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#23 User_Profile.getUser (package:flutter_poc/Models/User.dart)
<asynchronous suspension>
#24 _MyHomePageState.initPlatformState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:69:24)
<asynchronous suspension>
#25 _MyHomePageState.initState (file:///Users/chaythanyanair/Documents/Qburst/Learn/flutter_poc/lib/main.dart:52:5)
#26 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3734:58)
#27 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3600:5)
#28 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2890:14)
#29 Element.updateChild
This is my EventChannel implementation:
static const platform = const MethodChannel('samples.flutter.io/initialiseRanging');
static const stream =
const EventChannel('samples.flutter.io/ranging');
try {
await platform.invokeMethod('initialiseRanging').then((result){
print(result);
setState(() {
_currentValue = result;
});
stream.receiveBroadcastStream().listen(_onEvent, onError: _onError);
});
} on PlatformException catch (e) {
print( "{e.message}");
}
This is how the _onEvent and _onError functions are implemented.
void _onEvent(Object event) {
setState(() {
_currentValue = event.toString();
});
print(event);
}
void _onError(PlatformException error) {
print(error);
}
Any idea on why this could possible happen?
void _onError(PlatformException error) {
should be
void _onError(Object error) {
Even when you are only interested in PlatformException or even when this is the only exception that happened so far, doesn't mean there can't be others. The expected handler function needs to match the parameter type, instead of only the exceptions you expect.

Resources