簡體   English   中英

與相關用戶一起將數據添加到集合 Firestore flutter

[英]Adding data to collection firestore flutter with relevant user


這只是一些基本的注冊用戶界面
我需要在用戶注冊時發送這些數據。
目前我需要發送名字和姓氏。
發送數據沒問題,但它們沒有字段。
當我點擊注冊按鈕時,有沒有辦法添加用戶 ID?
那么如何根據相關用戶發送該數據???
以及如何與相關用戶檢索該數據?
希望你能幫助我
謝謝

class RegisterView extends StatefulWidget {
  const RegisterView({Key? key}) : super(key: key);

  @override
  State<RegisterView> createState() => _RegisterViewState();
}

class _RegisterViewState extends State<RegisterView> {
  late final TextEditingController _email;
  late final TextEditingController _password;
  late final TextEditingController _firstName;
  late final TextEditingController _lastName;
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    _email = TextEditingController();
    _password = TextEditingController();
    _firstName = TextEditingController();
    _lastName = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _firstName.dispose();
    _lastName.dispose();
    _email.dispose();
    _password.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 185, 185, 185),
      appBar: AppBar(
        backgroundColor: const Color.fromARGB(255, 87, 127, 160),
        elevation: 0,
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
          ),
        ),
      ),
      body: ListView(
        children: [
          Container(
            height: 150,
            padding: const EdgeInsets.only(top: 40),
            decoration: const BoxDecoration(
              color: Color.fromARGB(255, 87, 127, 160),
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(150),
                bottomRight: Radius.circular(150),
              ),
            ),
            child: const Text(
              'Create New Account',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 35,
                color: Colors.black,
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 40,
              vertical: 30,
            ),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  // First name and last name
                  Row(
                    children: [
                      Flexible(
                        // First Name
                        child: TextFormField(
                          decoration: const InputDecoration(
                            labelText: 'First Name',
                          ),
                          validator: (val) => val!.isEmpty ? 'requied*' : null,
                          controller: _firstName,
                        ),
                      ),
                      const SizedBox(
                        width: 20.0,
                      ),
                      Flexible(
                        // Last Name
                        child: TextFormField(
                          decoration: const InputDecoration(
                            labelText: 'Last Name',
                          ),
                          validator: (val) => val!.isEmpty ? 'requied*' : null,
                          controller: _lastName,
                        ),
                      ),
                    ],
                  ),
                  // Email Address
                  TextFormField(
                    decoration: const InputDecoration(
                      labelText: 'Email address',
                    ),
                    keyboardType: TextInputType.emailAddress,
                    controller: _email,
                    validator: (val) => val!.isEmpty ? 'requied*' : null,
                  ),
                  // Password
                  TextFormField(
                    decoration: const InputDecoration(
                      labelText: 'Create a Password',
                    ),
                    controller: _password,
                    obscureText: true,
                    enableSuggestions: false,
                    autocorrect: false,
                    validator: (val) => (val!.isEmpty && val.length < 5)
                        ? 'Enter a password with more than 6 characters'
                        : null,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  // Sign Up Button
                  TextButton(
                    style: TextButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 0, 132, 255),
                    ),
                    onPressed: () async {
                      final email = _email.text;
                      final password = _password.text;
                      if (_formKey.currentState!.validate()) {
                        try {
                          final userCredential =
                              await AuthService.firebase().register(
                            email: email,
                            password: password,
                          );
                          Map<String, dynamic> data = {
                            'first_name': _firstName.text,
                            'last_name': _lastName.text,
                          };
                          await FirebaseFirestore.instance
                              .collection('user')
                              .add(data);
                          devtools.log(userCredential.toString());
                          await showErrorDialog(
                            context,
                            'Registration Successful !\nYou can log in now.',
                          ).then(
                            (value) {
                              Navigator.of(context).pushNamedAndRemoveUntil(
                                  loginRoute, (route) => false);
                            },
                          );
                        } on InvalidEmailAuthException {
                          await showErrorDialog(
                            context,
                            'Invalid email',
                          );
                        } on WeakPasswordAuthException {
                          await showErrorDialog(
                            context,
                            'Weak password',
                          );
                        } on EmailAlreadyUsedAuthException {
                          await showErrorDialog(
                            context,
                            'Email already in use',
                          );
                        } on GenericAuthException {
                          await showErrorDialog(
                            context,
                            'Failed to register',
                          );
                        }
                      }
                    },
                    child: const Text(
                      'Sign Up',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

您當前用於編寫用戶數據的代碼是:

FirebaseFirestore.instance
  .collection('user')
  .add(data);

這會為數據生成一個唯一 ID。

如果要將數據存儲在用戶的 UID 下,可以使用:

FirebaseFirestore.instance
  .collection('user')
  .doc(userCredential.user!.uid)
  .set(data);

另見:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM