gpt4 book ai didi

flutter - 提供程序未更新UI

转载 作者:行者123 更新时间:2023-12-03 04:35:20 25 4
gpt4 key购买 nike

我有一个ListView。我需要根据用户点击来更改leading:ListTile属性。 UI不会因交互而改变。它在Hot Restart之后更新
我有类似Appmodel的设置

class AppModel extends ChangeNotifier {
final _saved = Set<String>();
Set<String> getApps() => _saved;

addApp(String apkPath) {
_saved.add(apkPath);
ChangeNotifier();
}

removeApp(String apkPath) {
_saved.remove(apkPath);
ChangeNotifier();
}
}
我有这样的 main.dart
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<AppModel>(
create: (_) => AppModel(),
),
FutureProvider<List<Application>>(
create: (_) => appService.fetchCountries(),
),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Countries List',
theme: ThemeData(primaryColor: Colors.green),
home: Home(),
),
);
}
和我的 ListView这样
Widget build(BuildContext context) {
List<Application> apps = Provider.of<List<Application>>(context);

return ListView.builder(
itemCount: apps.length,
itemBuilder: (contxt, index) => _buildRow(apps[index]));
}

Widget _buildRow(ApplicationWithIcon app) {
return Consumer<AppModel>(builder: (context, appModel, child) {
final saved = appModel.getApps().contains(app.apkFilePath);
return ListTile(
leading: Image.memory(app.icon, height: 40),
trailing: saved
? Icon(Icons.check_circle, color: Colors.deepPurple[400])
: Icon(Icons.check_circle_outline),
title: Text(app.appName),
onTap: () => saved
? appModel.removeApp(app.apkFilePath)
: appModel.addApp(app.apkFilePath),
);
});
}

最佳答案

您需要通过notifyListeners()调用来通知侦听器:

 class AppModel extends ChangeNotifier {
final _saved = Set<String>();
Set<String> getApps() => _saved;

addApp(String apkPath) {
_saved.add(apkPath);
notifyListeners();
}

removeApp(String apkPath) {
_saved.remove(apkPath);
notifyListeners();
}
}

关于flutter - 提供程序未更新UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64194775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com