小部件未在提供商变量更改时重新绘制-颤振



我有一个名为" favoritesprovider ";它有一个变量叫做"_favoritos"这里存储了一个id列表

我要做的是,每当一个新项目被添加或删除到favorites变量时,重新绘制一个ListView小部件。下面是我这样做的函数,在这里我更新变量和notifyListeners。

Future setFavorites(
int id,
) async {
final prefs = await SharedPreferences.getInstance();
String _receivedData = (prefs.getString('favorites') ?? "");
List _decodedData = [];
if (_receivedData != "") {
_decodedData = json.decode(_receivedData);
}
String _sentData = "";
if (_decodedData.contains(id)) {
_decodedData.remove(id);
_sentData = json.encode(_decodedData);
} else {
_decodedData.add(id);
_sentData = json.encode(_decodedData);
}
prefs.setString("favorites", _sentData);
_favoritos = _decodedData;
notifyListeners();
return _favoritos;}

我想重新绘制的项目是这样嵌套的:

  • 主页:包含IndexedStack的脚手架主体
List<Widget> _widgetOptions = [
HomePage(),
FavoriteScreen(),
CompletedScreen()
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _selectedIndex,
children: _widgetOptions,
),
  • FavoriteScreen:无状态小部件只包含我自己的FavDoneList小部件。
  • FavDoneList:包含列表的有状态小部件。→我想重新渲染.我尝试使用侦听器,但它不重绘:
@override
Widget build(BuildContext context) {
var _favorites = Provider.of<FavoritesProvider>(context).favoritos;
if (flag == true) {
if (_favorites.isEmpty) {
return Center(child: Text("No has añadido favoritos"));
}
return ListView(
children: _loadFavorites(_favorites),
);
}
return Center(
child: CircularProgressIndicator(
color: Colors.red,
));
}

你能帮我理解我做错了什么吗?我不知道怎么重新画。谢谢!

我用了一些"丑"字来解决这个问题:

因为我的提供者、消费者或监听器都不能工作,所以我打算重新加载整个FavDoneList小部件每次按下底部中间的TAB键。就性能而言,这是一个非常小的代价,它不会对用户产生太大影响。

我在主页面这样做了:

void _onItemTapped(int index) {
if (index == 1) {
setState(() {
_widgetOptions.removeAt(1);
_widgetOptions.insert(1, FavDoneList(key: UniqueKey()));
_selectedIndex = index;
});
} else {
setState(() {
_selectedIndex = index;
});
}}

传递唯一键非常重要,否则不起作用

最新更新