简体   繁体   中英

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.

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

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

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. This way you will be able to save user data into cloud firestore and also get data like name email etc as well. you can store user data into cloud firestore like this.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM