我有个问题.不幸的是,我不能处理它. 我已经创建了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数据.
不幸的是,我的知识仍然是基础的,这就是为什么我被困在一个地方
有谁知道如何正确初始化流行的产品控制器类吗?