用 Flutter 写一个精美的登录页面(最新版)
参考了博客:用flutter写一个精美的登录页面。但是那篇文章是 18 年的,较多 API 已经更新,本篇博文在其基础上使用最新版本 Dart 和 Flutter 开发。
完整源码在文章最后,有需要可以直接看源码。
效果图:


该页面的主体布局如下:
Scaffold,没有 AppBarFormListView 作为外层控件return Scaffold(
body: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 20),
children: [
const SizedBox(height: kToolbarHeight), // 距离顶部一个工具栏的高度
buildTitle(), // Login
buildTitleLine(), // 标题下面的下滑线
const SizedBox(height: 50),
buildEmailTextField(), // 输入邮箱
const SizedBox(height: 30),
buildPasswordTextField(context), // 输入密码
buildForgetPasswordText(context), // 忘记密码
const SizedBox(height: 50),
buildLoginButton(context), // 登录按钮
const SizedBox(height: 30),
buildOtherLoginText(), // 其他账号登录
buildOtherMethod(context), // 其他登录方式
buildRegisterText(context), // 注册
],
),
),
);

大标题 Titile 比较简单,就是设置了 边距 和 文字大小:
Padding 组件:设置边距Text 组件:显示文本及控制样式Widget buildTitle() {
return const Padding( // 设置边距
padding: EdgeInsets.all(8),
child: Text(
'Login',
style: TextStyle(fontSize: 42),
));
}
Title 下面的下划线其实就是个设置了宽高的 Container:
Align 组件:用于控制子组件的对齐方式Container 组件:一个包含绘画、定位、大小的组件Widget buildTitleLine() {
return Padding(
padding: const EdgeInsets.only(left: 12.0, top: 4.0),
child: Align(
alignment: Alignment.bottomLeft,
child: Container(
color: Colors.black,
width: 40,
height: 2,
),
));
}

邮箱输入框:使用正则对输入进行校验
TextFormField 组件:用于 Form 中的文本输入框validator 属性用于对输入框进行表单校验onSave 属性当表单校验通过后执行一些操作何时进行表单校验是
From组件中的一个属性
Widget buildEmailTextField() {
return TextFormField(
decoration: const InputDecoration(labelText: 'Email Address'),
validator: (v) {
var emailReg = RegExp(
r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
if (!emailReg.hasMatch(v!)) {
return '请输入正确的邮箱地址';
}
},
onSaved: (v) => _email = v!,
);
}
密码输入框:
obscureText 属性控制表单文字的显示与隐藏,我们使用自定义变量来实现点击按钮隐藏或显示密码功能suffixIcon 属性是在输入框后面加一个图标,给它一个点击方法是改变是否显示密码,并更改图标的颜色_isObscure 控制输入框密码的可见性,涉及到界面显示的更新,因此要更新 _isObscure 的代码放在 setState 中。Widget buildPasswordTextField(BuildContext context) {
return TextFormField(
obscureText: _isObscure, // 是否显示文字
onSaved: (v) => _password = v!,
validator: (v) {
if (v!.isEmpty) {
return '请输入密码';
}
},
decoration: InputDecoration(
labelText: "Password",
suffixIcon: IconButton(
icon: Icon(
Icons.remove_red_eye,
color: _eyeColor,
),
onPressed: () {
// 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
setState(() {
_isObscure = !_isObscure;
_eyeColor = (_isObscure
? Colors.grey
: Theme.of(context).iconTheme.color)!;
});
},
)));
}
密码输入框下面还有一行 “忘记密码?” 的文本,利用 Align 组件将其靠右对齐
Widget buildForgetPasswordText(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
// Navigator.pop(context);
print("忘记密码");
},
child: const Text("忘记密码?",
style: TextStyle(fontSize: 14, color: Colors.grey)),
),
),
);
}

登录按钮:
ElevatedButton 组件是一个常见的,点击后有波纹效果的按钮Widget buildLoginButton(BuildContext context) {
return Align(
child: SizedBox(
height: 45,
width: 270,
child: ElevatedButton(
style: ButtonStyle(
// 设置圆角
shape: MaterialStateProperty.all(const StadiumBorder(
side: BorderSide(style: BorderStyle.none)))),
child: Text('Login',
style: Theme.of(context).primaryTextTheme.headline5),
onPressed: () {
// 表单校验通过才会继续执行
if ((_formKey.currentState as FormState).validate()) {
(_formKey.currentState as FormState).save();
//TODO 执行登录方法
print('email: $_email, password: $_password');
}
},
),
),
);
}

