My application has Firebase Authentication implemented and each user have to input their display name to register into the application.
Inside my application I want the user to be able to update this display name.
The logic is very simple, user clicks 'Change Display Name' button, a ModalBottomSheet appears where user can input his new display name and save it. But this way the screen doesn't gets updated when the display name is changed until I hot reload or restart the application.
class Body extends StatelessWidget {
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
Widget build(BuildContext context) {
String displayName = _auth.currentUser.displayName;
final _formKey = GlobalKey<FormState>();
String newDisplayName;
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Current display name is:',
style: TextStyle(fontSize: 20),
),
Text(
'$displayName',
style: TextStyle(fontSize: 25),
),
RaisedButton(
child: Text('Change Display Name'),
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) {
return Padding(
padding: MediaQuery.of(context).viewInsets
child: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
decoration: InputDecoration(
labelText: 'New Display Name',
),
keyboardType: TextInputType.text,
onSaved: (value) {
newDisplayName = value;
},
),
RaisedButton(
child: Text('Change'),
onPressed: () {
_formKey.currentState.save();
_auth.currentUser
.updateProfile(displayName: newDisplayName);
Navigator.pop(context);
},
),
],
),
),
);
},
);
},
),
],
),
),
);
}
}
I have tried to call .reload in different places but the display name won't change until page is refreshed.
_auth.currentUser.reload();
EDIT: Solution thanks to https://stackoverflow.com/users/11921453/twelve
Wrap the manin widget with the following StreamBuilder and you will be able to retrieve the snapshot.data.displayName instantly.
child: StreamBuilder<User>(
stream: FirebaseAuth.instance.userChanges(),
Firebase has a stream to listen to user changes. Define this stream next to your _auth.
Wrap your widget-tree with au streambuilder and set the value to the defined stream.
Now the widget-tree gets rebuild every time the user data changes.