gpt4 book ai didi

flutter - Getx 无法与 FutureBuilder 一起正常工作以获取更新列表

转载 作者:行者123 更新时间:2023-12-03 03:29:41 33 4
gpt4 key购买 nike

我在我的项目中使用 Getx Controller 。我已经为 FutureBuilder 创建了用于显示列表的 Controller ,但是 .Obs 没有在 Future Function 上设置。我正在分享代码。

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,);

最佳答案

形成 docs :

3 - The third, more practical, easier and preferred approach, just add.obs as a property of your value:

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();
},
);
},
);
};

关于flutter - Getx 无法与 FutureBuilder 一起正常工作以获取更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64783928/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com