skip to Main Content

Iā€™m new to Flutter. How can I retrieve user data from Firebase to my profile page?

My Firebase data contains a name, email, blood type, and a date of birth. And I would like to retrieve this data to my app’s profile page.

This is my profile page code:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:line_awesome_flutter/line_awesome_flutter.dart';
import '../Reminder/ui/theme.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final user = FirebaseAuth.instance.currentUser!;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //leading: IconButton(onPressed: (){}, icon: const Icon(Icons.arrow_back_ios_new),),
        centerTitle: true,
        title: Text(
          'Profile',
          style: headingStyle,
        ),
        backgroundColor: Get.isDarkMode ? Colors.grey[700] : Colors.white,
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              SizedBox(
                width: 120,
                height: 120,
                child: Image(image: AssetImage("images/profile.png")),
              ),
              const SizedBox(height: 50),
              Form(
                child: Column(
                  children: [
                    TextFormField(
                      decoration: InputDecoration(
                          prefixIconColor: Get.isDarkMode?Colors.black:Colors.white,
                          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: BorderSide(color: Get.isDarkMode?Colors.white:Colors.black,)),
                          labelText: "Email",
                          prefixIcon: Icon(LineAwesomeIcons.envelope_1, color:  Get.isDarkMode?Colors.white:Colors.black),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100))),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      decoration: InputDecoration(
                          prefixIconColor: Get.isDarkMode?Colors.black:Colors.white,
                          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: BorderSide(color: Get.isDarkMode?Colors.white:Colors.black,)),
                          labelText: "Full Name",
                          prefixIcon: Icon(LineAwesomeIcons.user, color:  Get.isDarkMode?Colors.white:Colors.black),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100))),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      decoration: InputDecoration(
                          prefixIconColor: Get.isDarkMode?Colors.black:Colors.white,
                          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: BorderSide(color: Get.isDarkMode?Colors.white:Colors.black,)),
                          labelText: "Date of Birth",
                          prefixIcon: Icon(LineAwesomeIcons.baby_carriage, color:  Get.isDarkMode?Colors.white:Colors.black),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100))),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      decoration: InputDecoration(
                          prefixIconColor: Get.isDarkMode?Colors.black:Colors.white,
                          focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(100), borderSide: BorderSide(color: Get.isDarkMode?Colors.white:Colors.black,)),
                          labelText: "Blood Type",
                          prefixIcon: Icon(Icons.bloodtype, color:  Get.isDarkMode?Colors.white:Colors.black),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(100))),
                    ),
                    SizedBox(height: 15,),
                    SizedBox(
                      width: 100,
                      child: MaterialButton(
                        onPressed: () {
                          FirebaseAuth.instance.signOut();
                        },
                        color: Colors.redAccent,
                        child: Text('SIGN OUT'),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

2

Answers


  1. Use either StreamBuilder or FutureBuilder, get the data from firebase, and display it accordingly.

    1. StreamBuilder

    When you want to listen to changes constantly, and want the data to get updated without a hot reload/restart

    2. FutureBuilder

    When you want to get the document only once and have no requirement of listening constantly to the change of the document.

    1. Using StreamBuilder

       @override
        Widget build(BuildContext context) {
          return Scaffold(
            body: Center(
              child: StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
                stream:  FirebaseFirestore
                         .instance
                         .collection('users')
                         .doc(FirebaseAuth.instance.currentUser!.uid) // šŸ‘ˆ Your document id which is equal to currentuser
                         .snapshots(),
                builder:
                    (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                  if (snapshot.hasError) {
                    return const Text('Something went wrong');
                  }
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const Text("Loading");
                  }
                  Map<String, dynamic> data =
                      snapshot.data!.data()! as Map<String, dynamic>;
                  return Text(data['fullName']); // šŸ‘ˆ your valid data here
                },
              ),
            ),
          );
        }
      
    2. Using FutureBuilder

       @override
        Widget build(BuildContext context) {
          return Scaffold(
            body: Center(
                child: FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
              future: FirebaseFirestore.instance
                  .collection('users')
                  .doc(FirebaseAuth.instance.currentUser!.uid) // šŸ‘ˆ Your document id which is equal to currentuser
                  .get(),
              builder: (_, snapshot) {
                if (snapshot.hasError) return Text('Error = ${snapshot.error}');
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Text("Loading");
                }
                Map<String, dynamic> data = snapshot.data!.data()!;
                return Text(data['fullName']); //šŸ‘ˆ Your valid data here
              },
            )),
          );
        }
      
    Login or Signup to reply.
  2. You can use a stream builder to retrieve data from Firebase and display it to the user on real time. It may have some issues with styling, since I wrote it without any IDE, but I hope you’ll get the idea how to get your data from a stream builder.

    Example

    class ProfilePage extends StatefulWidget {
      const ProfilePage({super.key});
    
      @override
      State<ProfilePage> createState() => _ProfilePageState();
    }
    
    class _ProfilePageState extends State<ProfilePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Column(children: [
          StreamBuilder(
              stream: FirebaseFirestore.instance
                  .collection('your_collection')
                  .snapshots(),
              builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: SizedBox(
                      height: 50,
                      width: 50,
                      child: CircularProgressIndicator(
                        color: Colors.green,
                        backgroundColor: Colors.grey,
                      ),
                    ),
                  );
                } else {
                  return ListView(
                    shrinkWrap: true,
                    children: snapshot.data!.docs.map((document) {
                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Card(
                          color: const Color.fromRGBO(255, 255, 255, 1)
                              .withOpacity(0.6),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(15),
                          ),
                          child: Column(
                            children: <Widget>[
                              Text(document['name']),
                              Text(document['email']),
                              Text(document['bloodType']),
                              Text(document['dob']),
                            ],
                          ),
                        ),
                      );
                    }).toList(),
                  );
                }
              })
        ]));
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search