我正在尝试列出应用程序中产品的类别,并且我正在使用提供程序包进行状态管理。在构建期间,即使列表不是空白,其显示的列表也为空,然后我添加了一个click事件以在列表正常工作时对其进行更新。
我在启动画面期间调用getAllCategories()
函数,并且vallCategoryList
有值。
这是我的类别课程
class Category with ChangeNotifier{
int catId;
String catName;
String catThumbnail;
List<SetCategory> allCategoryList = [];
void getAllCategories() async {
String categoryUrl = 'https://app.ecwid.com/api/ccccccc';
Response allCategory = await get(categoryUrl);
print('getAllCategories');
if (allCategory.statusCode == 200) {
var categoryData = allCategory.body;
int totalcount = jsonDecode(categoryData)['count'];
if (allCategoryList.length != totalcount) {
allCategoryList.clear();
for (int i = 0; i < totalcount; i++) {
allCategoryList.add(SetCategory(
catId: jsonDecode(categoryData)['items'][i]['id'],
catName: jsonDecode(categoryData)['items'][i]['name'],
catThumbnail: jsonDecode(categoryData)['items'][i]['thumbnailUrl'],
));
}
}
}
print('allcategorylist length ${allCategoryList.length}');
notifyListeners();
}
}
class SetCategory {
int catId;
String catName;
String catThumbnail;
SetCategory(
{ this.catId, this.catName, this.catThumbnail});
}
我的屏幕代码
class HomeScreen extends StatefulWidget {
static const String id = 'homeScreen';
// static int reload = 0;
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
final category = Provider.of<Category>(context);
print('category length ${category.allCategoryList.length}'); // here it shows length as 0 even though it has a value of 16.
return Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Category ${category.allCategoryList.length}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15.0,
),
textAlign: TextAlign.start,
),
),
InkWell(
onTap: () {
category.getAllCategories(); // when i tap here this updates the list
}),
],
),
答案 0 :(得分:0)
您是否在小部件中使用了ChangeNotifierProvider
,如图here
如果您只是使用Provider
,它不会更新,而只是使后代可以访问该对象
答案 1 :(得分:0)
通过添加Consumer
来解决,更改后的代码如下
child: Consumer<Category>(
builder: (_,category,__){
return ListView.builder();
}