Remove column name after get data - flutter

So when I get some string data from database I'm using this method
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res = req;
});
}
then im using method cetak() like this
cetak("SELECT CUST_NAME FROM ts_custxm WHERE CUST_CODE = '$custCode'");
But when im trying to display the res using Text(res)
it show [{"CUST_NAME":"MY NAME"}]
any idea how to make res only show MY NAME without show its column name?

You first need to convert by jsonDecode() or json.decode():
var req = jsonDecode(req)
setState(() {
res = req;
});
and then access to your data by:
res[0]["CUST_NAME"].toString()

You are getting result of a query in res variable. As a result of a query is an array of objects.
in your case : [{"CUST_NAME":"MY NAME"}]
so get MY NAME you should use res[0]["CUST_NAME"].toString().
Hope this will help!

Related

Unable to sort "This expression has a type of 'void' so its value can't be used."

im new to flutter, im unable to sort List and get the 'This expression has a type of 'void' so its value can't be used.' error
List getSnack = [];
var sortSnack = [];
Future _getSnacks() async {
var response = await http.get(Uri.parse(url));
List decode = jsonDecode(response.body);
setState(() {
getSnack = decode
.where((snack) => snack["snack_type"]
.toLowerCase()
.contains(defaultType.toLowerCase()))
.toList();
});
sortSnack = getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));
}
i want to sort the "snack" which contains the name of the snack from a-z and vice versa
i have tried this and still doesn't work
List getSnack = [];
var sortSnack = getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));;
Future _getSnacks() async {
var response = await http.get(Uri.parse(url));
List decode = jsonDecode(response.body);
// List filter = decode;
setState(() {
getSnack = decode
.where((snack) => snack["snack_type"]
.toLowerCase()
.contains(defaultType.toLowerCase()))
.toList();
});
}
the error says 'The instance member 'getSnack' can't be accessed in an initializer.'
Sort() apply its sorting to the list, it's not returning any value (void). What you should write instead is:
getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));
var sortSnack = getSnack;
or use the cascade operator if you want this on one line:
var sortSnack = getSnack..sort((a, b) => a["snack"].compareTo(b["snack"]));
Be aware that in both cases sortSnack will be a shallow copy of getSnack. Any change in SortSnack will be reflected in getSnack.
This is a void function you can't use it or assign it to another variable. you just have to use this as an expression and use your original List after applying sort function.
Remove the commented part and just apply the function which is void.your original list (getSnack) will be updated itself.
//var sortSnack = ...
getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));;

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...}

can't fetching json in flutter

It Work When String is used BUT Can't fetch String Object.
it Works :-
String? url = "https://api.thedogapi.com/v1/images/search";
var raw = await http.get(Uri.parse(url));
it is Not working :-
getInfoFromSharedPref() async {
dogApiLink = await SharedPreferenceHelper().getDogName();
}
var raw = await http.get(Uri.parse('${dogApiLink}'));
where dogApiLink is String and having Link But Not working.
bro it's direct .. I just don't understand if the return from the shared preferences that you are taking is a link ???? if it's only dog name then that's your problem.. if it's a legitimate link then
{
String uri = "The link";
var response = await http.get(Uri.parse(uri), "The headers of the api").then(){
// The task you wanna perform.
}
}

Showing json data upon selecting item from suggestion list

I want to fetch and show corresponding player's data when their name is selected from the suggestion list. I have AutoCompleteTextField widget using which player's name is typed and selected from the list, as below:
Current issue I am facing is, when player is searched and selected, then I get null value back at first, as below:
But when I tap in the search field and select the same player again from suggestion list, then the api call is made and data is shown properly, as below:
Current code is, on itemSubmitted parameter of AutoCompleteTextfield, I am making call to the method that shows the data inside setState(), as below:
itemSubmitted: (item) {
setState(() {
searchTextField.textField.controller.text = item.name;
textInput = true;
showData();
});
},
Inside showData(), I am parsing the json per input search in the field and if player data is found, I am making another call inside same method to fetch the data, as below:
showData() {
String input = searchTextField.textField.controller.text.toLowerCase();
found = false;
for (var i = 0; i < PlayerViewModel.players.length; i++) {
if (PlayerViewModel.players[i].name.toLowerCase() == input) {
players = PlayerViewModel.players[i];
found = true;
break;
}
}
if (found) {
fetchJson(players.pid);
}
}
void fetchJson(int pid) async {
var response = await http.get(
'http://cricapi.com/api/playerStats?apikey=<apiKey>&pid=$pid');
if (response.statusCode == 200) {
String responseBody = response.body;
var responseJson = jsonDecode(responseBody);
name = responseJson['name'];
playingRole = responseJson['playingRole'];
battingStyle = responseJson['battingStyle'];
country = responseJson['country'];
imageURL = responseJson['imageURL'];
data = responseJson;
The data is fetched properly but not firing at first attempt when I select player from list, but only at second attempt when I select the player again from the list. And this happens for every subsequent player search.
What am I missing here ? How to fetch and show the data as soon as the player name is selected from suggestion list ?
You should implement a FutureBuilder where the future is fetchJson() which returns data. Also try to see what it returns.
if (found) {
fetchJson(players.pid).then(print);
}

how to transform a Future<dynamic> to string in dart:flutter

I’m using some sqflite to do a query on a database, and extract a specific name of a table, for example: I have 3 names, Roberto, Ricardo and Andres, and I want to obtain only the name of Roberto, so this is what im doing:
loginLogic() async {
var X = 'Roberto';
final db = await database;
List<Map> result = await db.rawQuery('SELECT * FROM Usuario WHERE username=?', [X]);
So now, I want to compare this result with another one to do an "if" function, just like this:
if(result==X){
return 1;
} else {
return 0;
}
But this is what flutter says:
List<Map<dynamic, dynamic>> result
Equality operator '==' invocation with references of unrelated
And the Debug console:
type 'Future<dynamic>' is not a subtype of type 'int'
So I need a way to compare the value that results from the list of users with the string with the variable I declarated 'X'.
Try using the reference of this problem
This is what I’ve tried:
loginLogicpar() async {
var X = 'Giova';
final db = await database;
final result = await db.rawQuery('SELECT * FROM Usuario WHERE username=?', [X]);
return result;
}
loginLogic() async {
var X = 'Giova';
final user = await loginLogicpar();
if(user==X){
return 1;
}
return 0;
}
And returns the exact same result: type 'Future' is not a subtype of type 'int'
Added the code so you can replicate it, just be sure you have sqflite on your depenencies.
It was a hell of a road, but i made it with the help of you all, but the final piece was #mutantkeyboard, what i was getting was a list of the different elements from the table of Sqflite, but after converting it with a variable and the .first function i get to transform it to another variables! here's what i made:
loginLogic() async {
final db = await database;
var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Usuario");
int id = table.last["id"];
for(var i=1; i<id; i++){
var result = await db.rawQuery('SELECT username FROM Usuario WHERE id=?', [i]);
String Y = result.first["username"];
if(Y=='Roberto'){
return 1;
}
}
return 0;
}
if you want to compare it with another variable outside, for example, an auth for a local-login (that's what i was doing, just for educational purpose, i'll NEVER suggest you to put your usernames and passwords inside your local software) and compare the textfield.text with the table, then you can modify the code to something like this:
loginLogic(String field) async {
final db = await database;
var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Usuario");
int id = table.last["id"];
for(var i=1; i<id; i++){
var result = await db.rawQuery('SELECT username FROM Usuario WHERE id=?', [i]);
String Y = result.first["username"];
if(Y==field){
return 1;
}
}
return 0;
}