Flutter中用Getx连接API到UI出现空白页,求解决方案
我正在尝试在Flutter中使用GetX将API连接到UI,已经创建了JSON解析类、Product Controller、Product Model和API服务,但运行代码后页面呈空白状态,无法加载显示数据列表,请求帮忙排查解决。
相关代码
Product列表视图代码
class ProductListView extends StatelessWidget { final ProductController productController = Get.put(ProductController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppString.productList), ), body: Obx(() { if (productController.isLoading.value) return Center( child: CircularProgressIndicator(), ); else return ListView.builder( itemCount: productController.productList.length, itemBuilder: (context, index) { return Column( children: [ Row( children: [ Container( width: 150, height: 100, margin: EdgeInsets.fromLTRB(16, 8, 8, 8), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: Image.network( productController.productList[index].imageLink, width: 150, height: 100, fit: BoxFit.fill, color: AppColor.purplecolor, colorBlendMode: BlendMode.color), ), ), Flexible( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( productController.productList[index].title, style: TextStyle(fontSize: 18), ), Text( productController .productList.value[index].description, style: TextStyle(fontSize: 18, color: AppColor.grey), ), Text( productController.productList[index].brand, style: TextStyle(fontSize: 18, color: AppColor.grey), ), Text( productController.productList[index].price, style: TextStyle(fontSize: 18, color: AppColor.grey), ), ], ), ), ], ), Container( color: AppColor.grey200, height: 2, ), ], ); }, ); }), ); } }
Product Model代码
import 'dart:convert'; List<ProductModel> productModelFromJson(String str) => List<ProductModel>.from( json.decode(str).map((x) => ProductModel.fromJson(x))); String productModelToJson(List<ProductModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class ProductModel { int? id; String? title; String? description; int? price; double? discountPercentage; double? rating; int? stock; String? brand; String? category; String? thumbnail; List<String>? images; ProductModel( {this.id, this.title, this.description, this.price, this.discountPercentage, this.rating, this.stock, this.brand, this.category, this.thumbnail, this.images}); ProductModel.fromJson(Map<String, dynamic> json) { id = json['id']; title = json['title']; description = json['description']; price = json['price']; discountPercentage = json['discountPercentage']; rating = json['rating']; stock = json['stock']; brand = json['brand']; category = json['category']; thumbnail = json['thumbnail']; images = json['images'].cast<String>(); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['title'] = this.title; data['description'] = this.description; data['price'] = this.price; data['discountPercentage'] = this.discountPercentage; data['rating'] = this.rating; data['stock'] = this.stock; data['brand'] = this.brand; data['category'] = this.category; data['thumbnail'] = this.thumbnail; data['images'] = this.images; return data; } }
Product Controller中Product Model声明
RxList productList = <ProductModel>[].obs;
关键问题及修复方案
1. 字段名称不匹配
列表视图中使用imageLink字段,但Product Model里对应的图片字段是thumbnail,不存在imageLink,这会导致空指针异常,页面无法正常渲染。
修复:将Image.network的参数改为productController.productList[index].thumbnail ?? '',添加空值判断避免报错。
2. 未触发数据请求
当前Controller仅声明了productList,没有调用API获取数据的逻辑,也没有在初始化时触发请求,导致productList始终为空。
修复:补充Controller的数据请求逻辑,示例如下:
class ProductController extends GetxController { RxList<ProductModel> productList = <ProductModel>[].obs; RxBool isLoading = false.obs; // 补充isLoading状态变量 final ApiService apiService = ApiService(); // 假设已实现ApiService @override void onInit() { super.onInit(); fetchProducts(); // 初始化时自动请求数据 } void fetchProducts() async { isLoading.value = true; try { // 调用API服务获取数据 List<ProductModel> products = await apiService.getProducts(); productList.assignAll(products); // 用assignAll更新RxList } catch (e) { print('数据请求失败: $e'); // 打印错误日志排查 } finally { isLoading.value = false; } } }
3. 缺失isLoading状态变量
视图中使用了productController.isLoading.value进行状态判断,但Controller中未声明该变量,会导致状态判断错误。
修复:在Controller中添加RxBool isLoading = false.obs;,并在请求数据时更新状态。
4. 类型转换错误
Product Model中的price是int?类型,直接传入Text组件会报错(Text需要String类型)。
修复:将price转换为字符串后传入:Text(productController.productList[index].price?.toString() ?? '0'),添加空值判断避免空指针。
内容的提问来源于stack exchange,提问作者Priya

