【发布时间】:2021-12-28 23:34:47
【问题描述】:
当我遇到这个错误时,我正在学习 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();
}
【问题讨论】: