如何使用 GetX 更改 API link 保持相同的控制器和 UI

How to change API link keeping the same controller and UI using GetX

我有一个控制器,我在其中从 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 页面传递到控制器 但我只能从这里传递硬代码数据,因为它发出警告 无法通过初始化程序访问实例成员变量

I hope you guys got my problem, I want the UI screen to be same and controller too. I only want to change the API link, which is fetching data from Product_Service.dart file and passing that data to the Controller inside the List.

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

这有帮助吗?

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

我在首页的onTap函数上传了Get.find<ProductController>().fetchProduct(3);,让它传参

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