我在下面撰寫了代碼來提取 json 資料并將其顯示在我的應用程式中,它回傳狀態代碼為 200 的資料,但出現下面提到的錯誤。我的 json 檔案的鏈接是http://mvs.bslmeiyu.com/api/v1/products/popular。我正在使用顫振 2.10 并獲得依賴。請幫助我,因為我被困在這里,無法在我的應用程式中顯示產品串列。
錯誤:
I/flutter ( 7254): got products
E/flutter ( 7254): [ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>',
stack trace: #0 PopularProductController.getPopularProductList (package:my_restaurant/controllers/popular_product_controller.dart:16:60)
E/flutter ( 7254): <asynchronous suspension>
E/flutter ( 7254):
這是我的初始化函式'dependencies.dart'
import 'package:get/get.dart';
import 'package:my_restaurant/controllers/popular_product_controller.dart';
import 'package:my_restaurant/data/api/api_client.dart';
import 'package:my_restaurant/data/repository/popular_product_repo.dart';
import 'package:my_restaurant/utils/app_constants.dart';
Future<void> init()async {
//api client
Get.lazyPut(()=> ApiClient(appBaseUrl: AppConstants.BASE_URL));
//repositories
Get.lazyPut(()=> PopularProductRepo(apiClient: Get.find()));
//controllers
Get.lazyPut(()=> PopularProductController(popularProductRepo: Get.find()));
}
這是我的 api 客戶端 'api_client.dart'
import 'package:get/get.dart';
import 'package:my_restaurant/utils/app_constants.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);
token = AppConstants.TOKEN;
_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());
}
}
}
這是我的存盤庫代碼“popular_product_repo.dart”
import 'package:get/get.dart';
import 'package:my_restaurant/data/api/api_client.dart';
import 'package:my_restaurant/utils/app_constants.dart';
class PopularProductRepo extends GetxService{
final ApiClient apiClient;
PopularProductRepo({required this.apiClient});
Future<Response> getPopularProductList() async{
return await apiClient.getData(AppConstants.POPULAR_PRODUCT_URI);
}
}
這是我的控制器代碼“popular_product_controller.dart”
import 'package:my_restaurant/data/repository/popular_product_repo.dart';
import 'package:my_restaurant/models/products_model.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){
print("got products");
_popularProductList = [];
_popularProductList.addAll(Product.fromJson(response.body).products);
//print(_popularProductList);
update();
}else{
print("No products");
}
}
}
這是我的模式代碼“products_modal.dart”
class Product {
int? _totalSize;
int? _typeId;
int? _offset;
late List<ProductModal> _products;
List<ProductModal> 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 = <ProductModal>[];
json['products'].forEach((v) {
_products!.add(ProductModal.fromJson(v));
});
}
}
}
class ProductModal {
int? id;
String? name;
String? description;
int? price;
int? stars;
String? img;
String? location;
String? createdAt;
String? updatedAt;
int? typeId;
ProductModal(
{this.id,
this.name,
this.description,
this.price,
this.stars,
this.img,
this.location,
this.createdAt,
this.updatedAt,
this.typeId});
ProductModal.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'];
}
}
這是我的 main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:my_restaurant/controllers/popular_product_controller.dart';
import 'package:my_restaurant/pages/food/popular_food_detail.dart';
import 'package:my_restaurant/pages/food/recommended_food_detail.dart';
import 'package:my_restaurant/pages/home/food_page_body.dart';
import 'pages/home/main_food_page.dart';
import 'package:my_restaurant/helper/dependencies.dart' as dep;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await dep.init();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
Get.find<PopularProductController>().getPopularProductList();
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
)
);
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Restaurant',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MainFoodPage(),
);
}
}
uj5u.com熱心網友回復:
您得到的回應是 JSON 編碼值,它是一個字串,而在流行的產品控制器中,您撰寫了這一行
_popularProductList.addAll(Product.fromJson(response.body).products);
在這一行 Product.fromJson 想要一個 Map<String, dynamic>,你可以通過這個來解決這個問題。
Map rawData = jsonDecode(response.body);
_popularProductList.addAll(Product.fromJson(rawData).products);
這將解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427904.html
