Related
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;
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 .
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.
I want to fetch details of a product by retrieving its ID and by accessing its Id to load the details needed but I keep getting an error that I dont quite understand?
here is my provider data:
class AddCar {
int id;
String name;
String city;
String country;
String currencyT;
double price;
String date;
int sponsNum;
String category;
String company;
String model;
String year;
String engine;
double distanceCovered;
String transmission;
String oilT;
String outColor;
String inColor;
String description;
File image;
PlaceLocation location;
bool isFavorite;
AddCar({
this.id,
this.name,
this.city,
this.country,
this.currencyT,
this.price,
this.date,
this.sponsNum,
this.category,
this.company,
this.model,
this.year,
this.engine,
this.distanceCovered,
this.transmission,
this.oilT,
this.outColor,
this.inColor,
this.description,
this.image,
this.location,
this.isFavorite = false,
});
}
class PlaceLocation {
final double latitude;
final double longitude;
final String address;
const PlaceLocation({
this.address,
this.latitude,
this.longitude,
});
}
Here is how im fetching the data (i have a link to a custome ID that im clicking on to lead to that product):
Future<void> fetchAndSetCarDetails() async {
const url = 'customLink/Detail?Id=204';
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
List<AddCar> loadedCars = [];
extractedData.forEach((carId, carData) {
loadedCars.add(AddCar(
id: int.parse(carId),
name: carData['adTitle'],
sponsNum: carData['adNumber'],
price: carData['adPrice'],
date: carData['adDate'],
model: carData['brandModel'],
year: carData['modelYear'],
distanceCovered: carData['kilometer'],
transmission: carData['gearType'],
oilT: carData['fuelType'],
location: carData['adLocation'][PlaceLocation(
address: carData['adAddress'],
latitude: carData['lath'],
longitude: carData['lang'],
)],
description: carData['adDetails'],
country: carData['country'],
city: carData['cityName'],
category: carData['category'],
company: carData['brand'],
engine: carData['cylinder'],
outColor: carData['exteriorColor'],
inColor: carData['interiorColor'],
));
});
_cars = loadedCars;
print(response.body);
notifyListeners();
}
Here is the print data I get:
I/flutter (13626): {"id":204,"adTitle":null,"adDate":"2019-11-07T11:52:40.0156875","adPrice":25.0,"adNumber":195,"adAddress":"AdAddressssssss","adLocation":{"lath":"40.959028921030104","lang":" 30.992774628906318"},"adDetails":null,"country":227,"cityName":"Stockholm","category":"car child 1","categoryId":7,"brand":"mercedes","brandId":1,"brandModelId":6,"brandModel":"M300","cylinder":"6C","kilometer":300.0,"modelYear":"2010","fuelType":"benz","gearType":"automatic","exteriorColor":"red","interiorColor":"yellow","carType":1,"image":[],"isFavorite":false,
Here is the error I get when I click on the product to access its details:
E/flutter (13626): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Invalid radix-10 number (at character 1)
E/flutter (13626): id
E/flutter (13626): ^
E/flutter (13626):
E/flutter (13626): #0 int._throwFormatException (dart:core-patch/integers_patch.dart:131:5)
E/flutter (13626): #1 int._parseRadix (dart:core-patch/integers_patch.dart:142:16)
E/flutter (13626): #2 int._parse (dart:core-patch/integers_patch.dart:100:12)
E/flutter (13626): #3 int.parse (dart:core-patch/integers_patch.dart:63:12)
E/flutter (13626): #4 Cars.fetchAndSetCarDetails.<anonymous closure>
package:flutter_app/providers/car_provider.dart:88
E/flutter (13626): #5 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (13626): #6 Cars.fetchAndSetCarDetails
package:flutter_app/providers/car_provider.dart:86
E/flutter (13626): <asynchronous suspension>
E/flutter (13626): #7 _MyCarDetailsState.initState.<anonymous closure>
package:flutter_app/details/car_details.dart:23
E/flutter (13626): #8 _rootRunUnary (dart:async/zone.dart:1132:38)
E/flutter (13626): #9 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
E/flutter (13626): #10 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
E/flutter (13626): #11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
E/flutter (13626): #12 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
E/flutter (13626): #13 Future._complete (dart:async/future_impl.dart:512:7)
E/flutter (13626): #14 new Future.delayed.<anonymous closure> (dart:async/future.dart:313:16)
E/flutter (13626): #15 _rootRun (dart:async/zone.dart:1120:38)
E/flutter (13626): #16 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (13626): #17 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
E/flutter (13626): #18 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:963:23)
E/flutter (13626): #19 _rootRun (dart:async/zone.dart:1124:13)
E/flutter (13626): #20 _CustomZone.run (dart:async/zone.dart:1021:19)
E/flutter (13626): #21 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:947:23)
E/flutter (13626): #22 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:21:15)
E/flutter (13626): #23 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
E/flutter (13626): #24 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
E/flutter (13626): #25 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:172:12)
E/flutter (13626):
You have several problems.
1 - your forEach closure looks like you are expecting the JSON to include a list of cars that you are going to add to loadedCars but it does not - there's just one car. That's why extractedData is a Map<String, dynamic> not a List<Map<String, dynamic>>.
2 - that means that the forEach closures is iterating over the members of the map so gets called once with carId='id' and carData=204 and then again with carId='adPrice' and carData=25.0 etc. This is clearly not what you're expecting! The exception happens when you try to parse 'id' into an int.
Given that there's only one car in your current json you can dispense with the loop. You should extract that one car like:
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
var theOneCar = AddCar(
id: extractedData['id'], // no need for parse either - id is already an int
name: extractedData['adTitle'],
// etc
// etc
print (theOneCar);
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);