Flutter - 'List<dynamic>' is not a subtype of type - flutter

I've been looking for a WordPress + Flutter App integration and found a good one, but I got this error message:
I'm pretty this is a simple error, but I'm more into a design guy than a dev, so would be great if some of you give me some tip about it. Thanks in advance!
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../config.dart';
import '../model/post_entity.dart';
class WpApi {
static const String BASE_URL = URL + REST_URL_PREFIX + '/wp/v2/';
static Future<List<PostEntity>> getPostsList(
{int category = 0, int page = 1}) async {
var posts = [];
try {
String extra = category != 0 ? '&categories=' + '$category' : '';
dynamic response = await http.get(Uri.parse(BASE_URL +
'''
posts?_embed&page=$page''' +
extra));
dynamic json = jsonDecode(response.body);
(json as List).forEach((v) {
posts.add(PostEntity.fromJson(v));
});
} catch (e) {
//TODO Handle No Internet Response
}
return posts;
}
static Future<List<PostCategory>> getCategoriesList({int page = 1}) async {
List<PostCategory> categories = [];
try {
dynamic response = await http.get(Uri.parse(BASE_URL +
'categories?orderby=count&order=desc&per_page=15&page=$page'));
dynamic json = jsonDecode(response.body);
(json as List).forEach((v) {
categories.add(PostCategory.fromJson(v));
});
} catch (e) {
//TODO Handle No Internet Response
}
return categories;
}
}
The error is on the return posts;
Exception has occurred.
_TypeError (type 'List<dynamic>' is not a subtype of type 'FutureOr<List<PostEntity>>')

change var posts = [] to List<PostEntity> posts = []
static Future<List<PostEntity>> getPostsList(
{int category = 0, int page = 1}) async {
List<PostEntity> posts = []; //<-- change var posts = [] to List<PostEntity> posts = []
try { ...

Related

Flutter - loop not working while parsing json

I am trying to create model and parse json data from api
for that i created the model class you can see below
class FeatureModel {
String? PlanFeatures;
bool? FeatureStatus;
FeatureModel({this.PlanFeatures, this.FeatureStatus});
FeatureModel.fromJson(parsonJson) {
PlanFeatures = parsonJson['PlanFeatures'];
FeatureStatus = parsonJson['FeatureStatus'];
}
}
now i am trying to parse json with the help of loop
let me show you my method
List<FeatureModel> featureModel = [];
Uri featureAPI = Uri.parse(
planFeatureApi);
apiCall() async {
try {
http.Response response = await http.get(featureAPI);
// print(response.statusCode);
if (response.statusCode == 200) {
var decode = json.decode(response.body);
print(decode);
for (var i = 0; i < decode.length; i++) {
print(i);
featureModel.add(
FeatureModel.fromJson(decode[i]),
);
}
}
} catch (e) {}
}
I am calling it here
onPressed: () async{
await apiCall();
}
but the problem is here
loop is not working while parsing data
in that particular code i remains on 0 only
when i removes featureModel.add( FeatureModel.fromJson(decode[i]), ); i started increaing till 10
please let me know if i am making any mistake or what
thanks in advance
Here is the sample of api respone
[{"PlanFeatures":"Video Link Sharing","FeatureStatus":"true"},{"PlanFeatures":"Email \u0026amp; Telephonic Support","FeatureStatus":"true"},{"PlanFeatures":"Remove Pixeshare Branding","FeatureStatus":"false"},{"PlanFeatures":"Add Custom logo on uploaded photos","FeatureStatus":"false"},{"PlanFeatures":"Get Visitor Info","FeatureStatus":"false"},{"PlanFeatures":"Mobile Apps","FeatureStatus":"false"},{"PlanFeatures":"Send Questionnaries","FeatureStatus":"false"},{"PlanFeatures":"Create \u0026amp; Send Quotation","FeatureStatus":"false"},{"PlanFeatures":"Online Digital Album Sharing","FeatureStatus":"false"},{"PlanFeatures":"Analytics","FeatureStatus":"false"}]
thanks
I found many errors, first, the fromJson is not a factory constructor and doesn't return a class instance from the JSON.
the second one is that the bool values from the sample you added are String not a bool so we need to check over it.
try changing your model class to this:
class FeatureModel {
String? PlanFeatures;
bool? FeatureStatus;
FeatureModel({this.PlanFeatures, this.FeatureStatus});
factory FeatureModel.fromJson(parsonJson) {
return FeatureModel(
PlanFeatures: parsonJson['PlanFeatures'],
FeatureStatus: parsonJson['FeatureStatus'] == "false" ? false : true,
);
}
}

understanding tflite input output from tflite model

i'm following some online courses and i didn't understand why im always got
I/flutter (10799): Bad state: failed precondition and
E/SurfaceSyncer(10799): Failed to find sync for id=0
here is my code
import 'dart:io';
import 'package:tflite_flutter/tflite_flutter.dart';
import 'package:tflite_flutter_helper/tflite_flutter_helper.dart';
class Classifier {
Classifier();
classifyImage(var image) async {
var inputImage = File(image.path);
ImageProcessor imageProcessor = ImageProcessorBuilder()
.add(ResizeOp(456,456, ResizeMethod.BILINEAR))
.add(NormalizeOp(0,255))
.build();
TensorImage tensorImage = TensorImage.fromFile(inputImage);
tensorImage = imageProcessor.process(tensorImage);
TensorBuffer probabilityBuffer =
TensorBuffer.createFixedSize(<int>[1, 120], TfLiteType.float32);
try {
Interpreter interpreter = await Interpreter.fromAsset("model2.tflite");
interpreter.run(tensorImage.buffer, probabilityBuffer.buffer);
} catch(e) {
print(e);
}
List<String> labels = await FileUtil.loadLabels("assets/data2.txt");
SequentialProcessor<TensorBuffer> probabilityProcessor =
TensorProcessorBuilder().build();
TensorLabel tensorLabel = TensorLabel.fromList(
labels, probabilityProcessor.process(probabilityBuffer));
Map labeledProb = tensorLabel.getMapWithFloatValue();
double highestProb = 0;
String dogBreed = "";
labeledProb.forEach((breed, probability) {
if (probability*100 > highestProb) {
highestProb = probability*100;
dogBreed = breed;
}
});
var outputProb = highestProb.toStringAsFixed(1);
print(dogBreed + "%" + outputProb);
return [dogBreed, outputProb];
}
}
the model
the error

How to assign values from an API call to a variable in flutter

I have the following method which is use dto verify a ticket/token
var ticketArray = ticket.split('|');
//First check to verify token using simple versification algo
if (widget.eventID.toString() != (ticketArray[0])) {
setState(() {
ticketMainMsg = 'This QR code is NOT VALID';
ticketsubtitle = ticketArray.length != 2
? 'The QR code is fake'
: 'QR code could belong to another event';
ticketStatus = false;
return;
});
}
//Make API call
ticketModel = HttpVerifyTicketPost(
eventId: widget.eventID,
ticket: ticket,
scannerId: widget.scannerId,
).verifyTicket();
}
From above, you can see I do a very simple check on the qr code/token if this simple step fails, I don't bother making an API call and I set the state based on these values.
However if the check passes, then I proceed to make an API call to the server to fully verify the token/code.
My issue is I am struggling to now assign the values from the API call to the ticketStatus, ticketMainMsgand ticketsubtitle parameters. Can anyone helo shed some light. I am quite new to flutter but I am aware that the TicketModel will be a type of Future. My background is PHP so forgive me!
EDIT: The httpVerifyTicket Class
class HttpVerifyTicketPost {
String ticket;
int someId;
int anotherId;
HttpVerifyTicketPost(
{required this.ticket, required this.someId, required this.anotherId});
String verifyURL =
'https://api.com/api/vendors/scanner/native/verify/ticket';
Future<TicketModel> verifyTicket() async {
var storage = await SharedPreferences.getInstance();
var code= storage.getString('code');
var client = http.Client();
var ticketModel = null;
var body = {
'ticket': ticket,
'scanner': scannerCode,
'someId': someId,
'anotherId': anotherId
};
try {
var url = Uri.parse(verifyURL);
var res = await client.post(url, body: jsonEncode(body));
if (res.statusCode == 200) {
var jsonString = res.body;
var jsonMap = json.decode(jsonString);
ticketModel = TicketModel.fromJson(jsonMap);
}
return ticketModel;
} catch (Exception) {
return ticketModel;
}
}
}
Try this please
HttpVerifyTicketPost(
eventId: widget.eventID,
ticket: ticket,
scannerId: widget.scannerId,
).verifyTicket().then((value){setState(() {
ticketModel=value
});
});
I don't quite understand what you want to achieve, but maybe you need to add an asynchronous method like
ticketModel = await HttpVerifyTicketPost( //add await eventId: widget.eventID, ticket: ticket, scannerId: widget.scannerId, ).verifyTicket();
and you must add async like Future Foo() async {your code...}

for-in using dart Exception: type '_InternalLinkedHashMap<String, dynamic>

i am not familiar using For-in using dart, i use similar code in ts or angular and it work as expected, but get lost when use flutter and need more guidance to use it.
Future<int> datetransaction(String mid) async {
var url = 'http://callsomehttp.com/$mid';
var res = await http.get(url);
if (res.statusCode == 200) {
var dtpoint = json.decode(res.body);
var availabledate = [];
for (var key in dtpoint) {
var dateEle = dtpoint[key]['Balance']['date'];
if (availabledate.indexOf(dateEle) == -1) {
availabledate.add(dateEle);
totalSpending(dateEle, mid);
}
}
print('available data $availabledate');
var spen = totalTransaction.reduce((a, b) => a + b);
return spen ;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}");
}
}
Future totalSpending (String date, String ckey) async {
var total = 0 ;
final String url = 'http://otherurl.com/$date';
final res = await http.get(url);
if (res.statusCode == 200) {
var pdata = json.decode(res.body);
for (var key in pdata) {
var el = pdata[key]['Transaction']['customer_code'];
var ttl = int.parse(pdata[key]['Transaction']['total']);
if( el == ckey) {
totalTransaction.add(ttl);
total = ttl ;
}
}
return total ;
} else {
throw Exception(
"Request to $url failed with status ${res.statusCode}: ${res.body}");
}
}
any guidance to give a light , or other way to get the result really appreciate, thank you

How can I make sure a method waits for a http response instead of returning null in Dart?

I am trying to write a little command line library in Dart to work with the Facebook API. I have a class 'fbuser' which gets the auth-token and user-id as properties and has a method 'groupIds' which should return a List with all IDs of groups from the user.
When I call the method it returns null altough the two possbile returns are called after the http response. What did I do wrong?
Here is my code:
import 'dart:convert'; //used to convert json
import 'package:http/http.dart' as http; //for the http requests
//config
final fbBaseUri = "https://graph.facebook.com/v2.1";
final fbAppID = "XXX";
final fbAppSecret = "XXY";
class fbuser {
int fbid;
String accessToken;
fbuser(this.fbid, this.accessToken); //constructor for the object
groupIds(){ //method to get a list of group IDs
var url = "$fbBaseUri/me/groups?access_token=$accessToken"; //URL for the API request
http.get(url).then((response) {
//once the response is here either process it or return an error
print ('response received');
if (response.statusCode == 200) {
var json = JSON.decode(response.body);
List groups=[];
for (int i = 0; i<json['data'].length; i++) {
groups.add(json['data'][i]['id']);
}
print(groups.length.toString()+ " Gruppen gefunden");
return groups; //return the list of IDs
} else {
print("Response status: ${response.statusCode}");
return (['error']); //return a list with an error element
}
});
}
}
void main() {
var usr = new fbuser(123, 'XYY'); //construct user
print(usr.groupIds()); //call method to get the IDs
}
At the moment the output is:
Observatory listening on http://127.0.0.1:56918
null
response received
174 Gruppen gefunden
The method runs the http request but it returns null immediately.
(I started programming this summer. Thanks for your help.)
return http.get(url) // add return
void main() {
var usr = new fbuser(123, 'XYY'); //construct user
usr.groupIds().then((x) => print(x)); //call method to get the IDs
// or
usr.groupIds().then(print); //call method to get the IDs
}