flutter:how can i received value as same as mysql database? - mysql

Hi I am try use mysql database in my flutter app...but till now fetch all data as string..what changes i have to done in my below code to received as data as my database...
in below code verify is a number and i want to received as number till time i received verify as string ....please help me ............
FetchJSON() async {
var Response = await http.get(
"http://192.168.42.107/my_payment/getdata.php",
headers: {"Accept": "application/json"},
);
if (Response.statusCode == 200) {
String responseBody = Response.body;
var responseJSON = json.decode(responseBody);
abc = responseJSON['username'];
verify = responseJSON['verified'];
setState(() {
print('UI Updated');
});
} else {
print('Something went wrong. \nResponse Code : ${Response.statusCode}');
}
}

So essentially you want "strongly typed" data for your http response, you have to define such data yourself. Normally people do something like this:
class MyData {
final String username;
final bool verified; // assume this should be a boolean
MyData.fromJson(dynamic json)
: username = json['username'],
verified = json['verified'] == 1; // assume you get back a number for verified
}
Then you can convert your responseJSON to MyData and carry on from there.

Related

Flutter/Dart Error - NoSuchMethodError (NoSuchMethodError: Class 'String' has no instance method 'map'

I receive an error that has something to do with JSON receiver inside Flutter/Dart.
Had to share in a docs file since the full json response is pretty long. It had like 15 columns error log
Detail Class
class Detail {
String kodkursus;
String namakursus;
String kursusdescription;
Detail(
{required this.kodkursus,
required this.namakursus,
required this.kursusdescription});
factory Detail.fromJson(Map<String, dynamic> json) {
return Detail(
kodkursus: json['crs_code'] as String,
namakursus: json['crs_title_bm'] as String,
kursusdescription: json['crs_description_bm'] as String,
);
}
}
Code
Future<dynamic> generateDetailList() async {
var url = 'http://10.0.2.2:81/login_testing/kursus_display.php';
var data = {'usr_id': widget.username2};
var response = await http.post(url, body: json.encode(data));
var list = json.decode(json.encode(response.body));
List<Detail> _detail =
list.map<Detail>((json) => Detail.fromJson(json)).toList();
detailDataSource = DetailDataSource(_detail);
return _detail;
}
Return (full error log)
NoSuchMethodError (NoSuchMethodError: Class 'String' has no instance method 'map'...
I fairly new to this Flutter/Dart but I got the feeling it had something to do with the json, it just I cant get my head over it
Please check your API response because this error generates when there are difference in datatype.
this error says your app response it in String and you are accessing this as map so please check your API response or
try to replace this :
var list = json.decode(json.encode(response.body));
with :
var list = json.decode(response.body);
because json.encode method encodes all list data and that values datatype is String so it gives error.
Replace your function generateDetailList as such:
Future<List<Detail>?> generateDetailList() async {
Uri url = Uri.parse('http://10.0.2.2:81/login_testing/kursus_display.php');
Map<String, String> data = {'usr_id': 'widget.username2'};
http.Response response = await http.post(url, body: json.encode(data));
// var list = json.decode(json.encode(response.body));
var responseMap = await jsonDecode(response.body);
if (response.statusCode == 200) {
List<Detail> _details =
responseMap.map<Detail>((x) => Detail.fromJson(x)).toList();
return _details;
} else {
return null;
}
}
And try not to use var everywhere.

Both urls provides same json data but flutter can only parse one

Despite both urls showing the same json data, my code only works with the url "https://5f210aa9daa42f001666535e.mockapi.io/api/products" but the other. Wonder why and been struggling for 3 nights for this:
Future<List<Product>> fetchProducts() async {
const String apiUrl =
"http://10.0.2.2:8000/api/book";
//"https://5f210aa9daa42f001666535e.mockapi.io/api/products";
final response = await http.get(apiUrl);[enter image description here][1]
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
List<Product> products = (json.decode(response.body) as List)
.map((data) => Product.fromJson(data))
.toList();
// Return list of products
return products;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load');
}
I think, you try this way. Using package: dio
https://pub.dev/packages/dio

Flutter - Multiple HTTP Requests to the same JSON

I have this API where go to fetch data.
For each "date" I have a JSON Object.
What I want to do is fetch objects from let's say 5 years and get them on the same final JSON http response.
So I don't have to display only a day at the time.
Future<List<Schedule>> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date'; //the $date would be e.g. 2010, 2011, 2012, ...
final response = await http.get(url);
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((data) {
return new Schedule.fromJson(data);
}).toList();
}
}
What is the best way to implement this?
If your API returns just a single Schedule object, you need to modify your method to get a single element.
Future<Schedule> getFromEspnSchedule(String sport) async {
final url = 'http://myserver.com/api/$date';
final response = await http.get(url);
if (response.statusCode == 200) {
return Schedule.fromJson(json.decode(response.body));
} else {
// make sure you return API error here
}
}
After you do this, you can go ahead and chain this into multiple calls made at the same time to achieve getting the data faster:
List<Schedule> responseList = await Future.wait([
getFromEspnSchedule('football'),
getFromEspnSchedule('volleyball'),
getFromEspnSchedule('basketball'),
getFromEspnSchedule('chess'),
]);
// responseList objects are listed the same way they are called above.
Schedule footballSchedule = responseList[0];
Schedule volleyballSchedule = responseList[1];
Schedule basketballSchedule = responseList[2];
Schedule chessSchedule = responseList[3];

