Flutter - Http get json data
459
Let me correct you,
- You can't send body with
GET
http request, so change the API toPOST
or sendid_machdien
as Query parameter. - Inside
class Get
You are trying to parsejson['id_machdien']
but in your response there is noid_machdien
, it must be one of the response's item (like : id, trang_thai_app).
Author by
Alars
Updated on December 22, 2022Comments
-
Alars over 1 year
My http-get json data in flutter project it can't get the data, I've tested with postman and it's succeed, but in flutter it's didn't or because of me don't know how to put in. I've try different ways but none are succeed!
Can anyone help me?! If anyone need more info, I'll give it to you!
Flutter Debug Console: https://i.stack.imgur.com/IGZDP.png
Postman tested succeed: https://i.stack.imgur.com/khj9a.png
Postman tested failed: https://i.stack.imgur.com/Ee6tU.png
Future<Get> getdata(String id) async { final username = 'test'; final password = '9876543'; final credentials = '$username:$password'; final stringToBase64 = utf8.fuse(base64); final encodedCredentials = stringToBase64.encode(credentials); final String apiUrl = "http://sv.com/api/values/"; Map<String, String> headers = { HttpHeaders.contentTypeHeader: "application/json; charset=utf-8", HttpHeaders.authorizationHeader: "Basic $encodedCredentials", }; final response = await http.get(apiUrl,headers: headers); if (response.statusCode == 200) { final String responseString = response.body; print(response.statusCode); print(responseString); return Get.fromJson(json.decode(response.body)); } else { print(response.statusCode); print(response.body); } }
Get class
class Get { final String id; Get({ this.id, }); factory Get.fromJson(Map<String, dynamic> json) { return Get( id: json['id_machdien'].toString() ); } }
Main
class _MyHomePageState extends State<MyHomePage> { Get _dataget; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text(widget.title), ), body:Center( child: Column( children: <Widget> [ RaisedButton( onPressed: () async{ final Get dataget = await getdata(id); setState(() { _dataget = dataget; }); }, child: Text('Mở',style: TextStyle(fontSize: 15)), ), ], ), ), ) ); } }
-
Alars almost 4 yearsi wan't to get data on sql server through my flutter api not post, and how i send '''id_machdien''' as Query parameter? Can you write it down, i not good at this. In my response there is no id_machdien(so how can i fix this), and yes it's the one for the response's item (like : id, trang_thai_app)
-
ikerfah almost 4 yearsYou can use this sv.com/api/values/?id_machdien=value_here
-
ikerfah almost 4 yearsYou need to make some changes to your API too, Can you share the code of your backend?