我有个问题.不幸的是,我不能处理它. 我已经创建了4个文件:

depencies.dart

import 'package:food_delivery/controllers/popular_product_controller.dart';
import 'package:food_delivery/data/api/apiclient.dart';
import 'package:food_delivery/data/repository/popular_product_repo.dart';
import 'package:get/get.dart';

Future<void> init() async {
  //api clinet
  Get.lazyPut(() => ApiClient(appBaseUrl: 'https://mvs.bslmeiyu.com'));

  //repository
  Get.lazyPut(() => PopularProductRepo(apiClient: Get.find()));

  //controllers
  Get.lazyPut(() => PopularProductController(popularProductRepo: Get.find()));
}

popular_product_repo.dart

import 'package:food_delivery/data/api/apiclient.dart';
import 'package:get/get.dart';

class PopularProductRepo extends GetxService {
  final ApiClient apiClient;

  PopularProductRepo({required this.apiClient});

  Future<Response> getPopularProductList() async {
    return await apiClient
        .getData('http://mvs.bslmeiyu.com/api/v1/products/popular');
  }
}

popular_product_controller.dart

import 'package:food_delivery/data/repository/popular_product_repo.dart';
import 'package:food_delivery/models/products_model.dart';
import 'package:get/get.dart';

class PopularProductController extends GetxController {
  final PopularProductRepo popularProductRepo;

  PopularProductController({required this.popularProductRepo});

  List<dynamic> _popularProductList = [];
  List<dynamic> get popularProductList => _popularProductList;

  Future<void> getPopularProductList() async {
    Response response = await popularProductRepo.getPopularProductList();
    if (response.statusCode == 200) {
      _popularProductList = [];
      _popularProductList.addAll(Product.fromJson(response.body).products);
      update();
    } else {
      return null;
    }
  }
}

product_model.dart

class Product {
  int? _totalSize;
  int? _typeId;
  int? _offset;
  late List<ProductModel> _products;
  List<ProductModel> get products => _products;

  Product(
      {required totalSize,
      required typeId,
      required offset,
      required products}) {
    this._totalSize = totalSize;
    this._typeId = typeId;
    this._offset = offset;
    this._products = products;
  }

  Product.fromJson(Map<String, dynamic> json) {
    _totalSize = json['total_size'];
    _typeId = json['type_id'];
    _offset = json['offset'];
    if (json['products'] != null) {
      _products = <ProductModel>[];
      json['products'].forEach((v) {
        _products!.add(ProductModel.fromJson(v));
      });
    }
  }
}

class ProductModel {
  int? id;
  String? name;
  String? description;
  int? price;
  int? stars;
  String? img;
  String? location;
  String? createdAt;
  String? updatedAt;
  int? typeId;

  ProductModel(
      {this.id,
      this.name,
      this.description,
      this.price,
      this.stars,
      this.img,
      this.location,
      this.createdAt,
      this.updatedAt,
      this.typeId});

  ProductModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    description = json['description'];
    price = json['price'];
    stars = json['stars'];
    img = json['img'];
    location = json['location'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    typeId = json['type_id'];
  }
}

Apiclinet.dart

import 'package:get/get.dart';

class ApiClient extends GetConnect implements GetxService {
  late String token;
  final String appBaseUrl;

  late Map<String, String> _mainHeaders;

  ApiClient({required this.appBaseUrl}) {
    baseUrl = appBaseUrl;
    timeout = Duration(seconds: 30);
    _mainHeaders = {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': 'Bearer $token',
    };
  }

  Future<Response> getData(String uri) async {
    try {
      Response response = await get(uri);
      return response;
    } catch (e) {
      return Response(statusCode: 1, statusText: e.toString());
    }
  }
}

在main.dart文件中,我想添加一个元素 Get.find().getPopularProductList();

main.dart

import 'package:flutter/material.dart';
import 'package:food_delivery/controllers/popular_product_controller.dart';
import 'package:food_delivery/pages/food/popular_food_detail.dart';
import 'package:food_delivery/pages/food/recomended_food_detail.dart';
import 'package:food_delivery/pages/home/main_food_page.dart';
import 'package:food_delivery/data/repository/popular_product_repo.dart';

import 'package:get/get.dart';
import 'helper/depencies.dart' as dep;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dep.init;

  // Initialize the PopularProductController

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Get.find<PopularProductController>().getPopularProductList();

    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: RecomencedFoodDetail(),
    );
  }
}

Unfortunately, I immediately get an error: ════════ Exception caught by widgets library ═══════════════════════════════════ The following message was thrown building MyApp(dirty): "PopularProductController" not found. You need to call "Get.put(PopularProductController())" or "Get.lazyPut(()=>PopularProductController())"

为什么不能在这里使用Get.find? 我希望将控制器元素初始化为能够使用JSON数据.

不幸的是,我的知识仍然是基础的,这就是为什么我被困在一个地方

有谁知道如何正确初始化流行的产品控制器类吗?

推荐答案

应该是main.dart里的await dep.init();.

Json相关问答推荐

如何在JMESPath中区分空和假?

用于参考的Jolt变换

Jolt:数组中两个字符串的连接

在 SQL 存储过程中使用参数 Select 值

json 字符串到 Postgres 14 中的表视图

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

xidel:是否可以从 JSON 对象中检索特定的嵌套值?

Powershell 7.2:ConvertFrom-Json - 日期处理

如何在linux中用jq过滤json数组?

如何使用 Swiftui 判断 JSON 是否缺少键值对

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

如何使用 Swift 从 NSURLSession 获取 cookie?

使用 jq,将对象数组转换为具有命名键的对象

如何创建 JSON 对象 Node.js

jQuery JSON 响应总是触发 ParseError

使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

在 Java 中比较两个 JSON 文件的最佳方法

如何将 MongoDB 查询转换为 JSON?

如何从 JSON 响应中提取单个值?

如何在 postgresql 9.3 中循环 JSON 数组