Flutter - Format Exception : Unexpected end of input (at character 1) - flutter

I'm facing this Exception while loading json from a .json file. complete Exception is :
E/flutter ( 4062): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
FormatException: Unexpected end of input (at character 1)
E/flutter ( 4062):
E/flutter ( 4062): ^
E/flutter ( 4062):
E/flutter ( 4062): #0 _ChunkedJsonParser.fail (dart:convert- patch/convert_patch.dart:1405:5)
E/flutter ( 4062): #1 _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:523:7)
E/flutter ( 4062): #2 _parseJson (dart:convert-patch/convert_patch.dart:41:10)
E/flutter ( 4062): #3 JsonDecoder.convert (dart:convert/json.dart:506:36)
E/flutter ( 4062): #4 JsonCodec.decode (dart:convert/json.dart:157:41)
E/flutter ( 4062): #5 _HomePageState.loadJsonData.<anonymous closure>.<anonymous closure> (package:audio_player/presentation/pages/home_page.dart:22:35)
E/flutter ( 4062): #6 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter ( 4062): #7 _HomePageState.loadJsonData.<anonymous closure> (package:audio_player/presentation/pages/home_page.dart:20:27)
E/flutter ( 4062): #8 _rootRunUnary (dart:async/zone.dart:1436:47)
E/flutter ( 4062): #9 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 4062): <asynchronous suspension>
E/flutter ( 4062): #10 _HomePageState.loadJsonData (package:audio_player/presentation/pages /home_page.dart:19:5)
E/flutter ( 4062): <asynchronous suspension>
My Json file path (lib/utils/json/popular_books.json) and code look like this:
[
{
"rating":"4.5",
"title":"sometitle",
"text":"sometext",
"img":"lib/utils/assets/image_1",
}
...
]
My images are in the same folder utils/assets. I'm loading json
List? popularBooks;
loadJsonData() async {
await DefaultAssetBundle.of(context).loadString("lib/utils/json/popular_books.json").then(
(loadedJson) => setState(
() {
popularBooks = json.decode(loadedJson);
},
),
);
}
#override
void initState() {
loadJsonData();
super.initState();
}
And I'm trying to load only the images in the page view :
PageView.builder(
itemCount: popularBooks==null?0:popularBooks!.length,
controller: _controller,
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.only(right: 10),
height: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: Image.asset("${popularBooks![index]["img"]}"),
);
},
),
And then this Format Exception If you have any fix please share it I'd me very thankful. <3

Your JSON is invalid. With a json validator you can spot the problem. In your JSON it is the following syntax error:
[
{
"rating":"4.5",
"title":"sometitle",
"text":"sometext",
"img":"lib/utils/assets/image_1", <-- This comma is the problem
}
]

Related

Error calling provider on button click (FORM SAVED)

I am posting a map on button click using provider, which calls Chopper service to post a map data to the server. It gives an error to the server which is something like this.
I/flutter ( 4801): Observatory listening on ************************************
E/flutter ( 4801): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'DateTime'
E/flutter ( 4801): #0 _JsonStringifier.writeObject (dart:convert/json.dart:688:7)
E/flutter ( 4801): #1 _JsonStringifier.writeMap (dart:convert/json.dart:769:7)
E/flutter ( 4801): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:724:21)
E/flutter ( 4801): #3 _JsonStringifier.writeObject (dart:convert/json.dart:679:9)
E/flutter ( 4801): #4 _JsonStringStringifier.printOn (dart:convert/json.dart:877:17)
E/flutter ( 4801): #5 _JsonStringStringifier.stringify (dart:convert/json.dart:862:5)
E/flutter ( 4801): #6 JsonEncoder.convert (dart:convert/json.dart:262:30)
E/flutter ( 4801): #7 JsonCodec.encode (dart:convert/json.dart:172:45)
E/flutter ( 4801): #8 JsonConverter.encodeJson
E/flutter ( 4801): #9 JsonConverter.convertRequest
E/flutter ( 4801): #10 ChopperClient._encodeRequest
E/flutter ( 4801): #11 ChopperClient._handleRequestConverter
E/flutter ( 4801): #12 ChopperClient.send
E/flutter ( 4801): #13 _$PersonalPostingService.postPersonal
E/flutter ( 4801): #14 _FormState.build.<anonymous closure>.<anonymous closure>
E/flutter ( 4801): #15 _FormState.build.<anonymous closure>.<anonymous closure>
E/flutter ( 4801): #33 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter ( 4801): #34 _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)
E/flutter ( 4801):
Exited (1)
This is where I am calling the function the body is a MAP of string, dynamic
child: RaisedButton(
onPressed: () async {
final form = _formKey.currentState;
if (form!.validate()) {
form.save();
showNotification();
await Provider.of<PersonalPostingService>(
context,
listen: false)
.postPersonal(data);
}
},
child: Text('Save'))),
The GET requests are working fine and are easily being displayed in a listview but the POST function is not working, just for the reference below is the chopper service for POST
#Post(path: 'http://157.......:8040/personal')
Future<Response> postPersonal(
#Body() Map<String, dynamic> body,
);

Unhandled Exception: Invalid argument: Instance of 'CartItemModel'

i am working on a store application and after the user places an order, i will like to store that order details in the firebase firestore. the function for carrying out that call after the button is pressed is this
addOrderDetails() {
final user = Provider.of<UserProvider>(context, listen: false);
writeOrderDetailsForUser({
"userId" : user.user.uid,
"description" : "Cash on delivery",
"status" : "pending",
"createdAt": DateTime.now().millisecondsSinceEpoch.toString(),
"totalPrice" : user.userModel.totalCartPrice,
"cart" : user.userModel.cart,
"address" : widget.addressId,
"phone" : user.userModel.phone,
}).whenComplete(() async {
for (CartItemModel cartItem in user.userModel.cart){
bool value = await user.removeFromCart(cartItem: cartItem);
if(value) {
user.reloadUserModel();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Item has been successfully removed from cart"),));
}else {
print(
"item has not been removed from cart please try again"
);
}
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(
"Your order has been successfully created, please we will call you in a few minutes to confirm your order"),));
});
changeScreenReplacement(context, NavigationController());
}
Future writeOrderDetailsForUser(Map<String, dynamic> data) async
{
await EcommerceApp.firestore
.collection(EcommerceApp.collectionOrders)
.document(EcommerceApp.sharedPreferences.getString(EcommerceApp.userUID) + data['createdAt'])
.setData(data);
}
}
However i am getting this error anytime i make the function call
I/flutter (24853): cart items are: Instance of 'CartItemModel'
E/flutter (24853): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Invalid argument: Instance of 'CartItemModel'
E/flutter (24853): #0 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:419:7)
E/flutter (24853): #1 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #2 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:409:9)
E/flutter (24853): #3 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #4 StandardMessageCodec.writeValue. (package:flutter/src/services/message_codecs.dart:416:9)
E/flutter (24853): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter (24853): #6 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:414:13)
E/flutter (24853): #7 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #8 StandardMessageCodec.writeValue. (package:flutter/src/services/message_codecs.dart:416:9)
E/flutter (24853): #9 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter (24853): #10 StandardMessageCodec.writeValue (package:flutter/src/services/message_codecs.dart:414:13)
E/flutter (24853): #11 FirestoreMessageCodec.writeValue (package:cloud_firestore_platform_interface/src/method_channel/utils/firestore_message_codec.dart:83:13)
E/flutter (24853): #12 StandardMethodCodec.encodeMethodCall (package:flutter/src/services/message_codecs.dart:551:18)
E/flutter (24853): #13 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:150:13)
E/flutter (24853): #14 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (24853): #15 MethodChannelDocumentReference.setData (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:28:43)
E/flutter (24853): #16 DocumentReference.setData (package:cloud_firestore/src/document_reference.dart:48:22)
E/flutter (24853): #17 _PaymentPageState.writeOrderDetailsForUser (package:maen/screens/placeOrderPayment.dart:349:10)
E/flutter (24853): #18 _PaymentPageState.addOrderDetails (package:maen/screens/placeOrderPayment.dart:316:5)
E/flutter (24853): #19 _PaymentPageState.build. (package:maen/screens/placeOrderPayment.dart:297:17)
The problem is caused because of this line
"cart" : user.userModel.cart,
Seems like your user.userModel.cart is the List of CartItemModel,
To overcome this you'll have to serialize this and then add to the database, because database doesn't know anything about CartItemModel,
Do something like this:
"cart" : user.userModel.cart.map((e)=>e.toJson()).toList();
In CartItemModel define the toJson function
As the details is less, I assume CartItemModel has fields like id , name and price
Map toJson() => {
'id': id,
'name': name,
'price' : price
};
This should solve your problem

for loop showing RangeError flutter

The following code shows
E/flutter ( 7354): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Exception: RangeError (index): Invalid value: Not in inclusive range 0..17: 18
E/flutter ( 7354): #0 List.[] (dart:core-patch/growable_array.dart:254:60)
E/flutter ( 7354): #1 parseStudent (package:xxx/screens/SearchActivity/main.dart:22:19)
E/flutter ( 7354): #2 _IsolateConfiguration.apply (package:flutter/src/foundation/_isolates_io.dart:81:34)
E/flutter ( 7354): #3 _spawn.<anonymous closure> (package:flutter/src/foundation/_isolates_io.dart:88:65)
E/flutter ( 7354): #4 _spawn.<anonymous closure> (package:flutter/src/foundation/_isolates_io.dart:87:5)
E/flutter ( 7354): #5 Timeline.timeSync (dart:developer/timeline.dart:163:22)
E/flutter ( 7354): #6 _spawn (package:flutter/src/foundation/_isolates_io.dart:85:35)
E/flutter ( 7354): #7 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:286:17)
E/flutter ( 7354): #8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
this error.
Code:
Map<String, dynamic> map = json.decode(responseBody);
List<dynamic> data = map["students"];
//developer.log(data[0]);
List<Student> stL = List<Student>();
for(int i=0;data[i]!=null;i++){
Student student = Student(rollno:data[i]["username"],name:data[i]["name"],
hostel:data[i]["hostel"],room:data[i]["room"],gender:data[i]["gender"]);
stL.add(student);
}
developer.log(stL.toString());
return stL;
developer.log() is not called.Can someone give a solution?
Or is there a better way to parse the JSON to a list of Student
#Tipu solution is acceptable, but dart can provide more flexible way. You can also use the from named constructor of List.
List<Student> stL = List<Student>.from(map['students'].map((element) =>
Student(rollno:element["username"],name:element["name"],
hostel:element["hostel"],room:element["room"],gender:element["gender"])
).toList());
Instead of using List<dynamic> use Iterable.
Iterable list = map['students'];
list.forEach((element){
Student student = Student(rollno:element["username"],name:element["name"],
hostel:element["hostel"],room:element["room"],gender:element["gender"]);
stL.add(student);
});

How to select larger or max id from database flutter

