json.decode throws FormatException on nested double quote in json - dart - dart

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.

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.

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>>);

Concurrent modification during iteration while trying to remove object from a list

Am trying to loop in multiple lists and finally comparing their names and delete it from a list if they don't match ...
but am getting this error:
Concurrent modification during iteration:
although i have took a copy of the original list just to avoid this error .. but still am getting it .. what i tried is:
globals.filteredPollsList = pollsList;
pollsList.forEach( (p) {
for (var e in entitiesList) {
print(e.name);
for (var entity in entitiesFilter) {
print(entity);
print(e.name);
if (e.name != entity && p.entityId != e.id) {
print('true');
globals.filteredPollsList.remove(p);
}
}
}
});
but am getting this error:
flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
flutter: The following ConcurrentModificationError was thrown while handling a gesture:
flutter: Concurrent modification during iteration: Instance(length:8) of '_GrowableList'.
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 List.forEach (dart:core/runtime/libgrowable_array.dart:279:36)
flutter: #1 _ShapedWidgetState.filterPoll (package:moi_polls_app/pages/home.page.dart:1484:15)
flutter: #2 _ShapedWidgetState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:moi_polls_app/pages/home.page.dart:1896:45)
flutter: #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
flutter: #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
flutter: #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
flutter: #6 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
flutter: #7 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
flutter: #8 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
flutter: #9 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
flutter: #10 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
flutter: #11 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19)
flutter: #12 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
flutter: #13 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
flutter: #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
flutter: #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
flutter: #16 _invoke1 (dart:ui/hooks.dart:168:13)
flutter: #17 _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
flutter:
flutter: Handler: onTap
flutter: Recognizer:
flutter: TapGestureRecognizer#e99b3(debugOwner: GestureDetector, state: possible, won arena, finalPosition:
flutter: Offset(283.3, 608.7), sent tap down)
how to solve this?
If you want to copy your list use this:
globals.filteredPollsList = List.from(pollsList);

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.

dart upload file error: FormatException: Bad UTF-8 encoding 0xbf

Here is my server side dart code:
import 'dart:io';
import 'package:http_server/http_server.dart';
void main() {
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.listen((HttpRequest request) {
if (request.method.toLowerCase() == 'post' && request.uri.path == '/upload') {
HttpBodyHandler.processRequest(request).then((body) {
HttpBodyFileUpload fileUpload = body.body['file'];
File file = new File('aaa');
file.writeAsBytes(fileUpload.content, mode: FileMode.WRITE).then((_) {
request.response.close();
});
});
}
});
});
}
and my error is:
Unhandled exception:
Uncaught Error: FormatException: Bad UTF-8 encoding 0xbf
Stack Trace:
#0 _Utf8Decoder.convert (dart:convert/utf.dart:534)
#1 _Utf8ConversionSink.addSlice (dart:convert/string_conversion.dart:334)
#2 _Utf8ConversionSink.add (dart:convert/string_conversion.dart:330)
#3 _ConverterStreamEventSink.add (dart:convert/chunked_conversion.dart:89)
#4 _handleData (dart:async/stream_transformers.dart:119)
#5 _RootZone.runUnaryGuarded (dart:async/zone.dart:1020)
#6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#7 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:270)
#8 _StreamController&&_SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:578)
#9 _StreamController._add (dart:async/stream_controller.dart:453)
#10 _StreamController.add (dart:async/stream_controller.dart:410)
#11 BoundMultipartStream._parse.reportData (package:mime/src/bound_multipart_stream.dart:161:34)
#12 BoundMultipartStream._parse (package:mime/src/bound_multipart_stream.dart:318:28)
#13 BoundMultipartStream.BoundMultipartStream.<anonymous closure>.<anonymous closure> (package:mime/src/bound_multipart_stream.dart:111:24)
#14 _RootZone.runUnaryGuarded (dart:async/zone.dart:1020)
#15 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#16 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:270)
#17 _ForwardingStreamSubscription._add (dart:async/stream_pipe.dart:122)
#18 _ForwardingStream._handleData (dart:async/stream_pipe.dart:86)
#19 _handleData (dart:async/stream_pipe.dart:154)
#20 _RootZone.runUnaryGuarded (dart:async/zone.dart:1020)
#21 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#22 _DelayedData.perform (dart:async/stream_impl.dart:595)
#23 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:711)
#24 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:671)
#25 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#26 _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#27 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:126)
#0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:820)
#1 _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#2 _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:126)
Process finished with exit code 255
I used postman to make a post, I chose form-data and add a key called file, value is a txt file.
after send my post to dart server, i got this exception.
is there something wrong with the post ? or the dart code ?
I'm really new to dart, please help me out...
thank you.

Resources