My changenotifierprovider is not updating. Not sure why

Issue

Here is my change Notifier class.

class UserChamaNotifier with ChangeNotifier {
    final List<UserChama> _userChamaList = [];
    
    
      UnmodifiableListView<UserChama> get userchamaListy =>
          UnmodifiableListView(_userChamaList);
    
      void addUserChama(UserChama userchama) {
        _userChamaList.add(userchama);
        notifyListeners();
      }
 }

I have created the provider in main.dart:

Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => _appStateManger,
        ),
        ChangeNotifierProvider(
          create: (context) => _profileManager,
        ),
        ChangeNotifierProvider(
          create: (context) => UserChamaNotifier(),
        )
      ],

Then I proceed to add a chama object to my list:

UserChama userChama =
          UserChama(id: s['Id'], phone: s['Phone'], name: s['Name']);
      print(userChama.phone);
      Provider.of<UserChamaNotifier>(context).addUserChama(userChama);

Here i try to access the list through the provider:

class ChamaList extends StatelessWidget {
  const ChamaList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    UserChamaNotifier userChamaNotifier =
        Provider.of<UserChamaNotifier>(context, listen: true);
    return Text(userChamaNotifier.userchamaListy.length.toString());
  }
}

At this point, i have experimented alot and i still don’t have the correct way of implementation.

Solution

While adding data, set listen:false

  Provider.of<UserChamaNotifier>(context,listen:false)
          .addUserChama(userChama);

Check more how listen: false works when used with Provider.of(context, listen: false).

Answered By – Yeasin Sheikh

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *