加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 14:57:12 所属栏目:百科 来源:网络整理
导读:提交用户的注册信息 我们现需要将用户的注册信息保存到Firebase实时数据库,在Firebase控制台中,更改Firebase实时数据库的安全规则,选择“Database 规则”,规则如下所示: { " rules ": { " users ": { " .read ": true ," .write ": true } ," messages

提交用户的注册信息

我们现需要将用户的注册信息保存到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,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",onPressed: () {
                _handleSubmitted();
              },//...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读