Flutter :- How to parse the JSON from the model class in flutter? - flutter

I am parsing the JSON like from key and values like below code in flutter
Future<LoginBean> login() async {
var body = json.encode({"MOB": "1112223330", "KEY": "123456"});
return http.post(
Uri.encodeFull(
"https://MY_Server/Users/login"),
body: body.toString(),
headers: {'Content-type': 'application/json'}).then((response) {
print("Response Status : $response");
if (response.statusCode == 200) {
Map userMap = jsonDecode(json);
var user = new LoginBean.fromJson(userMap);
debugPrint("here is the response==>>>> $user");
}
});
}
Is there any other way to parse the JSON in Model class as we do in Android, please check the below example.
Gson gson = new Gson();
MY_LOGIN_BEAN loginBean = gson.fromJson(response, MY_LOGIN_BEAN.class);
I have referred this links but not getting the solution, please check below:-
1). Link
2). Link
3). Link
This is my JSON reponse
{"status":1,"message":"Login Successfully","data":{"userid":"101","Authorization":"eyJ1c2VyaWQiOiIxMDEiLCJ0b2tlbiI6IjVjYWRkYzUzMWY4YzAifQ==","roles":"2","firstname":"Ravindra","lastname":"kushwaha","fullname":"Ravindra kushwaha","wallet_amount":"845.00","mobile":"1112223330","email":"ravindra.kushwaha#consagous.com","chat_id":"","qrcode_image":"https:\/\/dapplepay.consagous.co.in\/uploads\/coupon_qr\/11C1f7ApJM8r.png","redirect_to_verify":"0","notification_status":"0","country_code":"91","Is_Allowed_Transaction":"1","profile_image":"https:\/\/dapplepay.consagous.co.in\/uploads\/user\/1553600479DapplePay1553600454461.png","fingerprint_status":"0"}}
I have tried below lines of code for it, please have a look on it , but I did not get any success on it.
class LoginBean {
int status;
String message;
Data data;
LoginBean({
this.status,
this.message,
this.data,
});
static Map<String, dynamic> toMap(LoginBean loginBean){
var map = Map<String, dynamic>();
map['status'] = loginBean.status;
map['message'] = loginBean.message;
map['data'] = Data.toMap(loginBean);
return map;
}
LoginBean.map(dynamic obj) {
this.status = obj["status"];
this.message = obj["message"];
if (obj['data'] != null) {
this.data = new Data.map(obj['data']);
}
}
factory LoginBean.fromJson(dynamic json) {
print('here we gooo');
return LoginBean(
status: json['status'],
message: json['message'],
data: new Data.fromJson(json['data'])
);
}
}
class Data {
String userid;
String authorization;
String roles;
String firstname;
String lastname;
String fullname;
String walletAmount;
String mobile;
String email;
String chatId;
String qrcodeImage;
String redirectToVerify;
String notificationStatus;
String countryCode;
String isAllowedTransaction;
String profileImage;
String fingerprintStatus;
Data.map(dynamic json) {
this.userid = json['userid'];
this.authorization = json['authorization'];
this.roles = json['roles'];
this.firstname = json['firstname'];
this.lastname = json['lastname'];
this.fullname = json['fullname'];
this.walletAmount = json['walletAmount'];
this.mobile = json['mobile'];
this.email = json['email'];
this.chatId = json['chatId'];
this.qrcodeImage = json['qrcodeImage'];
this.redirectToVerify = json['redirectToVerify'];
this.notificationStatus = json['notificationStatus'];
this.countryCode= json['countryCode'];
this.isAllowedTransaction = json['isAllowedTransaction'];
this.profileImage = json['profileImage'];
this.fingerprintStatus = json['fingerprintStatus'];
}
static Map<String, dynamic> toMap(LoginBean loginBean){
var map = Map<String, dynamic>();
map['userid'] = loginBean.data.userid;
map['authorization'] = loginBean.data.authorization;
map['roles'] = loginBean.data.roles;
map['firstname'] = loginBean.data.firstname;
map['lastname'] = loginBean.data.lastname;
map['fullname'] = loginBean.data.fullname;
map['walletAmount'] = loginBean.data.walletAmount;
map['mobile'] = loginBean.data.mobile;
map['email'] = loginBean.data.email;
map['chatId'] = loginBean.data.chatId;
map['qrcodeImage'] = loginBean.data.qrcodeImage;
map['redirectToVerify'] = loginBean.data.redirectToVerify;
map['notificationStatus'] = loginBean.data.notificationStatus;
map['countryCode'] = loginBean.data.countryCode;
map['isAllowedTransaction'] = loginBean.data.isAllowedTransaction;
map['profileImage'] = loginBean.data.profileImage;
map['fingerprintStatus'] = loginBean.data.fingerprintStatus;
return map;
}
factory Data.fromJson(dynamic json) {
return Data(
userid: json['userid'],
authorization: json['authorization'],
roles: json['roles'],
firstname: json['firstname'],
lastname: json['lastname'],
fullname: json['fullname'],
walletAmount: json['walletAmount'],
mobile: json['mobile'],
email: json['email'],
chatId: json['chatId'],
qrcodeImage: json['qrcodeImage'],
redirectToVerify: json['redirectToVerify'],
notificationStatus: json['notificationStatus'],
countryCode: json['countryCode'],
isAllowedTransaction: json['isAllowedTransaction'],
profileImage: json['profileImage'],
fingerprintStatus: json['fingerprintStatus'],
);
}
Data({
this.userid,
this.authorization,
this.roles,
this.firstname,
this.lastname,
this.fullname,
this.walletAmount,
this.mobile,
this.email,
this.chatId,
this.qrcodeImage,
this.redirectToVerify,
this.notificationStatus,
this.countryCode,
this.isAllowedTransaction,
this.profileImage,
this.fingerprintStatus,
});
}
I am getting the below exception from the above code, while i am using the model class to parse the JSON
2019-04-10 18:59:28.553 11121-11153/democom.first_flutter_app E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
#0 _LoginScreen.login.<anonymous closure> (package:first_flutter_app/onBording/login_screen.dart:139:34)
#1 _rootRunUnary (dart:async/zone.dart:1132:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#3 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#5 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#6 Future._complete (dart:async/future_impl.dart:473:7)
#7 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#8 _AsyncAwaitCompleter.complete (dart:async/runtime/libasync_patch.dart:28:18)
#9 _completeOnAsyncReturn (dart:async/runtime/libasync_patch.dart:294:13)
#10 _withClient (package:http/http.dart)
<asynchronous suspension>
#11 post (package:http/http.dart:70:3)
#12 _LoginScreen.login (package:first_flutter_app/onBording/login_screen.dart:129:12)
<asynchronous suspension>
#13 _LoginScreen.build.<anonymous closure>.<anonymous closure> (package:first_flutter_app/onBording/login_screen.dart:102:25)
#14 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14)
#15 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:568:30)
#16 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:120:24)
#17 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
#18 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
#19 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:369:9)
#20 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
#21 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
#22 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:214:19)
#23 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:192:22)
#24 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:149:7)
#25 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
#26 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
#27 _rootRunUnary (dart:async/zone.dart:1136:13)
#28 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#29 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#30 _invoke1 (dart:ui/hooks.dart:223:10)
#31 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)

You are decoding json when you should be decoding body received in response like this -
var userMap = jsonDecode(response?.body);

Related

WooCommerce package, flutter

I am trying to add WooCommerce payment gateways through WooCommerce plugin on flutter, I've been having an error related to it, and I'm pretty sure that it's the package's fault.
I'd really like any kind of help related to it, since I am stuck on it, The error points at the order "int". I changed it to string still gave me the same error.
Here's the code---
Method:
WooCommerce wooCommerce = WooCommerce(
baseUrl: baseUrl,
consumerKey: consumerKey,
consumerSecret: consumerSecret,
isDebug: true,
);
getPaymentGateways() async {
gateways = await wooCommerce.getPaymentGateways();
}
Error-
E/flutter (13771): #0 new WooPaymentGateway.fromJson (package:woocommerce/models/payment_gateway.dart:62:5)
E/flutter (13771): #1 WooCommerce.getPaymentGateways (package:woocommerce/woocommerce.dart:1413:39)
E/flutter (13771): <asynchronous suspension>
E/flutter (13771): #2 _CheckoutCardState.getPaymentGateways (package:flutter_auth/to_test/checkout.dart:34:34)
E/flutter (13771): #3 _CheckoutCardState.build.<anonymous closure> (package:flutter_auth/to_test/checkout.dart:100:23)
E/flutter (13771): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
E/flutter (13771): #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
E/flutter (13771): #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (13771): #7 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
E/flutter (13771): #8 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
E/flutter (13771): #9 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
E/flutter (13771): #10 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter (13771): #11 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (13771): #12 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)```
WooPaymentGateway-
String id;
String title;
String description;
int order;
bool enabled;
String methodTitle;
String methodDescription;
List<String> methodSupports;
WooPaymentGatewaySettings settings;
WooPaymentGatewayLinks lLinks;
WooPaymentGateway(
{this.id,
this.title,
this.description,
this.order,
this.enabled,
this.methodTitle,
this.methodDescription,
this.methodSupports,
this.settings,
this.lLinks}) : assert (id != null);
WooPaymentGateway.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
description = json['description'];
order = json['order'];
enabled = json['enabled'];
methodTitle = json['method_title'];
methodDescription = json['method_description'];
methodSupports = json['method_supports'].cast<String>();
settings = json['settings'] != null
? new WooPaymentGatewaySettings.fromJson(json['settings'])
: null;
lLinks = json['_links'] != null ? new WooPaymentGatewayLinks.fromJson(json['_links']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['description'] = this.description;
data['order'] = this.order;
data['enabled'] = this.enabled;
data['method_title'] = this.methodTitle;
data['method_description'] = this.methodDescription;
data['method_supports'] = this.methodSupports;
if (this.settings != null) {
data['settings'] = this.settings.toJson();
}
if (this.lLinks != null) {
data['_links'] = this.lLinks.toJson();
}
return data;
}
}
Let me know if I post the thing wrong<////>>??/////<<>>///

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

E/flutter ( 3391): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
E/flutter ( 3391): #0 new LoginResponseModel.fromJson (package:flutter_woocomerce/model/login_model.dart:21:53)
E/flutter ( 3391): #1 APIServices.loginCustomer (package:flutter_woocomerce/api_service.dart:63:36)
E/flutter ( 3391): <asynchronous suspension>
E/flutter ( 3391): #2 _LoginPageState._uiSetup.<anonymous closure> (package:flutter_woocomerce/pages/login_page.dart:137:36)
E/flutter ( 3391): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter ( 3391): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter ( 3391): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter ( 3391): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter ( 3391): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter ( 3391): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:222:7)
E/flutter ( 3391): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:476:9)
E/flutter ( 3391): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:77:12)
E/flutter ( 3391): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter ( 3391): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter ( 3391): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter ( 3391): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter ( 3391): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:358:19)
E/flutter ( 3391): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter ( 3391): #17 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter ( 3391): #18 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter ( 3391): #19 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter ( 3391): #20 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter ( 3391): #21 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 3391): #22 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 3391): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 3391): #24 _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 3391): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter ( 3391): mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
//login model
class LoginResponseModel {
bool success;
int statusCode;
String code;
String message;
Data data;
LoginResponseModel({
this.success,
this.statusCode,
this.code,
this.message,
this.data,
});
LoginResponseModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
statusCode = json['statusCode'];
code = json['code'];
message = json['message'];
data = json['data'] != null ? Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['success'] = this.success;
data['statusCode'] = this.statusCode;
data['code'] = this.code;
data['message'] = this.message;
if (this.data != null) {
data['data'] = this.data.toJson() ;
}
return data;
}
}
class Data {
String token;
int id;
String email;
String niceName;
String firstName;
String lastName;
String displayName;
Data({
this.token,
this.id,
this.email,
this.niceName,
this.firstName,
this.lastName,
this.displayName,
});
Data.fromJson(Map<String, dynamic> json) {
token = json['token'];
id = json['id'];
email = json['email'];
niceName = json['niceName'];
firstName = json['firstName'];
lastName = json['lastName'];
displayName = json['displayName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['token'] = this.token;
data['id'] = this.id;
data['email'] = this.email;
data['niceName'] = this.niceName;
data['firstName'] = this.firstName;
data['lastName'] = this.lastName;
data['displayName'] = this.displayName;
return data;
}
}
api services
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_woocomerce/config.dart';
import 'package:flutter_woocomerce/model/customer.dart';
import 'package:flutter_woocomerce/model/login_model.dart';
class APIServices {
Future<bool> createCustomer(CustomerModel) async {
var authToken =
base64.encode(utf8.encode(Config.key + ':' + Config.secret));
bool ret = false;
try {
var response = await Dio().post(
Config.url + Config.customerURL,
data: CustomerModel.toJson(),
options: Options(
headers: {
HttpHeaders.authorizationHeader: 'Basic $authToken',
HttpHeaders.contentTypeHeader: 'application/json',
}
)
);
if (response.statusCode == 201) {
ret = true;
}
} on DioError catch (e) {
if (e.response.statusCode == 404) {
ret = false;
} else {
ret = false;
}
}
return ret;
}
Future<LoginResponseModel> loginCustomer(String username,
String password) async {
LoginResponseModel model;
try {
var response = await Dio().post(
Config.tokenURL,
data: {
"username": username,
"password": password,
},
options: Options(
headers: {
HttpHeaders
.contentTypeHeader: 'application/x-www-form-urlencoded',
}
)
);
if (response.statusCode == 200) {
model = LoginResponseModel.fromJson(response.data);
}
} on DioError catch (e) {
print(e.message);
}
return model;
}
}
my code in github
From the "error" that shows you, the response type is a List<dynamic>. In LoginResponseModel.fromJson method debugPrint your response and check and make sure its type is Map<String, dynamic>.
The response that you updated in the comment above, shows that the value of data in the response is an array.
In your code here:
LoginResponseModel.fromJson(Map<String, dynamic> json) {
success = json['success'];
statusCode = json['statusCode'];
code = json['code'];
message = json['message'];
data = json['data'] != null ? Data.fromJson(json['data']) : null;
}
This line:
data = json['data'] != null ? Data.fromJson(json['data']) : null;
Solution:
You are trying to convert the array data into a Data object, while you actually need parse it into a List, like this:
data = json['data'] != null ? List<dynamic>.from(json["data"]) : null;
OR
if the List is of Data objects then:
data = json['data'] != null ? List<Data>.from(json["data"].map((x) => Data.fromJson(x))) : null;

ERROR:flutter/lib/ui/ui_dart_state.cc(166) Unhandled Exception: type '_CompactLinkedHashSet<Void>' is not a subtype of type 'FutureOr<Map<>>'

I got this error when I tried to parse json object from server.
I tried to find solutions many times but I couldn't get any.
IDE says this error occur in this code but not telling specific part.
The code below is my model's code which request api response to service module.
Future getLolBySummonerName(Map<String, String> queryBody) async {
try {
_lolResponse = await _lolService.getLolBySummonerName(queryBody);
notifyListeners();
} on UnauthorizedException {
return Future.error(Navigate('/loginMethod'));
} on NotFoundException {
return Future.error(Message('없는 소환사명입니다.'));
}
}
And this is service module part.
Future<LolResponse> getLolBySummonerName(Map<String, String> queryBody) async {
var uri = Uri.https('servier-url', '/endpoint', queryBody);
final response = await http.get(uri);
if (response.statusCode == 200) {
return LolResponse.fromJson(jsonDecode(response.body));
}
NetworkErrorHandler.throwProperException(response);
return null;
}
Finally those classes are the responses from server.
class LolResponse {
final String evaluation;
final FlexRank flexRank;
final String icon;
final int level;
final List<Most> mosts;
final SoloRank soloRank;
final String summonerName;
LolResponse(
{this.evaluation,
this.flexRank,
this.icon,
this.level,
this.mosts,
this.soloRank,
this.summonerName});
factory LolResponse.fromJson(Map<String, dynamic> json) {
return LolResponse(
evaluation: json['evaluation'],
flexRank: FlexRank.fromJson(json['flexRank']),
icon: json['icon'],
level: json['level'],
mosts: json['mosts'].map((e) => Most.fromJson(e)).toList(),
soloRank: SoloRank.fromJson(json['soloRank']),
summonerName: json['summonerName']);
}
}
class FlexRank {
final String image;
final String name;
FlexRank({this.image, this.name});
factory FlexRank.fromJson(Map<String, dynamic> json) {
if (json == null) return FlexRank();
return FlexRank(image: json['image'], name: json['name']);
}
}
class Most {
final String evaluation;
final int gameCount;
final String image;
final String name;
final double winRate;
Most({this.evaluation, this.gameCount, this.image, this.name, this.winRate});
factory Most.fromJson(Map<String, dynamic> json) {
if (json == null) return Most();
return Most(
evaluation: json['evaluation'],
gameCount: json['gameCount'],
image: json['image'],
name: json['name'],
winRate: json['winRate']);
}
}
class SoloRank {
final String image;
final String name;
SoloRank({this.image, this.name});
factory SoloRank.fromJson(Map<String, dynamic> json) {
if (json == null) return SoloRank();
return SoloRank(image: json['image'], name: json['name']);
}
}
I wrote my flutter information if this could help to get my solutions.
Flutter doctor
[√] Flutter (Channel stable, 1.20.1, on Microsoft Windows [Version 10.0.19041.388], locale ko-KR)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[√] Android Studio (version 4.0)
[!] IntelliJ IDEA Community Edition (version 2019.2)
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
[√] VS Code (version 1.47.3)
[√] Connected device (1 available)
! Doctor found issues in 1 category.
ADD
I brought my entire error log here.
E/flutter (22270): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: type '_CompactLinkedHashSet<void>' is not a subtype of type 'FutureOr<Map<dynamic, dynamic>>'
E/flutter (22270): #0 _FutureListener.handleError (dart:async/future_impl.dart:160:20)
E/flutter (22270): #1 Future._propagateToListeners.handleError (dart:async/future_impl.dart:708:47)
E/flutter (22270): #2 Future._propagateToListeners (dart:async/future_impl.dart:729:24)
E/flutter (22270): #3 Future._completeError (dart:async/future_impl.dart:537:5)
E/flutter (22270): #4 _AsyncAwaitCompleter.completeError (dart:async-patch/async_patch.dart:47:15)
E/flutter (22270): #5 InputProfileModel.getLolBySummonerName (package:match_making/ui/input/input_profile_model.dart)
E/flutter (22270): <asynchronous suspension>
E/flutter (22270): #6 _InputLolBodyState.build.<anonymous closure> (package:match_making/ui/input/lol/component/input_lol_body.dart:43:30)
E/flutter (22270): <asynchronous suspension>
E/flutter (22270): #7 _InputLolBodyState.build.<anonymous closure> (package:match_making/ui/input/lol/component/input_lol_body.dart)
E/flutter (22270): #8 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter (22270): #9 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter (22270): #10 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter (22270): #11 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter (22270): #12 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter (22270): #13 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter (22270): #14 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter (22270): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter (22270): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter (22270): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter (22270): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter (22270): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter (22270): #20 _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (22270): #21 _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (22270): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (22270): #23 _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter (22270): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)
E/flutter (22270):
Also the json request format too
{
"evaluation": "string",
"flexRank": {
"image": "string",
"name": "string"
},
"icon": "string",
"level": 0,
"mosts": [
{
"evaluation": "string",
"gameCount": 0,
"image": "string",
"name": "string",
"winRate": 0
}
],
"soloRank": {
"image": "string",
"name": "string"
},
"summonerName": "string"
}
class LolResponse {
String evaluation;
FlexRank flexRank;
String icon;
dynamic level;
List<Mosts> mosts;
FlexRank soloRank;
String summonerName;
LolResponse(
{this.evaluation,
this.flexRank,
this.icon,
this.level,
this.mosts,
this.soloRank,
this.summonerName});
LolResponse.fromJson(Map<String, dynamic> json) {
evaluation = json['evaluation'];
flexRank = json['flexRank'] != null
? new FlexRank.fromJson(json['flexRank'])
: null;
icon = json['icon'];
level = json['level'];
if (json['mosts'] != null) {
mosts = new List<Mosts>();
json['mosts'].forEach((v) {
mosts.add(new Mosts.fromJson(v));
});
}
soloRank = json['soloRank'] != null
? new FlexRank.fromJson(json['soloRank'])
: null;
summonerName = json['summonerName'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['evaluation'] = this.evaluation;
if (this.flexRank != null) {
data['flexRank'] = this.flexRank.toJson();
}
data['icon'] = this.icon;
data['level'] = this.level;
if (this.mosts != null) {
data['mosts'] = this.mosts.map((v) => v.toJson()).toList();
}
if (this.soloRank != null) {
data['soloRank'] = this.soloRank.toJson();
}
data['summonerName'] = this.summonerName;
return data;
}
}
class FlexRank {
String image;
String name;
FlexRank({this.image, this.name});
FlexRank.fromJson(Map<String, dynamic> json) {
image = json['image'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['image'] = this.image;
data['name'] = this.name;
return data;
}
}
class Mosts {
String evaluation;
dynamic gameCount;
String image;
String name;
int winRate;
Mosts({this.evaluation, this.gameCount, this.image, this.name, this.winRate});
Mosts.fromJson(Map<String, dynamic> json) {
evaluation = json['evaluation'];
gameCount = json['gameCount'];
image = json['image'];
name = json['name'];
winRate = json['winRate'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['evaluation'] = this.evaluation;
data['gameCount'] = this.gameCount;
data['image'] = this.image;
data['name'] = this.name;
data['winRate'] = this.winRate;
return data;
}
}
Can you try this model and check your api is working or not .

Complex models with json_serializable - List<objects> not converting to map

UPDATE
I have built a small sample and will add all code to this post. I have to believe there is an answer/explanation to this and am hoping someone can educate me on what I'm missing. Class fields that are type object are not getting converted and I do not understand why.
Here are the model classes I'm working with.
import 'package:json_annotation/json_annotation.dart';
part 'parent.g.dart';
#JsonSerializable()
class Parent {
int id;
final String name;
final int age;
List<Child> children;
Job job;
Parent({this.name, this.age, this.children, this.job});
factory Parent.fromJson(Map<String, dynamic> json) => _$ParentFromJson(json);
Map<String, dynamic> toJson() => _$ParentToJson(this);
}
#JsonSerializable()
class Child{
int id;
final String name;
final int age;
Child({this.name, this.age});
factory Child.fromJson(Map<String, dynamic> json) => _$ChildFromJson(json);
Map<String, dynamic> toJson() => _$ChildToJson(this);
}
#JsonSerializable()
class Job{
int id;
String title;
Job({this.title});
factory Job.fromJson(Map<String, dynamic> json) => _$JobFromJson(json);
Map<String, dynamic> toJson() => _$JobToJson(this);
}
Here is the .g generated file for these classes
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'parent.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Parent _$ParentFromJson(Map<String, dynamic> json) {
return Parent(
name: json['name'] as String,
age: json['age'] as int,
children: (json['children'] as List)
?.map(
(e) => e == null ? null : Child.fromJson(e as Map<String, dynamic>))
?.toList(),
job: json['job'] == null
? null
: Job.fromJson(json['job'] as Map<String, dynamic>),
)..id = json['id'] as int;
}
Map<String, dynamic> _$ParentToJson(Parent instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'age': instance.age,
'children': instance.children,
'job': instance.job,
};
Child _$ChildFromJson(Map<String, dynamic> json) {
return Child(
name: json['name'] as String,
age: json['age'] as int,
)..id = json['id'] as int;
}
Map<String, dynamic> _$ChildToJson(Child instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'age': instance.age,
};
Job _$JobFromJson(Map<String, dynamic> json) {
return Job(
title: json['title'] as String,
)..id = json['id'] as int;
}
Map<String, dynamic> _$JobToJson(Job instance) => <String, dynamic>{
'id': instance.id,
'title': instance.title,
};
Here is the DAO class for the parent class
import 'package:sembast/sembast.dart';
import 'package:json_serial_test/services/app_database.dart';
import 'package:json_serial_test/models/parent.dart';
class ParentDao {
static const String PARENT_STORE_NAME = 'parents';
// A Store with int keys and Map<String, dynamic> values.
// This Store acts like a persistent map, values of which are Parent objects converted to Map
final _parentStore = intMapStoreFactory.store(PARENT_STORE_NAME);
// Private getter to shorten the amount of code needed to get the
// singleton instance of an opened database.
Future<Database> get _db async => await AppDatabase.instance.database;
Future insert(Parent parent) async {
await _parentStore.add(await _db, parent.toJson());
}
Future update(Parent parent) async {
// For filtering by key (ID), RegEx, greater than, and many other criteria,
// we use a Finder.
final finder = Finder(filter: Filter.byKey(parent.id));
await _parentStore.update(
await _db,
parent.toJson(),
finder: finder,
);
}
Future deleteAll() async {
await _parentStore.delete(await _db);
}
Future delete(Parent parent) async {
final finder = Finder(filter: Filter.byKey(parent.id));
await _parentStore.delete(
await _db,
finder: finder,
);
}
Future<List<Parent>> getAllSortedByName() async {
// Finder object can also sort data.
final finder = Finder(sortOrders: [
SortOrder('name'),
]);
final recordSnapshots = await _parentStore.find(
await _db,
finder: finder,
);
// Making a List<Parent> out of List<RecordSnapshot>
return recordSnapshots.map((snapshot) {
final parent = Parent.fromJson(snapshot.value);
// An ID is a key of a record from the database.
parent.id = snapshot.key;
return parent;
}).toList();
}
}
Here is my test
// Setup
final k1 = Child(name: 'Billy', age: 10);
final k2 = Child(name: 'Jannet', age: 9);
final job = Job(title: 'Cook');
final List<Child> kids = [k1, k2];
final dad = Parent(name: 'Dave', age: 52, job: job, children: kids);
await pDao.insert(dad);
List<Parent> dadsInDb = await pDao.getAllSortedByName();
print('Dads from DB: ${dadsInDb.toString()}');
Upon trying to perform an insert of a Parent into my sembast DB, this is the error that shows up.
E/flutter (12986): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid argument(s): value Instance of 'Child' unsupported type Child E/flutter (12986): #0 cloneValue (package:sembast/src/utils.dart:191:3) E/flutter (12986): #1 cloneValue.<anonymous closure> (package:sembast/src/utils.dart:177:33) E/flutter (12986): #2 MappedListIterable.elementAt (dart:_internal/iterable.dart:417:29) E/flutter (12986): #3 ListIterable.toList (dart:_internal/iterable.dart:221:19) E/flutter (12986): #4 cloneValue (package:sembast/src/utils.dart:177:52) E/flutter (12986): #5 cloneValue.<anonymous closure> (package:sembast/src/utils.dart:174:49) E/flutter (12986): #6 MapMixin.map (dart:collection/maps.dart:165:28) E/flutter (12986): #7 cloneValue (package:sembast/src/utils.dart:173:18) E/flutter (12986):
#8 SembastStore.txnPutSync (package:sembast/src/store_impl.dart:133:15) E/flutter (12986): #9 SembastStore.txnAdd (package:sembast/src/store_impl.dart:117:11) E/flutter (12986): <asynchronous suspension> E/flutter (12986): #10 StoreRefMixin.add.<anonymous closure> (package:sembast/src/store_ref_impl.dart:75:12) E/flutter (12986): #11 SembastDatabase.inTransaction.<anonymous closure> (package:sembast/src/database_impl.dart:1238:34) E/flutter (12986):
#12 SembastDatabase.transaction.<anonymous closure>.<anonymous closure> (package:sembast/src/database_impl.dart:1090:59) E/flutter (12986): #13 new Future.sync (dart:async/future.dart:224:31) E/flutter (12986): #14 SembastDatabase.transaction.<anonymous closure> (package:sembast/src/database_impl.dart:1090:26) E/flutter (12986): #15 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:32:26) E/flutter (12986):
#16 SembastDatabase.transaction (package:sembast/src/database_impl.dart:1073:38) E/flutter (12986):
#17 SembastDatabase.inTransaction (package:sembast/src/database_impl.dart:1238:7) E/flutter (12986): #18 StoreRefMixin.add (package:sembast/src/store_ref_impl.dart:72:25) E/flutter (12986): #19 ParentDao.insert (package:json_serial_test/data/parent_dao.dart:17:24) E/flutter (12986): <asynchronous suspension> E/flutter (12986): #20
_MyHomePageState.build.<anonymous closure> (package:json_serial_test/main.dart:120:22) E/flutter (12986): #21
_InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14) E/flutter (12986):
#22 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36) E/flutter (12986):
#23 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter (12986): #24 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11) E/flutter (12986): #25 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5) E/flutter (12986): #26 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7) E/flutter (12986): #27 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) E/flutter (12986):
#28 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20) E/flutter (12986):
#29 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter (12986):
#30 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter (12986):
#31 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter (12986):
#32 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter (12986):
#33 _rootRunUnary (dart:async/zone.dart:1138:13) E/flutter (12986): #34 _CustomZone.runUnary (dart:async/zone.dart:1031:19) E/flutter (12986): #35 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7) E/flutter (12986): #36 _invoke1 (dart:ui/hooks.dart:273:10) E/flutter (12986): #37
_dispatchPointerDataPacket (dart:ui/hooks.dart:182:5) E/flutter (12986):
If someone could please assist me in showing what I've missed, done incorrectly, I would greatly appreciate it.
ORIGINAL POST
==============
Should json_serializable convert ALL of a class to JSON, or are there limitations that I am hitting?
I have decided to try and resolve a slew of issues I've caused myself by using json_serializable to create the toJson and fromJson methods needed for working with a NoSQL DB.
If I create a class which includes a field that is a List<Ojb>, the generated code seems to result in JSON for each field of the class but fails to do so for the objects in the list.
Simple example
class Parent {
final int age;
final String name;
List<Child> children;
Parent({this.age, this.name, this.children});
}
class Child {
final int age;
final String name;
Child({this.age, this.name});
}
When I use json_serializable, which seems to work beautifully, I get my toJson and fromJson methods for the above mentioned classes. At first glance, everything looks perfect.
When I attempt to insert a Parent (containing children) into my NoSQL DB, the insert fails to say that the type (referencing the Child object) is not supported - True statement, have no issues with that.
When I step through this via the debugger, here is what I am seeing.
Parent is converted to map
age shows up as key with its value
the name shows up as key with its value
Up to this point, I can see that everything is a map[.. and all looks great
Then we get to the list of Child objects.
This part is not converted to a map but still exists as a list of Child objects, hence the failure of the insert.
Both classes have the jsonSerializable annotation
Both classes are generating the expected code (part of), classes
Everything works perfectly as long as I don't try to use a List<myObject> in one of my classes.
The entire reason one would use a package like json_serializable is to rely on the code that is automatically generated and not have to build it myself. I don't want to have to manually update automatically generated code to resolve this, which is why I have not pasted in the code. If that's the answer, then I'll take a different route.
My question is... is there some configuration that I am missing or possibly doing incorrectly that would allow ALL items within the class to be converted to map/json, even when the fields of a class are not just simple int and string types. I would expect that I could have a class which includes primitives, along with objects, Lists of objects, etc. and everything should generate correctly, or no?
After many trials and rebuilds, I have resolved this issue and everything appears to be working now with my Sembast DB using json_serializable for my model classes. Possibly there were other factors that contributed to my success, but I think the main difference was adding the following parameter to the JSONSerializable annotation of the Parent class.
explicitToJson: true
Here is the code, in the event it helps somebody else out there.
The full explanation you can find here https://flutter.dev/docs/development/data-and-backend/json
#JsonSerializable(explicitToJson: true)
class Parent {
int id;
final String name;
final int age;
List<Child> children;
Job job;
Parent({this.name, this.age, this.children, this.job});
factory Parent.fromJson(Map<String, dynamic> json) => _$ParentFromJson(json);
Map<String, dynamic> toJson() => _$ParentToJson(this);
}

SQFLite (Flutter) Insert fails for Map containing Maps

Can someone confirm if SQFLite supports maps containing maps? I did run across the following post on this site and possibly this is the answer?
Flutter sqflite insert List<String>
In my situation, I have a two model classes I am working with.
House
Dog
House includes a field called pets which is a List
I have a constructor and factory method in each of these classes which takes care of converting to/from map/object as needed for sending to and retrieving information from SQFLite.
Model classes
Dog
class Dog {
final int id;
final String breed;
final String name;
final int age;
Dog({this.id, this.breed, this.name, this.age});
// Used when inserting a row into the db, including the id field
Map<String, dynamic> toMap() {
final map = Map<String, dynamic>();
map['id'] = id;
map['breed'] = breed;
map['name'] = name;
map['age'] = age;
return map;
}
// Used when returning a row from the DB and converting into an object
factory Dog.fromMap(Map<String, dynamic> data) => Dog(
id: data['id'],
breed: data['breed'],
name: data['name'],
age: data['age']
);
}
House
import 'dog.dart';
class House{
final int id;
final String name;
final String color;
final List<Dog> pets;
House({this.id, this.name, this.color, this.pets});
// Will be used when inserting a row into the database
Map<String, dynamic> toMap() {
final map = Map<String, dynamic>();
map['id'] = id;
map['name'] = name;
map['color'] = color;
if (this.pets != null) {
map['pets'] = this.pets.map((pet) => pet.toMap()).toList();
}
return map;
}
// Used when returning a row from the DB and converting into an object
factory House.fromMap(Map<String, dynamic> data) {
return House(
id: data['id'],
name: data['name'],
color: data['color'],
pets: data['pets'] != null
? (data['pets'] as List).map((pet) => Dog.fromMap(pet)).toList()
: null,
);
}
}
Method for inserting a new house
Future<int> addNewHome(House house) async {
// Attempt to add the house to the DB
var client = await database.db;
int result = await client.insert(HomesSchema.tblHomes, house.toMap(), conflictAlgorithm: ConflictAlgorithm.replace);
_homes.add(house);
return result;
}
When I attempt to perform the insert, I get the following error.
E/flutter ( 586): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(java.util.HashMap cannot be cast to java.lang.Integer) sql 'INSERT OR REPLACE INTO homes (id, name, color, pets) VALUES (?, ?, ?, ?)' args [1, Smith, Green, [{name: Mackie, id: 1, breed: Rottweiler, age: 8}, {name: Tanner, id: 2, breed: Mastiff, age: 8}]]}
E/flutter ( 586): #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:12:7)
E/flutter ( 586): <asynchronous suspension>
E/flutter ( 586): #1 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:25:7)
E/flutter ( 586): #2 SqfliteDatabaseMixin.safeInvokeMethod (package:sqflite/src/database_mixin.dart:188:15)
E/flutter ( 586): #3 SqfliteDatabaseMixin.txnRawInsert.<anonymous closure> (package:sqflite/src/database_mixin.dart:363:14)
E/flutter ( 586): #4 SqfliteDatabaseMixin.txnSynchronized.<anonymous closure> (package:sqflite/src/database_mixin.dart:307:22)
E/flutter ( 586): #5 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:32:26)
E/flutter ( 586): #6 SqfliteDatabaseMixin.txnSynchronized (package:sqflite/src/database_mixin.dart:303:43)
E/flutter ( 586): #7 SqfliteDatabaseMixin.txnWriteSynchronized (package:sqflite/src/database_mixin.dart:325:7)
E/flutter ( 586): #8 SqfliteDatabaseMixin.txnRawInsert (package:sqflite/src/database_mixin.dart:362:12)
E/flutter ( 586): #9 SqfliteDatabaseExecutorMixin.rawInsert (package:sqflite/src/database_mixin.dart:49:15)
E/flutter ( 586): #10 SqfliteDatabaseExecutorMixin.insert (package:sqflite/src/database_mixin.dart:59:12)
E/flutter ( 586): #11 Homes.addNewHome (package:search_list_view/providers/homes.dart:19:31)
E/flutter ( 586): <asynchronous suspension>
E/flutter ( 586): #12 _MyAppState.build.<anonymous closure> (package:search_list_view/main.dart:95:26)
E/flutter ( 586): #13 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter ( 586): #14 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter ( 586): #15 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter ( 586): #16 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter ( 586): #17 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter ( 586): #18 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter ( 586): #19 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter ( 586): #20 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter ( 586): #21 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter ( 586): #22 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter ( 586): #23 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter ( 586): #24 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter ( 586): #25 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter ( 586): #26 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter ( 586): #27 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter ( 586): #28 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter ( 586): #29 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter ( 586): #30 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter ( 586): #31 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter ( 586): #32 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter ( 586): #33 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter ( 586): #34 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter ( 586):
If the answer is to change my DB schema so I have a table which joins dogs and houses and then do a custom query to pull back the information I'm after, then fine, I will do that. It doesn't seem too far fetch that a nosql db should be able to handle this... yes/no?
Any assistance would be much appreciated.
Thank you,
Bob
For storing any kind of value in the SQLite Database you can simply serialize the object into a JSON string and later deserialize the object.
lets say you have a class called Menu. (I am using JSON serializable here)
class Menu {
#JsonKey(name: "status")
String status;
#JsonKey(name: "data")
MenuListData menuListData;
Menu(this.status, this.menuListData);
factory Menu.fromJson(Map<String,dynamic>
json)=>_$MenuFromJson(json);
Map<String, dynamic> toJson() => _$MenuToJson(this);
}
Here is how to encode it in JSON and store it(in your bloc).
Menue menuList =
await getIt<LiveMenuRepository>().getMenuResponse(menuPost);
//decode the response to String format
String menuResponseString = jsonEncode(menuList);
//convert the string to Map of <String,dynamic> format
Map<String, dynamic> menuResponseMap = {"menu": menuResponseString};
//store this Map response in to local database
int menuStored = await getIt<LocalMenuRepository>().insertMenuResponseData(menuResponseMap);
Your DB insertion method
Future<int> insertMenuResponseData(Map<String,dynamic> menuResponse) async {
final db = await dbProvider.database;
var result = db.insert(menuTable, menuResponse);
return result;
}
Later retrieve your object using this
final Map<String, dynamic> menuList = await getIt<LocalMenuRepository>().getMenuResponseString();
// if(menuList!=null) {
menuList.forEach((key, value) {
if (key == "menu") {
storedMenu = value ;
}
});
//decode the string back to Map Object
final dynamic menuMap = jsonDecode(storedMenu);
//getting the Menu object using fromJson method
final Menu menuListNameResponse = Menu
.fromJson(menuMap as Map<String,dynamic>);
//getMenuResponseString method in db
Future<Map<String,dynamic>> getMenuResponse() async {
final db = await dbProvider.database;
List<Map<String, dynamic>> result;
result = await db.rawQuery('SELECT * FROM $menuTable');
// print(result[0]);
if (result.length > 0) {
return result[0];
}
return null;
}
Supported types are listed here (num, String or Uint8List): https://github.com/tekartik/sqflite/blob/master/sqflite/doc/supported_types.md
Nested content is not supported, Map and List should be encoded in a supported type for example as json string.