[英]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.