我正在使用provider
程序包进行扑打。
问题是我有一个get
方法,在此方法下我返回了an instance of categories list array
但是由于某些原因,即使通过API向其中添加数据之后,该列表也始终为空。
下面是代码:
import 'package:flutter/material.dart';
import '../configs/api_contants.dart';
import '../models/category_model.dart';
import '../models/product_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class CategoriesProvider with ChangeNotifier{
List<Category> _items = [];
int currentPage = 1;
int lastPage = 1;
List<Category> get items {
print("Items askfor are : $_items");
return [..._items];
}
Category findById(String id) {
return _items.firstWhere((cat) => cat.id == id);
}
Future<void> fetchCategories() async {
try {
final response = await http.get(categoriesApi);
final data = json.decode(response.body) as Map<String, dynamic>;
final categories = data['data'];
if(categories == null) {
return [...items];
}
categories.forEach((prodData){
var img = (prodData['attributes']['image_url']!= null) ? imgBaseUrl+prodData['attributes']['image_url'] : 'http://placehold.it/1200x1200';
try {
print(prodData);
print('--------------------');
_items.add(
Category(
id: prodData['id'].toString(),
name: prodData['attributes']['name'],
imgUrl: img,
)
);
} catch (e) {
print(e);
}
});
notifyListeners();
} catch (e) {
print(e);
}
}
}
您会看到有一个print statement
,它确实显示了API的记录列表。
_items.add()
是我正在使用的东西,到目前为止,我还没有error
那个东西。
代码哪里出错了?
如果我在_items.add()
之后添加打印,也会在控制台中得到以下输出。
flutter: Instance of 'Future<void>'
flutter: Items askfor are : []
flutter: []
flutter: --------------------
flutter: [Instance of 'Category']
flutter: --------------------
flutter: [Instance of 'Category', Instance of 'Category']
flutter: --------------------
flutter: [Instance of 'Category', Instance of 'Category', Instance of 'Category']
flutter: --------------------
flutter: [Instance of 'Category', Instance of 'Category', Instance of 'Category', Instance of 'Category']
flutter: Items askfor are : []