如何在扑扑的云火存储中保存用户数据

时间:2020-10-11 05:59:07

标签: firebase flutter google-cloud-firestore firebase-authentication

我正在使用名为lit_firebase_auth的软件包,该软件包使Firebase身份验证更易于处理。我希望能够保存用户数据,例如用户登录后的用户名。基本上是这样的:

用户登录或注册->用户在主屏幕上单击“编辑个人资料”页面->用户可以在文本字段中输入所需的名称,然后单击“保存”->将该数据保存到相应的云中登录用户。

请我是一个初学者,我不知道如何实现这一目标。

以下是参考代码:

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),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

使用uuid作为文档名称将用户数据保存到Firebase中的文档中,以下代码将起作用。

如果您对如何在应用程序中使用代码感到困惑,那很简单。 只需按照以下步骤操作即可:

在传递显示名称数据的同时从onpress调用userSetup函数。

使用方法
下面的代码将使用用户集合中Firestore中的当前用户uuid创建新文档并保存数据。

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

userSteup函数

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;
}