Flutter run -d chrome not fetch json url

I've create Board List function by fetching json url via flutter
First I've crated into window exe it works properly like this below
But when I want to production via chrome or android
It is not working as this below
This is my code to fetch json url what did I do wrong?
Future<List<Schedule>> fetchBoardList() async {
final response = await http.get('http://192.168.10.109:8888/mcschedule/machine/');
String logResponse = response.statusCode.toString();
if (response.statusCode == 200){
//print('ResponseStatusCode: $logResponse'); // Check Status Code = 200
//print('ResponseBody: ' + response.body); // Read Data in Array
List<dynamic> responseJson = json.decode(response.body);
return responseJson.map((e) => new Schedule.fromJson(e)).toList();
} else {
throw Exception('error :(');
}
}

Flutter Can't Convert String To Double

Hello everyone i have a simple function that will receive double from my server and then it should parse this decimal to double and add it to the total amount variable
for (int i = 0; i < purchase.length; i++){
currentTotalPrice = currentTotalPrice + purchase[i]['total_price'];
}
the thing is i am receiving the total price which is a decimal in the database in a String format and when i try to do something like (purchase[i]['total_price']).toDouble(); the compiler throws
Class 'String' has no instance method 'toDouble'.
Receiver: "15.00"
Tried calling: toDouble()
i don't know why in other parts of my code it worked correctly
this is how i am receiving the data
Future<List> _fetchPurchases() async {
final prefs = await SharedPreferences.getInstance();
String accessToken = prefs.getString("accessToken");
final response = await http.get(
'$webSiteUrl/api/admin/purchases/${article['id']}/$_billNumber',
headers: <String, String>{
'Content-Type': 'application/json;',
'Authorization': 'Bearer $accessToken',
},
);
if(response.statusCode == 200){
List purchases = json.decode(response.body);
return purchases;
}else{
return showErrorMessage(context);
}
}
Note: I am Aware of the Constructor solution where you create a class and then factory the data to custom dart object but for some circumstances i can't do that unless i refactor a very large part of the code so if there is a direct way like toDouble() method it would be the best solution
Indeed toDouble does not exist in the String class, but if you must use it, you can create an extension and import it, something like this
extension NumberParsing on String {
double toDouble() {
return double.parse(this);
}
}
check this gist https://gist.github.com/fcontreras/d5095da7daa0ce24e0f3cb157b91e97f