I want to create a profil page where I just display informations from the user, but I have trouble to reach the data. When I want to use my variable user it display ‘Instance of Future<Map<String, dynamic>>’
If I put the ‘Widget build’ in async I have an error message who told me : ProfileScreen.build’ (‘Future Function(BuildContext)’) isn’t a valid override of ‘StatelessWidget.build’ (‘Widget Function(BuildContext)’).
class ProfileScreen extends StatelessWidget {
ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
final user = displayUser();
return Scaffold(
appBar: AppBar(
title: Text('Profile'),
),
body: Align(
alignment: Alignment.topLeft,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Align(
alignment: Alignment.topLeft,
child: Column(children: [
Text('Prénom :${user}nNom :nEmail :',
textWidthBasis: TextWidthBasis.longestLine),
]),
)
]),
),
persistentFooterButtons: [
SignOutButton(),
BottomNavBar(),
]);
}
// Get user informations
Future<Map<String, dynamic>> displayUser() async {
final User? currentUser = FirebaseAuth.instance.currentUser;
late final userUid = currentUser?.uid;
late final ref = FirebaseDatabase.instance.ref();
final resSnapshot = await ref.child('/utilisateur/' + userUid!).get();
final Map<String, dynamic> user = {};
if (resSnapshot.exists) {
user['id'] = userUid;
for (var value in resSnapshot.children) {
String key = value.key as String;
var val = value.value;
user[key] = val;
}
} else {
print('No data available.');
}
print(user); // This print display exactly the informations I want.
return user;
}
}
Thanks for your help.
3
Answers
Your
displayUser
isasync
function and you can’t call it insidebuild
method, you need to useFutureBuilder
like this:You can customize loading and error state to what you want.
change
StatelessWidget
toStatefulWidget
becauseuserInteract
on profileScreen,UserInteraction
changes will show on firebase.You can load the
user
in theinitstate
and then set user usingsetstate