Home > Net >  set a username & profile picture firebase login and then get it for a profile later on
set a username & profile picture firebase login and then get it for a profile later on

Time:10-30

ok, its late and I can't quite figure this out for some reason. I am coming from swift and newer to flutter. my code is below, I can't get my username to register in my json or anything else and I can't figure out how to pull it out later either, any help would be appreciated, I can pull out all the data but I haven't figured out how to assign the displayName or profile picture on a later screen

class WelcomeScreen extends StatefulWidget {
  const WelcomeScreen({Key? key}) : super(key: key);
  static const String id = 'welcome_screen';

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

class _WelcomeScreenState extends State<WelcomeScreen> with SingleTickerProviderStateMixin{
  FirebaseAuth auth = FirebaseAuth.instance;
  final _auth = FirebaseAuth.instance;
  var _isLoading = false;
  late AnimationController controller;
  late Animation animation;

  void _completeLogin() {
    Navigator.pushReplacement<void, void>(
      context,
      MaterialPageRoute<void>(
        builder: (BuildContext context) => Home(),
      ),
    );
  }
  void _submitAuthForm(
      String email,
      String username,
      String password,
      File imageFile,
      bool isLogin,
      BuildContext ctx,
      ) async {
    UserCredential authResult;

    try {
      setState(() {
        _isLoading = true;
      });

      if (isLogin) {
        authResult = await _auth.signInWithEmailAndPassword(
          email: email,
          password: password,


        );
        print('$username');
      } else {
        authResult = await _auth.createUserWithEmailAndPassword(
          email: email,
          password: password,
        );
        print('$username');

        final ref = FirebaseStorage.instance
            .ref()
            .child('user_image')
            .child(authResult.user!.uid   'jpg');

        await ref.putFile(imageFile);

        final url = await ref.getDownloadURL();

        await FirebaseFirestore.instance
            .collection('users')
            .doc(authResult.user!.uid)
            .set({
          'username': username,
          'email': email,
          'image_url': url,
        });
      }
    } on FirebaseAuthException catch (error) {
      var message = 'An error occurred, please check your credentials!';
      if (error.message != null) {
        message = error.message!;
      }

      ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(content: Text(message)));
      setState(() {
        _isLoading = false;
      });
    }
  }



  @override
  void initState() {

    super.initState();


    controller =
        AnimationController (
          duration: Duration(seconds: 1),
          vsync: this,

        );
    animation = ColorTween(begin: Colors.transparent, end: Colors.white.withOpacity(0.5)).animate(controller);
    controller.forward();

    controller.addListener(() {
      setState(() {

      });

    });

  }


  @override
  Widget build(BuildContext context) {
    FirebaseAuth.instance
        .authStateChanges()
        .listen((User? user) {
      if (user == null) {
        print('User is currently signed out!');
      } else {
        _completeLogin();
       print('1');
      }
    });
    return Container(
        decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/bar1.jpg"),
          fit: BoxFit.fill,
        )
        ),
      child: Scaffold(
      backgroundColor: Colors.white.withOpacity(0.5),
        body: Container(
          child: Center(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Image.asset('assets/images/logo.png'),
                  AuthForm(
                    _submitAuthForm,
                    _isLoading,
                  ),
                ],
              ),
            ),
          ),
          
        ),
      ),
    );
   
  }
}

and here is my auth form

FocusNode myFocusNode = FocusNode();
class AuthForm extends StatefulWidget {
  const AuthForm(this.submitFn, this.isLoading, {Key? key}) : super(key: key);

  final bool isLoading;
  final void Function(
      String email,
      String userName,
      String password,
      File image,
      bool isLogin,
      BuildContext ctx,
      ) submitFn;

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

class _AuthFormState extends State<AuthForm> {
  final _formKey = GlobalKey<FormState>();
  var _isLogin = true;
  String _userEmail = '';
  String _userName = '';
  String _userPassword = '';
  File _userImageFile = File('');

  void _pickedImage(File image) {
    _userImageFile = image;
  }

  void _trySubmit() {
    final isValid = _formKey.currentState!.validate();
    FocusScope.of(context).unfocus();

    if (_userImageFile.path.isEmpty && !_isLogin) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please pick an image'),
        ),
      );
      return;
    }

    if (isValid) {
      _formKey.currentState!.save();
      widget.submitFn(
        _userEmail.trim(),
        _userName.trim(),
        _userPassword.trim(),
        _userImageFile,
        _isLogin,
        context,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        margin: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 350),
            curve: Curves.easeIn,
            constraints: BoxConstraints(
              minHeight: _isLogin ? 224 : 390,
              maxHeight: _isLogin ? 268 : 456,
            ),
            child: Form(
              key: _formKey,
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    if (!_isLogin)
                      UserImagePicker(_pickedImage),
                    TextFormField(



                      cursorColor: Colors.red,
                      key: const ValueKey('email'),
                      autocorrect: false,
                      textCapitalization: TextCapitalization.none,
                      keyboardType: TextInputType.emailAddress,
                      decoration: InputDecoration(

                        labelText: 'Email address',


                      ),
                      validator: (val) {
                        if (EmailValidator.validate(val!) == false) {
                          return 'Please enter a valid email address.';
                        }
                        return null;
                      },
                      onSaved: (val) {
                        _userEmail = val!;
                      },
                    ),
                    if (!_isLogin)
                      TextFormField(
                        cursorColor: Colors.red,
                        key: const ValueKey('username'),
                        decoration: const InputDecoration(
                          labelText: 'Username',
                        ),
                        validator: (val) {
                          if (val!.isEmpty || val.length < 4) {
                            return 'Username must be at least 4 characters.';
                          }
                          return null;
                        },
                        onSaved: (val) {
                          _userName = val!;
                        },
                      ),
                    TextFormField(
                      cursorColor: Colors.red,
                      key: const ValueKey('password'),
                      decoration: const InputDecoration(
                        labelText: 'Password',
                      ),
                      obscureText: true,
                      validator: (val) {
                        if (val!.isEmpty || val.length < 6) {
                          return 'Check your password, it must be 6 character or longer.';
                        }
                        return null;
                      },
                      onSaved: (val) {
                        _userPassword = val!;
                      },
                    ),
                    const SizedBox(height: 12),
                    widget.isLoading
                        ? const CircularProgressIndicator()
                        : ElevatedButton(
                      style:  ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(Colors.red),
                      ),
                      child: Text(_isLogin ? 'Log in' : 'Sign up'),
                      onPressed: _trySubmit,
                    ),
                    TextButton(
                      child: Text(_isLogin
                          ? 'Create new account'
                          : 'I already have an account'),
                      onPressed: () {
                        setState(() {
                          _isLogin = !_isLogin;
                        });
                      },
                    ),
                    if (_isLogin)
                    TextButton(
                      child: Text(
                          'Forgot Password?'
                          ),
                      onPressed: () {
Navigator.pushNamed(context, ForgotPassword.id);
                      },
                    ),

                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

answered it my self by writing to a category in firebase then used the below code to pull it out later

import 'package:flutter/material.dart';

// Import the firebase_core and cloud_firestore plugin
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class AddUser extends StatelessWidget {
  final String fullName;
  final String company;
  final int age;

  AddUser(this.fullName, this.company, this.age);

  @override
  Widget build(BuildContext context) {
    // Create a CollectionReference called users that references the firestore collection
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    Future<void> addUser() {
      // Call the user's CollectionReference to add a new user
      return users
          .add({
            'full_name': fullName, // John Doe
            'company': company, // Stokes and Sons
            'age': age // 42
          })
          .then((value) => print("User Added"))
          .catchError((error) => print("Failed to add user: $error"));
    }

    return TextButton(
      onPressed: addUser,
      child: Text(
        "Add User",
      ),
    );
  }
}

and this code to query it

class GetUserName extends StatelessWidget {
  final String documentId;

  GetUserName(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
          return Text("Full Name: ${data['full_name']} ${data['last_name']}");
        }

        return Text("loading");
      },
    );
  }
}

CodePudding user response:

You can pass them as a constructor Example

   class UserDetail extends StatelessWidget {
   final File image;
   final String display;

  UserDetail({Key key, required this.image, required this.display}) : super(key: key);
   
@override
  Widget build(BuildContext context) {

    return Container(child:Row(
                children: <Widget>[
                            Image.file(image: File(image))),
                            Text(display),

  ], ),);

  }
}

You can read Passing data between screens in Flutter For more info.

  • Related