如何在flutter中将用户数据保存在云Firestore中

Posted

技术标签:

【中文标题】如何在flutter中将用户数据保存在云Firestore中【英文标题】:How to save user data in cloud fire store in flutter 【发布时间】:2021-01-25 18:34:26 【问题描述】:

我正在使用一个名为 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】:

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

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

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

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

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

userStup 函数

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;

【讨论】:

以上是关于如何在flutter中将用户数据保存在云Firestore中的主要内容,如果未能解决你的问题,请参考以下文章

Flutter-如何在flutter的整个应用程序生命周期中将数据保存在内存中?

在 Flutter 中将数据保存到 Firebase 实时数据库

如何在flutter中将图像数据保存到sqflite数据库以进行持久化

如何在flutter中将数据从firestore传递给Typeahead

如何在颤动中将 ImageCache 保存到磁盘?

如何在 Flutter 移动应用中将 Azure AD 用户登录到 Firebase?