I got this problem for long time ago trying to resolve this issue I saw many places at internet but not able to solve this problem to get the info from the API call from the controller class. Because of this kind of error I saw in docs flutter maybe because the flutter package that is also a dart package I got the SDK 3.0.0 here's the code please someone to help me achieve this project thank you so much:
This is the 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
);
}
}
This is the 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');
}
}
}
And this is the error:
[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>
CodePudding user response:
You are accepting null data, so you dont need to force with as
.
You can format like
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']}"));
}
CodePudding user response:
try this:
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
);
}
CodePudding user response:
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.
CodePudding user response:
Ok, well add this to your code:
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');
}
and tell me what it prints!