开发者社区 问答 正文

JSON无法在FLUTTER中检索数据

这是我扑扑的代码

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
            title: Text('JSON ListView in Flutter')
        ),
        body: JsonListView(),
      ),
    );
  }
}

class Fruitdata {
  String id;
  String fName;

  Fruitdata({
    this.id,
    this.fName,
  });

  factory Fruitdata.fromJson(Map<String, dynamic> json) {
    return Fruitdata(
      id: json['id'],
      fName: json['name'],
    //  fName: json['fruit_name'],
    );
  }
}

class JsonListView extends StatefulWidget {

  JsonListViewWidget createState() => JsonListViewWidget();

}

class JsonListViewWidget extends State<JsonListView> {

  final String uri = 'http://sha-way.freeweb.pk/index4.php';
//final String uri = 'https://flutter-examples.000webhostapp.com/fruites_list_file.php';

  Future<List<Fruitdata>> fetchFruits() async {

    var response = await http.get(uri);

    if (response.statusCode == 200) {

      final items = json.decode(response.body).cast<Map<String, dynamic>>();

      List<Fruitdata> listOfFruits = items.map<Fruitdata>((json) {
        return Fruitdata.fromJson(json);
      }).toList();

      return listOfFruits;
    }
    else {
      throw Exception('Failed to load data.');
    }

  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Fruitdata>>(
      future: fetchFruits(),
      builder: (context, snapshot) {

        if (!snapshot.hasData) return Center(
            child: CircularProgressIndicator()
        );

        return ListView(
          children: snapshot.data
              .map((data) => ListTile(
            title: Text(data.fName),
            onTap: (){print(data.fName);},
          ))
              .toList(),
        );
      },
    );
  }
}

我认为我制作的json非常完美...您可以在代码中注意到我对示例进行了注释... // fName:json ['fruit_name'],并且此//最终字符串uri =' https:// flutter- examples.000webhostapp.com/fruites_list_file.php ';

现在它从我有评论的那部分中检索数据很好,而不是从我在代码中的JSON中检索数据。我注意到的事情可能是因为示例链接包含https://,而我的代码中包含http://是我做错了这件事,还是还有其他需要帮助的地方使我感到困惑

展开
收起
社区秘书 2019-11-27 16:26:21 780 分享 版权
阿里云 AI 助理回答

从您的描述来看,问题可能不在于HTTP(http://)与HTTPS(https://)的差异,因为现代网络客户端如Flutter默认是支持与HTTP服务器通信的。不过,确实很多现代Web服务和API更倾向于使用HTTPS以确保数据传输的安全性。

您遇到的问题可能是由以下几个原因造成的:

  1. 服务器端配置或路径问题:请确认您的服务器(http://sha-way.freeweb.pk/index4.php)是否正确配置并能够响应请求。有时候,免费托管服务或者特定的服务器设置可能会阻止外部请求,或者文件路径有误。

  2. JSON格式不匹配:虽然您提到“我认为我制作的json非常完美”,但请再次检查从http://sha-way.freeweb.pk/index4.php返回的JSON数据结构是否与您在Fruitdata.fromJson中定义的结构完全匹配。特别是,您提到了注释掉的行// fName: json ['fruit_name'],这暗示原始数据源可能使用的是fruit_name而不是name作为键名。如果实际返回的数据使用的是fruit_name,而您代码中却尝试用name来解析,就会导致数据无法正确解析。

  3. 错误处理和日志:为了更好地诊断问题,可以在请求失败时添加更详细的错误信息打印,比如在fetchFruits方法中的异常处理部分打印出具体的错误信息,这样可以帮助您了解请求失败的具体原因。

  4. 网络权限和安全策略:对于Android和iOS应用,确保您的应用有正确的网络访问权限,并且如果是在模拟器或真实设备上测试,注意任何可能的安全限制或防火墙设置,这些都可能影响到HTTP请求的成功与否。

建议步骤: - 使用Postman或类似工具直接向http://sha-way.freeweb.pk/index4.php发送GET请求,验证返回的JSON格式。 - 在Flutter应用中增加日志输出,特别是在错误处理部分,以便获取更多关于请求失败的信息。 - 确认服务器端没有因为跨域资源共享(CORS)策略拒绝了您的请求,虽然这通常在使用HTTPS时更为常见,但某些服务器配置也可能对HTTP请求有限制。 - 如果可能,尝试将您的数据源也升级到HTTPS,这不仅有助于解决潜在的安全警告,也是现代Web开发的最佳实践。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答