提供商未更新 UI

Provider not updating UI

我有一个ListView。我需要根据用户点击更改 ListTileleading: 属性。 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();
   }
 }