我在项目中使用Getx控制器。我已经为FutureBuilder创建了用于显示列表的控制器,但是未在Future Function上设置.Obs。我正在共享代码。
class PPHomeController extends GetxController {
Future<List<PPProductRenterModel>> listNearProduct;
// i want to set .Obs end of the "listNearProduct" but it's not working because of Future.
FetchNearProductList({@required int price}) async {
listNearProduct = CallGetNearProducts();// Http API Result
}
}
{
PPHomeController _homeController = Get.put(PPHomeController());
Widget mainProductListView() {
return FutureBuilder<List<PPProductRenterModel>>
(builder: (context, AsyncSnapshot<List<PPProductRenterModel>> projectSnap){
if(!projectSnap.hasData){
if(projectSnap.connectionState == ConnectionState.waiting){
return Container(
child: Loading(),
);
}
}
return ListView.builder(
itemCount: projectSnap.data.length,
itemBuilder: (context, index) {
PPProductRenterModel model = projectSnap.data[index];
PPPrint(tag: "CheckId",value: model.productId);
return ProductMainItemRow(model);
});
},
future: _homeController.listNearProduct,);
答案 0 :(得分:2)
在 GetX 中实现 List 有一种更简洁的方法,无需担心类型转换:
实例化它:
final myList = [].obs;
分配:
myList.assignAll( listOfAnyType );
(参考)使用 List.value
时出现 Flutter 错误:
'value' 已弃用,不应使用。 List.value 已弃用。 使用 [yourList.assignAll(newList)]。尝试更换使用 已弃用的成员替换。
详细代码示例
ProductController.dart
class ProductController extends GetxController {
final productList = [].obs;
@override
void onInit() {
fetchProducts();
super.onInit();
}
void fetchProducts() async {
var products = await HttpServices.fetchProducts();
if (products != null) {
productList.assignAll(products);
}
}
}
HttpServices.dart
class HttpServices {
static var client = http.Client();
static Future<List<Product>> fetchProducts() async {
var url = 'https://link_to_your_api';
var response = await client.get(url);
if (response.statusCode == 200) {
return productFromJson(response.body);
} else {
return null;
}
}
}
product.dart
class Product {
Product({
this.id,
this.brand,
this.title,
this.price,
....
});
....
}
答案 1 :(得分:1)
形成docs:
3-第三种,更实用,更容易且首选的方法,只需添加 .obs作为您有价值的属性:
final items = <String>[].obs;
按照该说明进行操作,
final listNearProduct = Future.value(<PPProductRenterModel>[]).obs;
例如:
// controller
final list = Future.value(<String>[]).obs;
@override
void onInit() {
super.onInit();
fetchList();
}
Future<List<String>> callApi() async {
await Future.delayed(Duration(seconds: 2));
return ['test'];
}
void fetchList() async {
list.value = callApi();
}
// screen
@override
Widget build(BuildContext context) {
return GetX<Controller>(
init: Controller(),
builder: (controller) {
return FutureBuilder<List<String>>(
future: controller.list.value,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data[0]); // Output: test
return Text(snapshot.data[0]);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
);
},
);
};
答案 2 :(得分:0)
您从未真正打电话 FetchNearProductList
。
您需要在某个地方调用它,最好在FutureBuilder使用该Future之前。