其他登录方式:
ButtonBar 组件用于构建多个按钮的排列(方向可控)map 是个高阶函数,可以对 数组的每个元素进行某种操作,最后再归约成数组SnackBar 是一种从底部出现的轻量级弹窗final List _loginMethod = [
{
"title": "facebook",
"icon": Icons.facebook,
},
{
"title": "google",
"icon": Icons.fiber_dvr,
},
{
"title": "twitter",
"icon": Icons.account_balance,
},
];
Widget buildOtherMethod(context) {
return ButtonBar(
alignment: MainAxisAlignment.center,
children: _loginMethod
.map((item) => Builder(builder: (context) {
return IconButton(
icon: Icon(item['icon'],
color: Theme.of(context).iconTheme.color),
onPressed: () {
//TODO: 第三方登录方法
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${item['title']}登录'),
action: SnackBarAction(
label: '取消',
onPressed: () {},
)),
);
});
}))
.toList(),
);
}
注册按钮:
GestureDetector 是手势检测器,用它包裹组件后可以实现对该组件的各种手势的监听,例如:“单击”、“双击”、“长按” 等。Widget buildRegisterText(context) {
return Center(
child: Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('没有账号?'),
GestureDetector(
child: const Text('点击注册', style: TextStyle(color: Colors.green)),
onTap: () {
print("点击注册");
},
)
],
),
),
);
}
新建一个 Flutter 项目,替换其中 main.dart 的内容,即可运行起来。
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false, // 不显示右上角的 debug
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
// 注册路由表
routes: {
"/": (context) => const HomePage(title: "登录"), // 首页路由
});
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final GlobalKey _formKey = GlobalKey<FormState>();
late String _email, _password;
bool _isObscure = true;
Color _eyeColor = Colors.grey;
final List _loginMethod = [
{
"title": "facebook",
"icon": Icons.facebook,
},
{
"title": "google",
"icon": Icons.fiber_dvr,
},
{
"title": "twitter",
"icon": Icons.account_balance,
},
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: _formKey, // 设置globalKey,用于后面获取FormStat
autovalidateMode: AutovalidateMode.onUserInteraction,
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 20),
children: [
const SizedBox(height: kToolbarHeight), // 距离顶部一个工具栏的高度
buildTitle(), // Login
buildTitleLine(), // Login下面的下划线
const SizedBox(height: 60),
buildEmailTextField(), // 输入邮箱
const SizedBox(height: 30),
buildPasswordTextField(context), // 输入密码
buildForgetPasswordText(context), // 忘记密码
const SizedBox(height: 60),
buildLoginButton(context), // 登录按钮
const SizedBox(height: 40),
buildOtherLoginText(), // 其他账号登录
buildOtherMethod(context), // 其他登录方式
buildRegisterText(context), // 注册
],
),
),
);
}
Widget buildRegisterText(context) {
return Center(
child: Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('没有账号?'),
GestureDetector(
child: const Text('点击注册', style: TextStyle(color: Colors.green)),
onTap: () {
print("点击注册");
},
)
],
),
),
);
}
Widget buildOtherMethod(context) {
return ButtonBar(
alignment: MainAxisAlignment.center,
children: _loginMethod
.map((item) => Builder(builder: (context) {
return IconButton(
icon: Icon(item['icon'],
color: Theme.of(context).iconTheme.color),
onPressed: () {
//TODO: 第三方登录方法
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('${item['title']}登录'),
action: SnackBarAction(
label: '取消',
onPressed: () {},
)),
);
});
}))
.toList(),
);
}
Widget buildOtherLoginText() {
return const Center(
child: Text(
'其他账号登录',
style: TextStyle(color: Colors.grey, fontSize: 14),
),
);
}
Widget buildLoginButton(BuildContext context) {
return Align(
child: SizedBox(
height: 45,
width: 270,
child: ElevatedButton(
style: ButtonStyle(
// 设置圆角
shape: MaterialStateProperty.all(const StadiumBorder(
side: BorderSide(style: BorderStyle.none)))),
child: Text('Login',
style: Theme.of(context).primaryTextTheme.headline5),
onPressed: () {
// 表单校验通过才会继续执行
if ((_formKey.currentState as FormState).validate()) {
(_formKey.currentState as FormState).save();
//TODO 执行登录方法
print('email: $_email, password: $_password');
}
},
),
),
);
}
Widget buildForgetPasswordText(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 8),
child: Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () {
// Navigator.pop(context);
print("忘记密码");
},
child: const Text("忘记密码?",
style: TextStyle(fontSize: 14, color: Colors.grey)),
),
),
);
}
Widget buildPasswordTextField(BuildContext context) {
return TextFormField(
obscureText: _isObscure, // 是否显示文字
onSaved: (v) => _password = v!,
validator: (v) {
if (v!.isEmpty) {
return '请输入密码';
}
},
decoration: InputDecoration(
labelText: "Password",
suffixIcon: IconButton(
icon: Icon(
Icons.remove_red_eye,
color: _eyeColor,
),
onPressed: () {
// 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
setState(() {
_isObscure = !_isObscure;
_eyeColor = (_isObscure
? Colors.grey
: Theme.of(context).iconTheme.color)!;
});
},
)));
}
Widget buildEmailTextField() {
return TextFormField(
decoration: const InputDecoration(labelText: 'Email Address'),
validator: (v) {
var emailReg = RegExp(
r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
if (!emailReg.hasMatch(v!)) {
return '请输入正确的邮箱地址';
}
},
onSaved: (v) => _email = v!,
);
}
Widget buildTitleLine() {
return Padding(
padding: const EdgeInsets.only(left: 12.0, top: 4.0),
child: Align(
alignment: Alignment.bottomLeft,
child: Container(
color: Colors.black,
width: 40,
height: 2,
),
));
}
Widget buildTitle() {
return const Padding(
padding: EdgeInsets.all(8),
child: Text(
'Login',
style: TextStyle(fontSize: 42),
));
}
}
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?
我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的rubyyaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir
我的问题的一个例子是体育游戏。一场体育比赛有两支球队,一支主队和一支客队。我的事件记录模型如下:classTeam"Team"has_one:away_team,:class_name=>"Team"end我希望能够通过游戏访问一个团队,例如:Game.find(1).home_team但我收到一个单元化常量错误:Game::team。谁能告诉我我做错了什么?谢谢, 最佳答案 如果Gamehas_one:team那么Rails假设您的teams表有一个game_id列。不过,您想要的是games表有一个team_id列,在这种情况下
导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri