简体   繁体   English

Flutter Firebase:如何从 Firebase 调用显示名称和 UID 验证然后使用这些值并保存在 Cloud Firestore

[英]Flutter Firebase : How to call Display Name and UID from Firebase Auth then use those values and save in Cloud Firestore

I have a project from university, but I am confused how to call Display Name and UID from Firebase Auth then use those values and save in Cloud Firestore.我有一个大学项目,但我很困惑如何从 Firebase Auth 调用显示名称和 UID,然后使用这些值并保存在 Cloud Firestore 中。

I tried to write the code below but I got an error.我尝试编写下面的代码,但出现错误。

//Call Display Name and UID From Firebase User
    AuthNotifier authNotifier =
        Provider.of<AuthNotifier>(context, listen: false);
    String _currentDP = authNotifier.user.displayName;
    String _currentUID = authNotifier.user.uid;

    print('UID : $_currentUID');
    print('Display Name : $_currentDP');

    if (_currentInitRPP.ptk != null) {
      _currentInitRPP.ptk = rppNotifier.currentInitRPP.ptk;
    } else {
      _currentInitRPP.ptk = _currentDP;
    }

    if (_currentInitRPP.uid != null) {
      _currentInitRPP.uid = rppNotifier.currentInitRPP.uid;
      return;
    } else {
      _currentInitRPP.uid = _currentUID;
    }

    // Code end here

Please help me.请帮我。

Full Code完整代码

rpp_form.dart rpp_form.dart

import 'package:aplikasi_rpp/model/database.dart';
import 'package:aplikasi_rpp/notifier/auth_notifier.dart';
import 'package:aplikasi_rpp/notifier/rpp_notifier.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:aplikasi_rpp/api/api.dart';

class RPPForm extends StatefulWidget {
  final bool isUpdating;

  RPPForm({@required this.isUpdating});

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

class _RPPFormState extends State<RPPForm> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  InitRPP _currentInitRPP;

  @override
  void initState() {
    super.initState();
    RPPNotifier rppNotifier = Provider.of<RPPNotifier>(context, listen: false);

    //Call Display Name and UID From Firebase User
    AuthNotifier authNotifier =
        Provider.of<AuthNotifier>(context, listen: false);
    String _currentDP = authNotifier.user.displayName;
    String _currentUID = authNotifier.user.uid;

    print('UID : $_currentUID');
    print('Display Name : $_currentDP');

    if (_currentInitRPP.ptk != null) {
      _currentInitRPP.ptk = rppNotifier.currentInitRPP.ptk;
    } else {
      _currentInitRPP.ptk = _currentDP;
    }

    if (_currentInitRPP.uid != null) {
      _currentInitRPP.uid = rppNotifier.currentInitRPP.uid;
      return;
    } else {
      _currentInitRPP.uid = _currentUID;
    }

    // Code end here

    if (rppNotifier.currentInitRPP != null) {
      _currentInitRPP = rppNotifier.currentInitRPP;
    } else {
      _currentInitRPP = InitRPP();
    }
  }

