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:
- The getter ‘length’ isn’t defined for the type ‘Rx’.
- The operator ‘[]’ isn’t defined for the type ‘Rx’.
- 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
You need to create ProductList Model To List Model.
}
screenshot