5

我在我的项目中使用 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,);
4

3 回答 3

4

有一种更简洁的方法可以在 GetX 中实现 List 而无需担心类型转换:

实例化它:

final myList = [].obs;

分配它:

myList.assignAll( listOfAnyType );

(参考)使用时出现颤振错误List.value

'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,
    ....
  });
  ....
}
于 2021-02-20T23:06:51.017 回答
4

形成文档

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();
        },
      );
    },
  );
};
于 2020-11-11T10:41:44.150 回答
0

你从来没有真正打电话 FetchNearProductList

您需要在某个地方调用它,最好是在 FutureBuilder 使用该 Future 之前。

于 2020-11-11T10:35:30.020 回答