  Widget _buildMapelField() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Mata Pelajaran'),
      initialValue: _currentInitRPP.mapel,
      keyboardType: TextInputType.text,
      style: TextStyle(fontSize: 18),
      validator: (String value) {
        if (value.isEmpty) {
          return 'Form ini tidak boleh kosong';
        }
        return null;
      },
      onSaved: (String value) {
        _currentInitRPP.mapel = value;
      },
    );
  }

  Widget _buildKelasField() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Kelas (Contoh: Kelas I)'),
      initialValue: _currentInitRPP.kelas,
      keyboardType: TextInputType.text,
      style: TextStyle(fontSize: 18),
      validator: (String value) {
        if (value.isEmpty) {
          return 'Form ini tidak boleh kosong';
        }
        return null;
      },
      onSaved: (String value) {
        _currentInitRPP.kelas = value;
      },
    );
  }

  Widget _buildTahunFiled() {
    return TextFormField(
      decoration:
          InputDecoration(labelText: 'Tahun Ajaran (Contoh: 2020/2021)'),
      initialValue: _currentInitRPP.tahun,
      keyboardType: TextInputType.text,
      style: TextStyle(fontSize: 18),
      validator: (String value) {
        if (value.isEmpty) {
          return 'Form ini tidak boleh kosong';
        }
        return null;
      },
      onSaved: (String value) {
        _currentInitRPP.tahun = value;
      },
    );
  }

  Widget _buildSemesterField() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Semester (Ganjil/Genap)'),
      initialValue: _currentInitRPP.semester,
      keyboardType: TextInputType.text,
      style: TextStyle(fontSize: 18),
      validator: (String value) {
        if (value.isEmpty) {
          return 'Form ini tidak boleh kosong';
        }
        return null;
      },
      onSaved: (String value) {
        _currentInitRPP.semester = value;
      },
    );
  }

  Widget _buildMateriField() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Materi'),
      initialValue: _currentInitRPP.materi,
      keyboardType: TextInputType.text,
      style: TextStyle(fontSize: 18),
      validator: (String value) {
        if (value.isEmpty) {
          return 'Form ini tidak boleh kosong';
        }
        return null;
      },
      onSaved: (String value) {
        _currentInitRPP.materi = value;
      },
    );
  }

  _saveInitRPP() {
    if (!_formKey.currentState.validate()) {
      return;
    }
    _formKey.currentState.save();

    uploadInitRPP(_currentInitRPP, widget.isUpdating, _onInitRPPUploaded);

    print('mapel : ${_currentInitRPP.mapel}');
    print('kelas : ${_currentInitRPP.kelas}');
    print('tahun : ${_currentInitRPP.tahun}');
    print('semester : ${_currentInitRPP.semester}');
    print('materi : ${_currentInitRPP.materi}');
  }

  _onInitRPPUploaded(InitRPP initRPP) {
    RPPNotifier rppNotifier = Provider.of<RPPNotifier>(context, listen: false);
    rppNotifier.addInitRPP(initRPP);
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Data Awal RPP'),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(10),
        child: Form(
          key: _formKey,
          autovalidateMode: AutovalidateMode.always,
          child: Column(
            children: <Widget>[
              Text(
                widget.isUpdating ? 'Edit Data Awal RPP' : 'Buat Data Awal RPP',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(height: 20),
              _buildMapelField(),
              _buildKelasField(),
              _buildTahunFiled(),
              _buildSemesterField(),
              _buildMateriField(),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _saveInitRPP(),
        child: Icon(Icons.save),
        foregroundColor: Colors.white,
      ),
    );
  }
}

Error code in debug console调试控制台中的错误代码

The setter 'ptk=' was called on null.
Receiver: null
Tried calling: ptk="Person"
The relevant error-causing widget was
MaterialApp

I just figure out and modified the code in api.dart我只是弄清楚并修改了 api.dart 中的代码

api.dart api.dart

uploadInitRPP(
    InitRPP initRPP, bool isUpdating, Function initRPPUploaded) async {
  CollectionReference initRPPRef = Firestore.instance.collection('RPP');

  if (isUpdating) {
    initRPP.updatedAt = Timestamp.now();

    await initRPPRef.document(initRPP.id).updateData(initRPP.toMap());
    initRPPUploaded(initRPP);
    print('update Data Awal RPP dengan id: ${initRPP.id}');
  } else {
    initRPP.createdAt = Timestamp.now();

    final FirebaseAuth auth = FirebaseAuth.instance;
    final FirebaseUser user = await auth.currentUser();
    final uid = user.uid;
    final udn = user.displayName;

    DocumentReference documentRef = await initRPPRef.add(initRPP.toMap());

    initRPP.id = documentRef.documentID;
    initRPP.uid = uid;
    initRPP.ptk = udn;

    print('unggah Data Awal RPP sukses: ${initRPP.toString()}');

    await documentRef.setData(initRPP.toMap(), merge: true);
    initRPPUploaded(initRPP);
  }
}

One way would be to create a collection of Users and store user data with user id as the documentID and after signing-in, use the UserID to access all the details of the User.一种方法是创建用户集合并使用用户 ID 作为 documentID 存储用户数据,并在登录后使用用户 ID 访问用户的所有详细信息。 This way you will be able to save user data into cloud firestore and also get data like name email etc as well.这样,您将能够将用户数据保存到云 Firestore 中,还可以获取名称 email 等数据。 you can store user data into cloud firestore like this.您可以像这样将用户数据存储到云 Firestore 中。

  final CollectionReference userCollection =
  Firestore.instance.collection('userData');

  Future<void> updateUserData(String name, String email, String phoneNumber,
  String address, String type) async {
   return await userCollection.document(uid).setData({
  'Name': name,
  'Email': email,
  'Phone Number': phoneNumber,
  'Address': address,
});

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Flutter 中的 Firebase 获取 uid? - How to get uid from Firebase in Flutter? Flutter 使用 Cloud Firestore 和 Firebase Auth 存储用户数据 - Flutter store users data with Cloud Firestore and Firebase Auth 如何在使用 firebase Auth 注册用户时保存用户的 UID - How to save the UID of a user on registering the user using firebase Auth 如何在 Firebase Firestore 中添加自动 uid 字段 - How to add auto uid field in Firebase Firestore 在 Firestore 中,如何获取 Firebase Authentication 的 uid 为文档? - In Firestore, how to get the uid of Firebase Authentication to be a document? 如何在 Xamarin 中同时使用 Firebase Cloud Messaging 和 Firebase Auth? - How to use both Firebase Cloud Messaging and Firebase Auth in Xamarin? 如何使用flutter在Firebase云Firestore中添加多个节点 - how to add multiple nodes in Firebase cloud Firestore using flutter 如何将列表 object 发布到 flutter 中的云 Firestore firebase - How to post list object to cloud firestore firebase in flutter 调用 DocumentSnapshot Firestore 后如何正确注销 Firebase 身份验证? - How to Properly SignOut Firebase auth after call DocumentSnapshot Firestore? 将Cloud Firestore和Firebase添加到Flutter项目(Android) - Adding Cloud Firestore & Firebase to Flutter project (Android)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM