skip to Main Content

I am flutter beginner, using dart language. I am trying to integrate an API with UI in Flutter using GetX.
I created Json class and product controls. When I try to create the product list view, I get the below errors.

Thanks in advance!

Error lines:

1. itemCount: productController.productList.length,
2. productController.productList[index].imageLink,
3. productController.productList[index].title,

Errors:

  1. The getter ‘length’ isn’t defined for the type ‘Rx’.
  2. The operator ‘[]’ isn’t defined for the type ‘Rx’.
  3. The operator ‘[]’ isn’t defined for the type ‘Rx’.

Product List Code:


    import 'package:flutter/material.dart';
    import 'package:practice/commonmodule/AppColor.dart';
    import 'package:practice/commonmodule/AppString.dart';
    import 'package:practice/productmodule/controllers/product_controller.dart';
    import 'package:get/get.dart';

    class ProductListView extends StatelessWidget {
     final ProductController productController = Get.put(ProductController());

     @override
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppString.productList),
      ),
      body: Obx(
        () {
          if (productController.isLoading.value)
            return Center(child: CircularProgressIndicator());
          else
            return ListView.builder(
              itemCount: productController.productList.length,
              itemBuilder: (context, index) {
                return Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 150,
                          height: 100,
                          margin: EdgeInsets.fromLTRB(16, 8, 8, 8),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: Image.network(
                              productController.productList[index].imageLink,
                              width: 150,
                              height: 100,
                              fit: BoxFit.fill,
                              color: AppColor.bluecolor,
                              colorBlendMode: BlendMode.color,
                            ),
                          ),
                        ),
                        Flexible(
                            child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              productController.productList[index].title,
                              style: TextStyle(fontSize: 18),
                            ),
                            Text(
                              productController.productList[index].description,
                              style:
                                  TextStyle(fontSize: 18, color: AppColor.grey),
                            ),
                            Text(
                              productController.productList[index].price,
                              style:
                                  TextStyle(fontSize: 18, color: AppColor.grey),
                            ),
                          ],
                        )),
                      ],
                    ),
                    Container(
                      color: AppColor.grey200,
                      height: 2,
                    )
                  ],
                );
              },
            );
        },
      ),
    );
    }
    }

Product controller code:

class ProductController extends GetxController {
  var isLoading = true.obs;
  var productList = ProductModel().obs;

  @override
  void onInit() {
    fetchProducts();
    super.onInit();
  }

  void fetchProducts() async {
    try {
      isLoading(true);
      var products = await ApiService.fetchProducts();
      if (products != null) {
        productList.value = products;
      }
    } finally {
      isLoading(false);
    }
  }
}

`

2

Answers


  1. You need to create ProductList Model To List Model.

    class ProductController extends GetxController {
      var isLoading = true.obs;
      RxList[ProductModel]  productList= [].obs;
    
      @override
      void onInit() {
        fetchProducts();
        super.onInit();
       }
    
       void fetchProducts() async {
       try {
        isLoading(true);
        var products = await ApiService.fetchProducts();
        if (products != null) {
        productList.value = products;
        }
      } finally {
        isLoading(false);
      }
    }
    

    }

    Login or Signup to reply.
  2. import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    
    class ProductListView extends StatelessWidget {
      final ProductController productController = Get.put(ProductController());
      ProductListView({super.key});
    
      @override
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('productList'),
      ),
      body: Obx(
        () {
          if (productController.isLoading.value) {
            return const Center(child: CircularProgressIndicator());
          } else {
            return ListView.builder(
              itemCount: productController.productList.length,
              itemBuilder: (context, index) {
                return Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 150,
                          height: 100,
                          margin: const EdgeInsets.fromLTRB(16, 8, 8, 8),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: Image.asset(
                              productController.productList[index].imageLink,
                              width: 150,
                              height: 100,
                              fit: BoxFit.fill,
                              color: Colors.blue,
                              colorBlendMode: BlendMode.color,
                            ),
                          ),
                        ),
                        Flexible(
                            child: Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              productController.productList[index].title,
                              style: const TextStyle(fontSize: 18),
                            ),
                            Text(
                              productController.productList[index].description,
                              style:
                                  const TextStyle(fontSize: 18, color: Colors.grey),
                            ),
                            Text(
                              productController.productList[index].price.toString(),
                              style:
                                  const TextStyle(fontSize: 18, color: Colors.grey),
                            ),
                          ],
                        )),
                      ],
                    ),
                    Container(
                      color: Colors.grey[200],
                      height: 2,
                    )
                  ],
                );
              },
            );
          }
        },
      ),
    );
    }
    }
    
    class ProductController extends GetxController {
      final isLoading = true.obs;
      RxList<ProductModel> productList= <ProductModel>[].obs;
    
      @override
      void onInit() {
        fetchProducts();
        super.onInit();
      }
    
      void fetchProducts() async {
        try {
          isLoading.value = true;
          List<ProductModel> products = await ApiService().fetchProducts();
          if (products.isNotEmpty) {
            productList.value = products;
          }
        } finally {
          isLoading.value = false;
        }
      }
    }
    class ProductModel {
      int? id;
      String title;
      String description;
      int price;
      String imageLink;
      ProductModel({
        this.id,
        required this.title,
        required this.description,
        required this.price,
        required this.imageLink,
      });
      factory ProductModel.fromJson(Map<String, dynamic> data) => ProductModel(
        title: data["title"],
        description: data["description"],
        price: data["price"] ,
        imageLink: data["imageLink"],
      );
      Map<String, dynamic> toJson(data) => {
            "title": title,
            "description": description,
            "price": price,
            "imageLink": imageLink,
      };
    }
    class ApiService {
      Future<List<ProductModel>> fetchProducts() async {
        String json = '''[{
          "title": "title1",
          "description": "description1",
          "price": 1,
          "imageLink": "images/ic_facebook.png"
        }, {
          "title": "title2",
          "description": "description2",
          "price": 2,
          "imageLink": "images/ic_google.png"
        },{
          "title": "title3",
          "description": "description3",
          "price": 3,
          "imageLink": "images/ic_home_filled.png"
        }]''';
    
      var plistJson = jsonDecode(json) as List;
      List<ProductModel> plist = plistJson.map((tagJson) => ProductModel.fromJson(tagJson)).toList();
      return plist;
      }
    }
    

    screenshot

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search