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の番号を変更したいだけです。

製品画面.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画面とコントローラーも同じにしたいです。Product_Service.dartファイルからデータを取得し、そのデータをリスト内のコントローラーに渡す API リンクのみを変更したいだけです。

4

2 に答える 2