Flutter provider not updating the UI

Viewed 5921

I'm pretty sure I have everything setup correctly, or at least very close to correctly. However, either notifyLister(), my consumer is not working or maybe both.

I have my UserModel setup like so

...

class UserModel with ChangeNotifier {
      Map<dynamic, dynamic> _user;

      Map get user {
        return _user;
      }

      void setUser(user) {
        _user = user;
        notifyListeners();
      }
    }

I have my app setup like this in main.dart

...

void main() {
  runApp(ChangeNotifierProvider(
    builder: (context) => UserModel(),
    child: MyApp()
  ),
  );
}

Next I have a button that calls the setUser method in the UserModel

...

UserModel().setUser(user);

...

Lastly I have a Consumer nested in a column in the build method of app.dart

....

Consumer<UserModel>(
    builder: (context, user, child) {
        return user.user == null ? Text(
            'NULL ${user.user}',
                style: TextStyle(fontSize: 28),
        ) : Text(
            'NOT NULL ${user.user}',
                style: TextStyle(fontSize: 28),
        );
    },
),

....

user.user is at first placed on the screen which is correct because starts out as null however, when the user logs in the _user in the model is set to its eventual value the UI does not update. What did I do wrong?

1 Answers

here you created new object ;

UserModel().setUser(user);

so you set the user in empty object you will never use it should be

Provider.of<UserModel>(context).setUser(user);
Related