Home > database >  Read data from Firebase to Flutter UI
Read data from Firebase to Flutter UI

Time:07-19

I'am trying to show the datas from my firestore database into my user profile I made a separate class to get the datas. Now I'm having trouble on how to display it or call the class so that I can show the specific datas in the UI of my User Profile Screen. here is my database management class

class DatabaseManagement {

 final FirebaseFirestore _database = FirebaseFirestore.instance;

Future getVisitorDetails({required String uid}) async {
final CollectionReference userList =
    _database.collection('userList');
try {
  DocumentSnapshot ds = await userList.doc(uid).get();
  String firstname = ds.get('firstName');
  String lastname = ds.get('lastName');
  String email = ds.get('email');
  String? phoneNumber = ds.get('phoneNumber');
  String address = ds.get('address');


return [firstname, lastname, email, phoneNumber, address];
} catch (e) {
  print(e.toString());
  return null;
}
}

Here is my Profile Screen where the datas should be displayed

class ProfileScreen extends StatefulWidget {


const ProfileScreen({Key? key}) : super(key: key);
 @override


State<StatefulWidget> createState() => _ProfileScreenState();


class _ProfileScreenState extends State<ProfileScreen> {
String firstName,
String lastName,
String email,
String? phoneNumber,
String address,
String uid,

          Container(
        constraints: const BoxConstraints(
          minWidth: 250,
          maxWidth: 350,
        ),
        child: Column(
          children: [
            detailsWidget(
              icon: Icons.person,
              field: 'Full Name',
              value: name,
            ),
            detailsWidget(
              icon: Icons.email_rounded,
              field: 'Email',
              value: email,
            ),
            detailsWidget(
              icon: Icons.phone,
              field: 'Phone Number',
              value: phoneNumber,
            ), }

CodePudding user response:

I would recommend to write a User class that holds your 6 String properties (firstname, lastname,...) and contains a factory User.fromJson(Map<String, dynamic> json) constructor. Then you can adjust your call DocumentSnapshot ds = await userList.doc(uid).get(); with a withConverter(fromFirestore: _, toFirestore: _) call (check below) and return snapshot.data() afterwards.

User? _fromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? _,
  ) {
    final snapshotData = snapshot.data();
    if (snapshotData == null) return null;

    try {
      return User.fromJson(json);
    } catch (e) {
      debugPrint(e.toString());

      return null;
    }
  }

  // Not used but required for withConverter call.
Map<String, Object?> _toFirestore(User? _, SetOptions? __) => {};

Future<User?> getVisitorDetails({required String uid}) async {
  final snapshot = await_database
    .collection('userList')
    .doc(uid)
    .withConverter(fromFirestore: _fromFirestore, toFirestore: _toFirestore)
    .get();

  return snapshot.data();
}

Anywhere in your ProfileScreen you need a FutureBuilder where you do a call to your getVisitorDetails() method to get an User object and display the property values.

CodePudding user response:

FutureBuilder is quite simple and easy way to access data and handle errors. If you want to read more about it head over to this link. When should I use a FutureBuilder?

        child: FutureBuilder<DocumentSnapshot>(
             future: DatabaseManagement.getVisitorDetails(FirebaseAuth.instance.currentUser?.uid),
             builder: (context, snapshot) {
               if (snapshot.connectionState == ConnectionState.waiting) {
                 return const LoadingScreenWithOutScaffold();
               }
               if (snapshot.connectionState == ConnectionState.done) {
                 if (snapshot.hasData && snapshot.data!.exists) {
                   final data = snapshot.data?.data() as Map<String, dynamic>;

Then use it

       child: Column(
          children: [
            detailsWidget(
              icon: Icons.person,
              field: data['Full Name'], <== Whatever variable saved in your database
              value: name,
            ),
            detailsWidget(
              icon: Icons.email_rounded,
              field: data['Email'],
              value: email,
            ),
            detailsWidget(
              icon: Icons.phone,
              field: data['Phone Number'],
              value: phoneNumber,
            ), }
  • Related