Flutter实战一Flutter聊天应用(十三)

119 篇文章 9 订阅
82 篇文章 1416 订阅

提交用户的注册信息

我们现需要将用户的注册信息保存到Firebase实时数据库,在Firebase控制台中,更改Firebase实时数据库的安全规则,选择“Database > 规则”,规则如下所示:

{
  "rules": {
    "users":{
      ".read": true,
        ".write": true
    },
    "messages": {
      ".read": true,
      ".write": "auth != null && auth.provider == 'google'"
    }
  }
}

然后在sign_up.dart文件的SignUpState类中添加_userLogUp方法,代码如下所示:

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
//...
class SignUpState extends State<SignUp> {
  //...
  final reference = FirebaseDatabase.instance.reference().child('users');
  //...
  void _userLogUp(String username, String password, {String email, String phone}){
    reference.push().set({
      'name': username,
      'password': password,
      'email': email,
      'phone': phone,
    });
  }
  //...
}

SignUpState类的build方法中修改Join按钮的点击事件,代码如下所示:

class SignUpState extends State<SignUp> {
  //...
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        //...
            new FlatButton(
              child: new Container(
                //...
                child: new Center(
                    child: new Text("Join",
                        style: new TextStyle(
                          color: const Color(0xff000000),
                        ))),
              ),
              onPressed: () {
                _userLogUp(_usernameController.text, _passwordController.text,
                    email: _emailController.text, phone: _phoneController.text);
              },
            ),
        //...
}

现在我们在注册屏幕中点击Join按钮就会提交用户信息到Firebase实时数据库。

这里写图片描述

检查用户的输入内容

我们现在已经可以上传用户的注册信息,现在需要添加对注册信息的检查功能。在我们的应用程序中,注册信息有以下限制:用户名不能为空且大于等于三位,密码不能为空且大于等于六位。

class SignUpState extends State<SignUp> {
  //...
  String _correctUsername = "";
  String _correctPassword = "";
  //...
}

首先我们在SignUpState类的添加两个成员变量_correctUsername_correctPassword,存储用户名和密码的错误信息,同时根据它们是否为空来判断用户输入是否符合条件。

class SignUpState extends State<SignUp> {
          //...
                      new TextField(
                        controller: _usernameController,
                        decoration: new InputDecoration(
                          hintText: 'Username',
                          errorText: (_correctUsername == "")
                              ? null
                              : _correctUsername,
                          icon: new Icon(
                            Icons.account_circle,
                          ),
                        ),
                        onChanged: (String value) {
                          setState(() {
                            if (value.isEmpty) {
                              _correctUsername = "Username cannot be empty";
                            } else if (value.trim().length < 3) {
                              _correctUsername =
                                  "Username length is less than 3 bits";
                            } else {
                              _correctUsername = "";
                            }
                          });
                        },
                      ),
                      new TextField(
                        controller: _passwordController,
                        obscureText: true,
                        keyboardType: TextInputType.number,
                        decoration: new InputDecoration(
                          hintText: 'Password',
                          errorText: (_correctPassword == "")
                              ? null
                              : _correctPassword,
                          icon: new Icon(
                            Icons.lock_outline,
                          ),
                        ),
                        onChanged: (String value) {
                          setState(() {
                            if (value.isEmpty) {
                              _correctPassword = "Password cannot be empty";
                            } else if (value.trim().length < 6) {
                              _correctPassword =
                                  "Password length is less than 6 bits";
                            } else {
                              _correctPassword = "";
                            }
                          });
                        },
                      ),
          //...
}

这里写图片描述

现在用户输入时应用程序会给予对应的错误提示,我们还需要在用户点击Join按钮时再次检查用户名与密码,如果存在错误则弹出消息提示。弹出消息提示是比较常用的操作之一,因此我们可以单独封装起来,在项目的lib目录下创建一个prompt_page.dart文件,并添加下面的代码:

import 'package:flutter/material.dart';

class PromptPage {
  showMessage(BuildContext context, String text) {
    showDialog<Null>(
        context: context,
        child: new AlertDialog(
            title: new Text("Alert"),
            content: new Text(text),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('OK'))
            ]));
  }
}

然后我们回到sign_up.dart文件中来,在SignUpState类中添加PromptPage类型的promptPage成员变量。同时添加成员方法_handleSubmitted用于处理用户点击Join按钮时的操作。

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'dart:async';
import 'prompt_page.dart';
//...
class SignUpState extends State<SignUp> {
  //...
  PromptPage promptPage = new PromptPage();
  //...
  Future _handleSubmitted() async {
    if (_usernameController.text == '' || _passwordController.text == '') {
      await promptPage.showMessage(
          context, "Username or password cannot be empty!");
      return;
    } else if (_correctUsername.isNotEmpty || _correctPassword.isNotEmpty) {
      await promptPage.showMessage(
          context, "Username or password format is incorrect!");
      return;
    }
    _userLogUp(_usernameController.text, _passwordController.text,
        email: _emailController.text, phone: _phoneController.text);
  }
  //...
}

然后我们需要在SignUpState类的build方法中修改Join按钮的点击事件,代码如下所示:

class SignUpState extends State<SignUp> {
  //...
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        //...
            new FlatButton(
              child: new Container(
                //...
                child: new Center(
                    child: new Text("Join",
                        style: new TextStyle(
                          color: const Color(0xff000000),
                        ))),
              ),
              onPressed: () {
                _handleSubmitted();
              },
            ),
        //...
}

这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何小有

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值