I am developing an application through which I need to display a larger id. It was previously added to the database through the following query:
Future<String> getLogin() async {
var response = await http.get(Uri.encodeFull("http://xxxxxxxxx/Noti.php"),);
setState(() {
var convertDataToJson = json.decode(response.body.toString());
data = convertDataToJson['result'];
if (data != null) {
User_ID =int.parse(data[0]['id']);
}
}
);
}
<?php
require_once 'connt.php';
$query="SELECT * FROM addcomment";
$result = mysqli_query($con,$query);
$array = array();
while ($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
echo ($result) ?
json_encode(array("code" => 1, "result"=>$array)) :
json_encode(array("code" => 0, "message"=>"Data not found !"));
?>
Now like the example above works fine, but I need to take a higher id.
I created a php file like this:
<?php
require_once 'connt.php';
$query="SELECT MAX( id ) FROM addcomment";
$result = mysqli_query($con,$query);
$array = array();
while ($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
echo ($result) ?
json_encode(array("code" => 1, "result"=>$array)) :
json_encode(array("code" => 0, "message"=>"Data not found !"));
?>
But I got the following problem:
E/flutter (29294): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Invalid argument(s): The source must not be null
E/flutter (29294): #0 int.parse (dart:core-patch/integers_patch.dart:51:25)
E/flutter (29294): #1 AddCommentsState.getLogin.<anonymous closure> (package:flutter_apptestqeuriy/Ready.dart:89:22)
E/flutter (29294): #2 State.setState (package:flutter/src/widgets/framework.dart:1240:30)
E/flutter (29294): #3 AddCommentsState.getLogin (package:flutter_apptestqeuriy/Ready.dart:85:5)
E/flutter (29294): <asynchronous suspension>
E/flutter (29294): #4 AddCommentsState.initState.<anonymous closure> (package:flutter_apptestqeuriy/Ready.dart:58:9)
E/flutter (29294): #5 interval.function (package:flutter_apptestqeuriy/Ready.dart:16:9)
E/flutter (29294): #6 _rootRun (dart:async/zone.dart:1182:47)
E/flutter (29294): #7 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (29294): #8 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (29294): #9 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (29294): #10 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (29294): #11 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (29294): #12 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter (29294): #13 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (29294): #14 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter (29294): #15 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter (29294): #16 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (29294):
I don't know what is the problem. But I need to display the highest id in the field. If someone knows the solution, please help me.
Replace;
$query="SELECT MAX( id ) AS max_id FROM addcomment";
And echo row[“max_id”]

How to convert JSON response to Dart Map<String, int> object ...?

I'm getting data from my api as a following JSON object to create chart with the data. I want to covert this DIO response to a Map<String, int> object in my flutter app.
My API response:
{
"November 20": 1,
"October 20": 3,
"September 20": 1
}
My try of creating a map object:
Future<bool> fetchChartData() async {
var response = await CasesApiService().getChartData();
Map<String, dynamic> data = jsonDecode(response.data);
}
But it shows the following error:
E/flutter ( 4733): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
E/flutter ( 4733): #0 CasesProvider.fetchChartData
package:bdopsApp/providers/casesProvider.dart:86
E/flutter ( 4733): <asynchronous suspension>
E/flutter ( 4733): #1 _CasesChartViewState.build.<anonymous closure>
package:bdopsApp/…/casesApp/casesChart.dart:31
E/flutter ( 4733): #2 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:985
E/flutter ( 4733): #3 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1101
E/flutter ( 4733): #4 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:183
E/flutter ( 4733): #5 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:598
E/flutter ( 4733): #6 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:287
E/flutter ( 4733): #7 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:222
E/flutter ( 4733): #8 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:476
E/flutter ( 4733): #9 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:77
E/flutter ( 4733): #10 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:122
E/flutter ( 4733): #11 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 4733): #12 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:120
E/flutter ( 4733): #13 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:106
E/flutter ( 4733): #14 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:368
E/flutter ( 4733): #15 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:348
E/flutter ( 4733): #16 RendererBinding.dispatchEvent
package:flutter/…/rendering/binding.dart:268
E/flutter ( 4733): #17 GestureBinding._handlePointerEventImmediately
package:flutter/…/gestures/binding.dart:303
E/flutter ( 4733): #18 GestureBinding.handlePointerEvent
package:flutter/…/gestures/binding.dart:267
E/flutter ( 4733): #19 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:225
E/flutter ( 4733): #20 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:208
E/flutter ( 4733): #21 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 4733): #22 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 4733): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 4733): #24 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 4733): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
N.B: I'm doing my final year project. Therefore, the process I'm following might not be what is used in real world project.
If you run the following example in the dartPad you will get the result that you are looking for:
import 'dart:convert';
void main() {
var jsonString= "{\"November 20\": \"1\",\"October 20\": \"2\",\"September 20\": \"3\"}";
Map<String, dynamic> data = jsonDecode(jsonString);
print(data);
}
I think you need to check the data that you are getting it from the response.data