Evonic
Evonic

Reputation: 25

How to save user data in cloud fire store in flutter

I am using a package called lit_firebase_auth which makes firebase authentication easier to handle. I want to be able to save user data, such as the username after the user logs in. Basically as such:

User logs in or signs up --> User clicks on edit profile page from the home screen --> User can enter their desired name in the text field and click save --> Saves this data to the cloud of the respectful logged in user.

Please I'm a beginner and I have no idea how to pull this off.

Here is the code for reference:

cloud_firebase.dart:


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';



Future<void> userSetup(String displayName) async {
  CollectionReference users = FirebaseFirestore.instance.collection('Users');
  FirebaseAuth auth = FirebaseAuth.instance;
  String uid = auth.currentUser.uid.toString();
  users.add({'displayName': displayName, 'uid': uid});
  return;
}

auth.dart

import 'package:flutter/material.dart';
import 'package:kiwi/screens/auth/register.dart';
import 'package:kiwi/screens/background_painter.dart';
import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/auth/sign_in.dart';
import 'package:animations/animations.dart';
import 'package:kiwi/screens/home.dart';

class AuthScreen extends StatefulWidget {
  const AuthScreen({Key key}) : super(key: key);

  static MaterialPageRoute get route => MaterialPageRoute(
        builder: (context) => const AuthScreen(),
      );

  @override
  _AuthScreenState createState() => _AuthScreenState();
}

class _AuthScreenState extends State<AuthScreen>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  ValueNotifier<bool> showSignInPage = ValueNotifier<bool>(true);

  @override
  void initState() {
    _controller =
        AnimationController(vsync: this, duration: const Duration(seconds: 2));
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LitAuth.custom(
        onAuthSuccess: () {
          Navigator.of(context).pushReplacement(HomeScreen.route);
        },
        child: Stack(
          children: [
            SizedBox.expand(
                child: CustomPaint(
              painter: BackgroundPainter(),
            )),
            Center(
              child: ConstrainedBox(
                constraints: BoxConstraints(maxWidth: 800),
                child: ValueListenableBuilder<bool>(
                  valueListenable: showSignInPage,
                  builder: (context, value, child) {
                    return PageTransitionSwitcher(
                      reverse: !value,
                      duration: Duration(milliseconds: 800),
                      transitionBuilder:
                          (child, animation, secondaryAnimation) {
                        return SharedAxisTransition(
                          animation: animation,
                          secondaryAnimation: secondaryAnimation,
                          transitionType: SharedAxisTransitionType.vertical,
                          fillColor: Colors.transparent,
                          child: child,
                        );
                      },
                      child: value
                          ? SignIn(
                              key: ValueKey('SignIn'),
                              onRegisterClicked: () {
                                context.resetSignInForm();
                                showSignInPage.value = false;
                                _controller.forward();
                              },
                            )
                          : Register(
                              key: ValueKey('Register'),
                              onSignInPressed: () {
                                context.resetSignInForm();
                                showSignInPage.value = true;
                                _controller.reverse();
                              },
                            ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

splash.dart


import 'package:flutter/material.dart';

import 'package:lit_firebase_auth/lit_firebase_auth.dart';
import 'package:kiwi/screens/home.dart';
import 'package:kiwi/screens/auth/auth.dart';

class SplashScreen extends StatelessWidget {
  const SplashScreen({Key key}) : super(key: key);

  static MaterialPageRoute get route => MaterialPageRoute(
        builder: (context) => const SplashScreen(),
      );

  @override
  Widget build(BuildContext context) {
    final user = context.watchSignedInUser();
    user.map(
      (value) {
        _navigateToHomeScreen(context);
      },
      empty: (_) {
        _navigateToAuthScreen(context);
      },
      initializing: (_) {},
    );

    return const Scaffold(
      body: Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  void _navigateToAuthScreen(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback(
      (_) => Navigator.of(context).pushReplacement(AuthScreen.route),
    );
  }

  void _navigateToHomeScreen(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback(
      (_) => Navigator.of(context).pushReplacement(HomeScreen.route),
    );
  }
}

edit_profile.dart


import 'package:flutter/material.dart';
import 'package:kiwi/config/palette.dart';
import 'package:kiwi/screens/auth/decoration_functions.dart';

class Profile extends StatefulWidget {
  const Profile({Key key}) : super(key: key);

  static MaterialPageRoute get route => MaterialPageRoute(
        builder: (context) => const Profile(),
      );

  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  // UserModel _currentUser = locator.get<UserController>().currentUser;

  // File _image;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('Edit Profile'),
      ),
      body: Builder(
        builder: (context) => Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              SizedBox(
                height: 20.0,
              ),
              Column(
                children: <Widget>[
                  Text(
                    'Hey there',
                    style: TextStyle(color: Palette.lightGreen, fontSize: 20),
                  )
                ],
              ),
              SizedBox(
                height: 20,
              ),
              Expanded(
                flex: 8,
                child: ListView(
                  children: [
                    Padding(
                      padding: EdgeInsets.fromLTRB(50, 0, 50, 0),
                      child: TextFormField(
                        style: const TextStyle(
                          fontSize: 18,
                          color: Colors.green,
                        ),
                        decoration: signInInputDecoration(
                          hintText: 'New Username',
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        RaisedButton(
                          elevation: 4,
                          color: Colors.red,
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: const Text(
                            'Cancel',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                        RaisedButton(
                          elevation: 4,
                          color: Palette.lightGreen,
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: const Text(
                            'Save',
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: 2

Views: 7024

Answers (1)

Zakria Khan
Zakria Khan

Reputation: 2203

to save user data to document in firebase using uuid for document name the below code will work.

if you are confused about how to use the code in your app its simple. just follow the steps:

call userSetup Function from onpress while passing the display name data.

how to use
the below code will create new document using the currect users uuid in firestore in user collection and save the data.

onPress:(){
    userSetup(displayName:"zakriakhan");
}

userSteup Function

Future<void> userSetup(String displayName) async {
   //firebase auth instance to get uuid of user
   FirebaseAuth auth = FirebaseAuth.instance.currentUser();

   //now below I am getting an instance of firebaseiestore then getting the user collection
   //now I am creating the document if not already exist and setting the data.
   FirebaseFirestore.instance.collection('Users').document(auth.uid).setData(
   {
    'displayName': displayName, 'uid': uid
   })

   return;
}

Upvotes: 3

Related Questions