0

我在flutter项目中的http-get json数据无法获取数据,我用邮递员测试过,它成功了,但是在flutter中它没有或者因为我不知道如何输入。我已经尝试不同的方法,但没有一个成功!

谁能帮我?!如果有人需要更多信息,我会给你!

Flutter 调试控制台:https ://i.stack.imgur.com/IGZDP.png

Postman 测试成功:https ://i.stack.imgur.com/khj9a.png

邮递员测试失败: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);
  }
}

上课

class Get {

  final String id;

  Get({
    this.id,
    });

  factory Get.fromJson(Map<String, dynamic> json) {
    return Get(
        id: json['id_machdien'].toString()
    );
  }
}

主要的

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)),
                  ),
                ],
              ),
            ),
          )
        );
      }
}
4

1 回答 1

0

让我纠正你,

  1. 您无法通过GEThttp 请求发送正文,因此请将 API 更改为POSTid_machdien作为查询参数发送。
  2. 内部class Get您正在尝试解析json['id_machdien'],但在您的响应中没有id_machdien,它必须是响应的项目​​之一(例如:id,trang_thai_app)。
于 2020-06-28T21:06:00.393 回答