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>>);
Related
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.
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;
}
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.
Below code snippet throws Format Exception in Flutter json decode, Any suggestion please?
import 'dart:async' show Future;
import 'dart:convert';
Future<String> readBooks() async {
String jsonString = '{"description":"As part of the "You Don’t Know JS" series","quantity":55}';
Map<String, dynamic> books = json.decode(jsonString);
return jsonString;
}
Format Exception:
2018-10-23 20:40:30.680 18115-18142/addon.com.bookshop E/flutter:
[ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled
exception:
FormatException: Unexpected character (at character 26)
{"name":"As part of the "You Don’t Know JS" series","Age":55}
^
#0 _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1358:5)
#1 _ChunkedJsonParser.parse (dart:convert/runtime/libconvert_patch.dart:919:48)
#2 _parseJson (dart:convert/runtime/libconvert_patch.dart:29:10)
#3 JsonDecoder.convert (dart:convert/json.dart:540:36)
#4 JsonCodec.decode (dart:convert/json.dart:167:41)
#5 _MyHomePageState.readBooks (file:///E:/Me/TimePass/flutter/book_shop/lib/main.dart:58:39)
<asynchronous suspension>
#6 _MyHomePageState.build.<anonymous closure> (file:///E:/Me/TimePass/flutter/book_shop/lib/main.dart:48:39)
<asynchronous suspension>
#7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:503:14)
#8 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:558:30)
#9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#10 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
#11 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
#12 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
#13 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
#14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
#15 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:143:19)
#16 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
#17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
#18 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue
(package:flutter/src/gestures/binding.dart:64:7)
#19 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket
(package:flutter/src/gestures/binding.dart:48:7)
#20 _invoke1 (dart:ui/hooks.dart:142:13)
#21 _dispatchPointerDataPacket (dart:ui/hooks.dart:99:5)
That's just invalid JSON.
The inner quotes need to be escaped as \" to make your JSON valid.
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.