This is the function, I want to retrieve currentUser data.
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
print(user?.displayName);
}
How to display the name on the screen When I call the function in text widget i.e
Text(getData().toString()),
I get the following display Instance of 'Future'<'dynamic'>''
i'm a beginner in Flutter, please help!
CodePudding user response:
Since the function getData
is async
, it's a Future
and you can't use a future methods inside your tree widget directly
you can use it inside your widget tree using the widget FutureBuilder
FutureBuilder(
future: getData(),
builder: (context, snapshot){
if (!snapshot.hasData) return const SizedBox();
return Text(snapshot.data?.toString() ?? '');
}
also, you have to modify your method to make it return something, Ex.:
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
print(user?.displayName);
return user?.displayName;
}
UPDATE:
to access all the info you want from the User
object, let your method return the whole object;
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
print(user?.displayName);
return user;
}
and your FutureBuilder
will be
FutureBuilder(
future: getData(),
builder: (context, snapshot){
if (!snapshot.hasData) return const SizedBox();
if (snapshot.data == null) return const Text('Current user is null');
return Column(
children: [
Text('Name: ${snapshot.data?.displayName}'),
Text('Email: ${snapshot.data?.email}'),
///Add any attribute you want to show..
]
);
}
CodePudding user response:
getData() async {
User? user = await FirebaseAuth.instance.currentUser;
if(user!=null){
print(user.displayName);
print(user.email);}
}
this will wait for an async method to first complete then print