Reputation: 4418
My application uses Tab bar
:
Home screen shows the user's name and avatar. When User click to the Account tab (Last Tab) and updates the name and photo. How does the Home screen UI can listen and update the latest data?
Upvotes: 3
Views: 1406
Reputation: 4418
I use lib Provider
. Detail see provider.
First, create UserInfoProvider
of you:
class UserInfoProvider extends ChangeNotifier {
UserInfoData _userInfoData;
UserInfoData get userInfoData => this._userInfoData;
UserInfoProvider(){
_userInfoData = new UserInfoData();
}
void setUserInfoData(UserInfoData userInfo){
_userInfoData = userInfo;
notifyListeners();
}
}
After, you need handle this provider on main
:
ChangeNotifierProvider<UserInfoProvider>(
create: (_) => provider,
child: MaterialApp(
title: 'My App',
),
)
Then, when wrap Home UI with Consumer:
Consumer<UserInfoProvider>(
builder: (_, userInfoProvider, __){
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//get data from provider in Home UI
Text(userInfoProvider.userInfoData.displayName),
],
),
);
}
)
Finally, you can update in another screen, and Text
in HomeScreen will auto update UI.
Provider.of<UserInfoProvider>(context, listen: false).setUserInfoData(userDataUpdate);
This is very useful for checking the status of the user who is logged in.
Upvotes: 1