问题
I am trying to fetch data from My site link: http://mrmatjar.com/kaka/dataaza.php
Here is my code
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:mrmatjar_afflite/shopobj.dart';
class Operations{
static Future<List<ShopObj>> loly() async{
List<ShopObj> ak= new List<ShopObj>();
var res = await http.get(Uri.encodeFull("https://mrmatjar.com/kaka/dataaza"),headers: {"Accept":"application/json"});
print(res);
var v = json.decode(x.body);
for(var h in v){
ak.add(new ShopObj(h['title'], h['cost'], h['earn'], h['image']));
}
return ak;
}
}
But it is not working. when I run it the Web app Breaks and when I use Break point it shows file call by blinding.dart
回答1:
Welcome to stack overflow :).
First:
I see some typo error in your code.
var v = json.decode(x.body);
should be
var v = json.decode(res.body);
Second:
Once you fix the above you might face Cross Origin Request(CORS) error which may be because you have not set this up in your server. Especially if your flutter web application is not running in the same domain as the server where you api is running. Even if its on the same machine, you will have to allow the request from certain domain and ports. If you are not aware of CORS you can read here.
Third:
As I see you are processing the response without checking the statusCode of the response it would still lead to an error when you try to decode the response.
I have a simple running example here based on the DOGs public api.
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
class HttpRequestDemo extends StatefulWidget {
@override
_HttpRequestDemoState createState() => _HttpRequestDemoState();
}
class _HttpRequestDemoState extends State<HttpRequestDemo> {
String imageUrl = "";
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Center(
child: Image.network(
imageUrl,
height: MediaQuery.of(context).size.height / 3,
width: MediaQuery.of(context).size.width / 3,
),
),
FloatingActionButton(
child: Icon(Icons.cloud_download),
onPressed: () {
fetchData();
},
)
],
));
}
fetchData() async {
final res = await http.get("https://dog.ceo/api/breeds/image/random");
if (res.statusCode == 200) {
var v = json.decode(res.body);
setState(() {
imageUrl = v['message'];
});
}
}
}
This app will show a new dog photo every time you press the floating action button as shown below which is based on the response from the api.
来源:https://stackoverflow.com/questions/58557173/how-to-make-http-request-work-in-flutter-web