dart 如何解决Flutter应用程序不显示API数据的问题?

xcitsw88  于 2023-06-03  发布在  Flutter
关注(0)|答案(1)|浏览(228)

这是Flutter中的一个购物应用程序,我创建了一个控制器,模型,绑定和提供程序,用于在应用程序中获取和显示API数据。
这是控制器:

class ShopController extends GetxController
with StateMixin<List<NewProducts>>{
  var beveragesList = <NewProducts>[].obs;
  RxBool isLoading = false.obs;
  RxBool noMoreData = false.obs;
  int lastPage = 2;
  int currenctPage = 1;

  final count = 0.obs;

  ShopProductProvider provider;
  ShopController ({required this.provider});

  @override
  void onInit() {
    // TODO: implement onInit
    getProductList(true);
    super.onInit();
  }

  getProductList(bool isLoad) async {
    if(isLoad){
      change(null, status:  RxStatus.loading());
    }

    await provider.getProductlist().then((value) {
      if (kDebugMode){
        print(value);
      }
      List body = json.decode(value) as List;
      final data = body.map((d) => NewProducts.fromJson(d)).toList();
      change(data, status: RxStatus.success());
    }).onError((error, stackTrace) {
      change(null, status: RxStatus.error(error.toString()));
    });
  }

这是提供者:

class ShopProductProvider extends GetConnect {

  Future<dynamic> getProductlist() =>
      http
          .get(
        Uri.parse('${BaseUrl.baseUrl}/api/homepage'),
        /*headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },*/
      )
          .then((value) => value.body)
          .onError((error, stackTrace) => Future.error(error.toString()));

}

这是模型:

class NewProducts {
  int? id;
  int? categoryId;
  int? brandId;

  NewProducts(
      {this.id,
        this.categoryId,
        this.brandId});

  NewProducts.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    categoryId = json['category_id'];
    brandId = json['brand_id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['category_id'] = this.categoryId;
    data['brand_id'] = this.brandId;
    return data;
  }
}

这是一个很好的例子。

class ShopView extends GetView<ShopController> {

  // final ShopController shopController = Get.put(ShopController(provider: ShopProductProvider()));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Obx(() =>
   StaggeredGrid.count(
                        crossAxisCount: 2,
                        mainAxisSpacing: 3.0,
                        crossAxisSpacing: 0.0,
                        // I only need two card horizontally
                        children: **controller.beveragesList
                            .asMap()
                            .entries
                            .map<Widget>((e) {
                          NewProducts newproducts = e.value;**
                          return GestureDetector(
                            onTap: () {
                              Get.toNamed(Routes.SINGLEPRODUCT);
                            },
                            child: Container(
                              padding: const EdgeInsets.all(5),
                              child: MedicineCard(
                                item: newproducts,
                                heroSuffix: "explore_screen",
                              ),
                            ),
                          );
                        }).toList(), // add some space
                      )
                      ),

…………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………...
我尝试了很多东西,比如改变控制器、视图或列表视图,但什么都没有发生。我想问题出在我的视图页面上。我的API数据显示如下:

{
    "success": true,
    "message": "Data Retrive Successfully",
    "code": 200,
    "result": {
        "NewProducts": [
            {
                "id": 1490,
                "category_id": 41,
                "brand_id": 20,

但在商店视图中显示的是Map列表。我觉得有问题,也在控制器。

wi3ka0sx

wi3ka0sx1#

如果数据表单API没有获取,请检查您URL是否为http或https:
如果你的URL是http,那么你必须做一些网络配置,以便在Android和iOS的应用程序中使用http URL。
在Android中转到android/app/src/main/res
检查文件夹xml是否存在,如果不存在,则创建具有名称的文件夹,并在该文件夹中创建文件network_security_config.xml并粘贴以下代码:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">http://your.url.app.com</domain>
    </domain-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">https://your.url.app.com</domain>
    </domain-config>
      
</network-security-config>

AndroidManifest.xml文件中添加以下行

<application
     android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:usesCleartextTraffic="true" // this line
      android:networkSecurityConfig="@xml/network_security_config" // and this line
      android:requestLegacyExternalStorage="true"
      android:theme="@style/AppTheme">

相关问题