繁体   English   中英

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

[英]Error:flutter Unhandled Exception: type 'Null' is not a subtype of type 'String'

我很久以前就遇到了这个问题试图解决这个问题我在 inte.net 看到了很多地方但是无法解决这个问题从 API 从 controller class 调用中获取信息。由于这种错误我看到了文档 flutter 可能是因为 flutter package 这也是一个 dart package 我得到了 SDK 3.0.0 这里的代码请有人帮助我实现这个项目非常感谢:

这是 model class:

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

这是 controller class:

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>

您正在接受 null 数据,因此您不需要强制使用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']}"));
  }

尝试这个:

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

好的,将其添加到您的代码中:

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

告诉我它打印了什么!

  First you make all fields in ProductModel class is optional (null acceptable).

      then in constructor you have remove required work because you make it as option field, and in factory constructor there is no required an additional type casting like as Int, as String, just remove it.
      After this you must varified all key in factory return class ( constructor of production class ). Simply i mean check your all key of json and verify further your all data type with json you received from Api or somewhere else.
    Hope this will helpfull.

您需要打印出 response.body 并将其添加到此处,然后很明显哪个字段需要是可选的。

像这样的声明:

img: json['img'] as String,

当 json object 没有定义键 'img' 时,将产生错误消息 type 'Null' is not a subtype of type 'String'

所以你正在解析的键之一是未定义的。

为了弄清楚是哪一个,我们需要知道响应到底是什么样的。

然后从服务器中删除对可选字段的所有“as String”强制转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM