當我遇到此錯誤時,我正在參加 Flutter 課程(該課程是在 flutter 2 之前錄制的):
I/flutter ( 3538): type 'Null' is not a subtype of type 'String'
E/flutter ( 3538): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'String'
E/flutter ( 3538): #0 Products.fetchAndSetProducts
package:shop_app/providers/products_provider.dart:80
E/flutter ( 3538): <asynchronous suspension>
我試圖檢查突出顯示的行是否有問題,對我來說沒問題。
這是代碼:
Future<void> fetchAndSetProducts() async {
var url = Uri.parse(
'https://flutter-39ecc-default-rtdb.firebaseio.com/products.json');
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<Product> loadedProducts = [];
extractedData.forEach((key, value) {
loadedProducts.add(Product(
id: key,
title: value['title'],
description: value['description'],
price: value['price'],
isFavorite: value['isFavorite'],
imageUrl: value['imageUrl']));
});
_items = loadedProducts;
notifyListeners();
// print(json.decode(response.body));
} catch (error) {
print(error);
throw error; // line 80
}
}
這就是我呼叫這個函式的方式
var _isInit = true;
var _isLoading = false;
@override
void didChangeDependencies() {
if (_isInit) {
setState(() {
_isLoading = true;
});
Provider.of<Products>(context).fetchAndSetProducts().then((_) {
setState(() {
_isLoading = false;
});
});
}
_isInit = false;
super.didChangeDependencies();
}
uj5u.com熱心網友回復:
請檢查您的Product課程。它的屬性應該可以Null。
所以它可能String?不是String
Product(
id: key,
title: value['title'],
description: value['description'],
price: value['price'],
isFavorite: value['isFavorite'],
imageUrl: value['imageUrl']));
}
我檢查了來自https://flutter-39ecc-default-rtdb.firebaseio.com/products.json. 構造Product物件時需要使用一些缺失的鍵。
uj5u.com熱心網友回復:
這是因為您嘗試分配的值之一為空,而變數不可為空
loadedProducts.add(Product(
id: key,
title: value['title'],
description: value['description'],
price: value['price'],
isFavorite: value['isFavorite'],
imageUrl: value['imageUrl']));
});
看看這段代碼,如果你想制作一個模型類的產品,如果你讓每個變數都可以為空,那就太好了。
class ProductModel {
int? id;
String? title;
String? description;
double? price;
bool? isFavorite;
String? imageUrl;
}
如果您真的認真對待后端的分配,那就太好了。因為有些后端不一致。
factory ProductModel ProductModel.fromJson(Map<String, dynamic> json) => ProductModel({
id: json['id'] != null ? (json['id'] as num?)?.toInt() : null,
//it would be great if you also check if the json['id'] is instance of String or not, because sometimes you can get id with type String from backend
// why use num? instead of int?, because sometimes we can also get double from backend right? and int and double indicator isn't consistent
// that's why num? then cast to the type you want is the best practice
title: json['title'] as String?,
//etc..
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359624.html
