dart 错误:flutter未处理的异常:类型“Null”不是类型“String”的子类型

izj3ouym  于 2023-01-28  发布在  Flutter
关注(0)|答案(5)|浏览(211)

我得到这个问题很久以前试图解决这个问题,我看到很多地方在互联网上,但无法解决这个问题,以获得信息从API调用从控制器类.因为这种错误,我看到在docs flutter可能是因为flutter包,也是一个dart包,我得到了SDK 3.0.0这里的代码,请有人帮我实现这个项目非常感谢:
以下是模型类:

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;
  }

  factory Product.fromJson(Map<String, dynamic> json) {

    var list = json['products'] as List;
    List<ProductModel> productsList = list.map((e) => ProductModel.fromJson(e as Map<String, dynamic>)).toList();

    return Product(
        totalSize : json['total_size'] as int,
        typeId : json['type_id'] as int,
        offset : json['offset'] as int,
        products: productsList
    );
  }
}

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

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

  factory ProductModel.fromJson(Map<String, dynamic> json) {
    return ProductModel(
        id: json['id'] as int,
        name: json['name'] as String,
        description: json['description'] as String,
        price: json['price'] as int,
        stars: json['stars'] as int,
        img: json['img'] as String,
        location: json['location'] as String,
        createdAt: json['createdAt'] as String,
        updatedAt: json['updatedAt'] as String,
        typeId: json['typeId'] as int
    );
  }
}

这是控制器类:

import 'dart:convert';

import 'package:get/get.dart';
import 'package:licores_app/data/repository/category_product_repo.dart';

import '../models/products_model.dart';

class CategoryProductController extends GetxController {
  final CategoryProductRepo categoryProductRepo;
  CategoryProductController({required this.categoryProductRepo});

  List<dynamic> _categoryProductList = [];

  // Get Method from Product Model
  List<dynamic> get CategoryProductList => _categoryProductList;

  // Response from repo product method
  Future<void> getCategoryProductList() async {
    Response response =  await categoryProductRepo.getCategoryProductList();

    print('got the products'); // This is right to this point

    if (response.statusCode == 200) {
      // Init to null not to repeat
      _categoryProductList = [];
      _categoryProductList.addAll(Product
          .fromJson(jsonDecode(response.body))
          .products); // --> Here the
      // Unhandled Exception: type 'Null' is not a subtype of type 'String'
      print(_categoryProductList);
      update();
    } else { // I added the curly braces but took off because I was 
       // debugging the problem still persist!
       print('not able to get product list json');
    }
  }
}

这就是错误所在:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Null' is not a subtype of type 'String'
E/flutter ( 6243): #0      CategoryProductController.getCategoryProductList (package:licores_app/controllers/category_product_controller.dart:27:72)
E/flutter ( 6243): <asynchronous suspension>
jq6vz3qz

jq6vz3qz1#

您接受空数据,因此不需要强制使用as
您可以设置如下格式

name: json['name']
factory ProductModel.fromJson(Map<String, dynamic> json) {
    return ProductModel(
        id: int.tryParse("${json['id']}"),
        name: json['name'],
        description: json['description'],
        price: int.tryParse("${json['price']}"),
        stars: json['stars'],
        img: json['img'],
        location: json['location'],
        createdAt: json['createdAt'],
        updatedAt: json['updatedAt'],
        typeId: int.tryParse("${json['typeId']}"));
  }
fnx2tebb

fnx2tebb2#

试试这个:

factory ProductModel.fromJson(Map<String, dynamic> json) {
    return ProductModel(
        id: json['id'] as int,
        name: json['name'] as String ?? '',
        description: json['description'] as String ?? '',
        price: json['price'] as int ?? '',
        stars: json['stars'] as int ?? '',
        img: json['img'] as String ?? '',
        location: json['location'] as String ?? '',
        createdAt: json['createdAt'] as String ?? '',
        updatedAt: json['updatedAt'] as String ?? '',
        typeId: json['typeId'] as int ?? 0
    );
  }
klr1opcd

klr1opcd3#

好的,我们把这个添加到你的代码:

if (response.statusCode == 200) {
      // Init to null not to repeat
      _categoryProductList = [];
       //Added lines:
       //----------------------------
       print('response.body is ${response.body}');
       print('of type: ${response.body.runtimeType}');
       print('jsonDecode(response.body) is ${jsonDecode(response.body)}');
       print('of type: ${jsonDecode(response.body).runtimeType}');
       print('Product.fromJson(jsonDecode(response.body)) is ${Product.fromJson(jsonDecode(response.body))}');
       print('of type: ${Product.fromJson(jsonDecode(response.body)).runtimeType}');
       print('Product.fromJson(jsonDecode(response.body).products is ${Product.fromJson(jsonDecode(response.body)).products}');
       print('of type: ${Product.fromJson(jsonDecode(response.body)).products.runtimeType}');
       //----------------------------
      _categoryProductList.addAll(Product
          .fromJson(jsonDecode(response.body))
          .products); // --> Here the
      // Unhandled Exception: type 'Null' is not a subtype of type 'String'
      print(_categoryProductList);
      update();
    } else { // I added the curly braces but took off because I was 
       // debugging the problem still persist!
       print('not able to get product list json');
    }

告诉我它能打印什么!

wtlkbnrh

wtlkbnrh4#

首先,您必须检查是否收到响应代码200。然后按以下方式进行检查
首先,将ProductModel类中的所有字段设置为可选(可接受null)。
那么在构造函数中,您已经删除了所需工作,因为您将其设置为选项字段,而在工厂构造函数中,不需要额外的类型转换,如as Int,as String,只是删除它。在这之后你必须在工厂返回类中变量化所有键(生产类的构造函数)。简单地说,我的意思是检查你的json的所有关键字,并进一步验证你的所有数据类型与json你从API或其他地方收到的。希望这将有帮助。

kkih6yb8

kkih6yb85#

你需要打印出response.body并在这里添加它,那么哪个字段需要是可选的就很明显了。
这样的陈述:

img: json['img'] as String,

当json对象未定义键“img”时,将生成错误消息类型“Null "不是类型”String“的子类型
所以你要解析的键中有一个是未定义的。
为了弄清楚是哪一个,我们需要知道React的确切样子。
然后从服务器中删除可选字段上的所有“as String”强制转换。

相关问题