1

我有一个控制器,我从 API 获取数据并添加到列表中

product_controller.dart

import 'package:get/state_manager.dart';
import 'package:get_it_test/services/product_services.dart';

class ProductController extends GetxController {
  var ProductList = [].obs;

  @override
  void onInit() {
    // TODO: implement onInit
    fetchProduct();
    super.onInit();
  }

  void fetchProduct() async {
    var productsList = await ProductServices.fetchProducts(); 
    //ProductServices is a Separate class from where I am fetching the API
    print(productsList.data.products);
    if (productsList != null) {
      ProductList.assignAll(productsList.data.products);
    }
  }
}

我正在从 product_services.dart 获取数据

Product_services.dart

import 'package:get_it_test/Models/product_model.dart';
import 'package:http/http.dart' as http;

class ProductServices {
  static var client = http.Client();

  static Future fetchProducts() async {
    var response = await client.post(
        Uri.https('********.com', 'api/getProduct'),
        //Here I want to change the number (4) to any other number to fetch different data
        body:'{"category":"4","search":"","sortBy":"relavance","page":"","size":""}');
    if (response.statusCode == 200) {
      var jsonString = response.body;
      print(productsScreenFromJson(jsonString));
      return productsScreenFromJson(jsonString);
    } else {
      //show error message
      return null;
    }
  }
}

我想通过单击 UI 屏幕上的另一个按钮从 UI 更改该数字来获取不同的数据。

我想保持控制器和 UI 屏幕相同,我只想根据按钮单击更改 API url 中的数字。

Productscreen.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_it_test/Views/Widgets/BottomBar.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:get_it_test/Controller/product_controller.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class ProductScreen extends StatelessWidget {
  final String title;

  ProductScreen(this.title);

  final ProductController productController = Get.put(ProductController());
  //I tried creating a constructor in the Controller and passing the data from here to the controller
  //But I can only able to pass the hard code data through this as it is giving warning that 
  //access members can't be accessed through the initialiser
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.black),
        backgroundColor: Colors.white,
        title: Text(
          title,
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Obx(() => StaggeredGridView.countBuilder(
                    crossAxisCount: 2,
                    itemCount: productController.ProductList.length,
                    itemBuilder: (BuildContext context, int index) =>
                        new Container(
                            // height: 200,
                            width: 200,
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Column(
                                children: [
                                  CachedNetworkImage(
                                    imageUrl: productController
                                        .ProductList[index].image,
                                    placeholder: (context, url) =>
                                        new CircularProgressIndicator(),
                                    errorWidget: (context, url, error) => new Image
                                            .network(
                                        '****.com/noimage.png'),
                                  ),
                                  // Image.network(productController
                                  //     .ProductList[index].image),
                                  Text(productController
                                      .ProductList[index].prodName),
                                ],
                              ),
                            )),
                    staggeredTileBuilder: (int index) =>
                        new StaggeredTile.fit(1),
                    mainAxisSpacing: 4.0,
                    crossAxisSpacing: 4.0,
                  )),
            ),
            BottomBar()
          ],
        ),
      ),
    );
  }
}

我尝试在控制器中创建一个构造函数并将数据从 ProductScreen.dart 页面传递到控制器但我只能从这里传递硬代码数据,因为它警告 不能通过初始化程序访问实例成员变量

我希望你们能解决我的问题,我希望 UI 屏幕和控制器也一样。我只想更改 API 链接,该链接从Product_Service.dart文件中获取数据并将该数据传递给列表中的控制器。

4

2 回答 2

0
static Future fetchProducts(int number) async {
    var response = await client.post(
        Uri.https('********.com', 'api/getProduct'),
        //Here I want to change the number (4) to any other number to fetch different data
        body:'{"category":"$number","search":"","sortBy":"relavance","page":"","size":""}');
    .....
  }

这不可能吗?

要查看的编辑

Future getProductsWithAnotherCategory() async{

   
    final ProductController productController = Get.put(ProductController());
    final ProductController productController = Get.find();


    await productController.fetchProducts(4);
  }

这有帮助吗?

于 2021-03-15T03:20:39.007 回答
0

感谢@MMHasibuzzaman 的回答,我通过 final ProductController productController = Get.put(ProductController());homepage.dart文件中初始化解决了我的问题。

我传递 Get.find<ProductController>().fetchProduct(3);了主页的 onTap 函数,以便它传递参数。

还添加final ProductController productController = Get.find<ProductController>();ProductScreen.dart文件中,以便我可以在主页中使用相同的实例变量。它解决了我的问题。

于 2021-03-15T05:05:08.357 回答