Provider not updating UI

116 Views Asked by At

I have a ListView. I need to change the leading: property of ListTile based on user tap. UI is not changing on interaction. It's updating after a Hot Restart

I have Appmodel setup like

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();
  }
}

I have main.dart like this

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(),
      ),
    );
  }

And my ListView like this

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),
      );
    });
  }
1

There are 1 best solutions below

0
On BEST ANSWER

You need to notify listeners if something changes via notifyListeners() call:

 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();
   }
 }