Flutter TextField和Button组件开发登录页面案例

news2024/10/26 16:53:26

In this section, we’ll go through building a basic login screen using the Button and TextField widgets. We’ll follow a step-bystep approach, allowing you to code along and understand each part of the process. Let’s get started!

在本节中,我们将使用“Button”和“TextField”小部件构建一个基本的登录屏幕。我们将遵循一步一步的方法,允许您编写代码并理解过程的每个部分。我们开始吧!

Scenario: Creating a Login Screen

场景:创建登录界面

Imagine you’re building a mobile app that requires user authentication. You want users to be able to log in securely, so you need to design a login screen. This screen should include fields for users to enter their username and password, along with a “Login” button to initiate the authentication process. Additionally, you want to ensure that the password remains hidden as users type it.

假设您正在构建一个需要用户身份验证的移动应用程序。您希望用户能够安全登录,因此需要设计一个登录屏幕。该屏幕应该包括供用户输入用户名和密码的字段,以及用于启动身份验证过程的“Login”按钮。此外,您希望确保在用户键入密码时保持隐藏。

Step 1: Setting Up Your Project

步骤1:设置项目

Before we begin, make sure you have your Flutter project set up. If you haven’t done this yet, refer to previous sections for guidance.

在我们开始之前,确保你有你的Flutter项目设置。如果您还没有这样做,请参考前面的部分以获得指导。

Step 2: Building the Login Screen

步骤 2:创建登录屏幕

Open lib/main.dart: Open the lib/main.dart file in yourproject.

打开 lib/main.dart: 在您的项目中打开 lib/main.dart 文件。

Import Required Packages: Make sure you have thenecessary package imports at the top of the file:

导入所需软件包: 确保在文件顶部有必要的软件包导入:

import ‘package:flutter/material.dart’;

Create the Main Function: Replace the existing main function with the following code:

创建主函数: 用以下代码替换现有的 main 函数:

void main() {
	runApp(MyApp());
}

Create MyApp Class: Define the MyApp class as follows:

创建 MyApp 类: 定义 MyApp 类如下:

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: "用户登录",
      home: LoginScreen(),
    );
  }
}

Create LoginScreen Class: Now, let’s create the LoginScreen class inside the lib folder. This will be the main screen of our app:

class LoginScreen extends StatelessWidget {
  const LoginScreen({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("用户登录"),
      ),
      body: Center(
          child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[],
        ),
      )),
    );
  }
}

Add TextFields and Button: Inside the Column widget, add the following code to create two TextField widgets for username and password inputs, and an ElevatedButton for login:

添加文本字段和按钮: 在 “列 ”部件中添加以下代码,创建两个用于输入用户名和密码的 TextField 部件,以及一个用于登录的 ElevatedButton:

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    const TextField(
      decoration: InputDecoration(labelText: "账号"),
    ),
    const SizedBox(height: 20),
    const TextField(
      decoration: InputDecoration(labelText: "密码"),
      obscureText: true,
    ),
    const SizedBox(height: 20),
    ElevatedButton(
      onPressed: () {
        // Add your login logic here
      },
      child: const Text("登录"),
    ),
  ],
),

此时main.dart的完整代码如下:

import "package:flutter/material.dart";

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: "用户登录",
      home: LoginScreen(),
    );
  }
}

class LoginScreen extends StatelessWidget {
  const LoginScreen({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("用户登录"),
      ),
      body: Center(
          child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const TextField(
                  decoration: InputDecoration(labelText: "账号"),
                ),
                const SizedBox(height: 20),
                const TextField(
                  decoration: InputDecoration(labelText: "密码"),
                  obscureText: true,
                ),
                const SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                    // Add your login logic here
                  },
                  child: const Text("登录"),
                ),
              ],
            ),
          ],
        ),
      )),
    );
  }
}

效果预览如下:

在这里插入图片描述

Step 3: Exploring the Code

步骤 3:探索代码

Inside the LoginScreen widget, we’ve added two TextField widgets for username and password input, along with a SizedBox to create spacing.

在 LoginScreen 部件中,我们添加了两个用于输入用户名和密码的 TextField 部件,以及一个用于创建间距的 SizedBox。

TextField (Username Input): The first TextField widget allows users to enter their username. We’ve used the decoration property with the InputDecoration class to provide a visual hint (label) inside the text field. The labelText parameter sets the label for the text field, helping users understand what to enter.

TextField(用户名输入): 第一个 TextField 部件允许用户输入用户名。我们使用 InputDecoration 类的装饰属性在文本字段内提供视觉提示(标签)。labelText 参数设置了文本字段的标签,帮助用户了解要输入的内容。

TextField (Password Input): The second TextField widget is used for password input. For security reasons, we’ve set the obscureText property to true. This property hides the entered text, displaying it as dots, asterisks, or other obscured characters. This way, sensitive information like passwords remains hidden.

TextField(密码输入): 第二个 TextField widget 用于密码输入。出于安全考虑,我们将 obscureText 属性设置为 true。该属性会隐藏输入的文本,显示为点、星号或其他模糊字符。这样,像密码这样的敏感信息就会被隐藏起来。

SizedBox: This widget creates a space between the text fields and the button, providing visual separation and improving the layout. The height parameter in SizedBox sets the amount of vertical space between widgets.

SizedBox: 该部件可在文本字段和按钮之间创建一个空间,提供视觉分隔并改善布局。SizedBox 中的高度参数设置了部件之间的垂直空间大小。

ElevatedButton: This widget serves as the login button. For now, the onPressed property is empty. You can later add your login logic here.

ElevatedButton: 该部件用作登录按钮。目前,onPressed 属性为空。您可以稍后在此处添加登录逻辑。

Step 4: Run Your App

步骤 4:运行应用程序

Save your changes and run the app using the command:

保存更改并使用命令运行应用程序:

flutter run

Step 5: Exploring the Login Screen

步骤 5:探索登录屏幕

As the app launches, you’ll see a simple login screen with fields for entering a username and password, along with a “Login” button. Although the button doesn’t currently perform any action, this example provides a foundation for adding authentication logic and creating a functional login experience.

应用程序启动后,您会看到一个简单的登录屏幕,上面有输入用户名和密码的字段,以及一个 “登录 ”按钮。虽然按钮目前不执行任何操作,但这个示例为添加身份验证逻辑和创建功能性登录体验奠定了基础。

代码优化

之前的代码有一个不必要的Column组件嵌套, 去掉后改写如下:

import "package:flutter/material.dart";

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: "用户登录",
      home: LoginScreen(),
    );
  }
}

class LoginScreen extends StatelessWidget {
  const LoginScreen({super.key});

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("用户登录"),
      ),
      body: Center(
          child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const TextField(
              decoration: InputDecoration(labelText: "账号"),
            ),
            const SizedBox(height: 20),
            const TextField(
              decoration: InputDecoration(labelText: "密码"),
              obscureText: true,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // Add your login logic here
              },
              child: const Text("登录"),
            ),
          ],
        ),
      )),
    );
  }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2224080.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Python爬虫系列】_031.Scrapy_模拟登陆中间件

课 程 推 荐我 的 个 人 主 页:👉👉 失心疯的个人主页 👈👈入 门 教 程 推 荐 :👉👉 Python零基础入门教程合集 👈👈虚 拟 环 境 搭 建 :👉👉 Python项目虚拟环境(超详细讲解) 👈👈PyQt5 系 列 教 程:👉👉 Python GUI(PyQt5)教程合集 👈👈…

ArcGIS001:ArcGIS10.2安装教程

摘要&#xff1a;本文详细介绍arcgis10.2的安装、破解、汉化过程。 一、软件下载 安装包链接&#xff1a;https://pan.baidu.com/s/1T3UJ7t_ELZ73TH2wGOcfpg?pwd08zk 提取码&#xff1a;08zk 二、安装NET Framework 3.5 双击打开控制面板&#xff0c;点击【卸载程序】&…

World of Warcraft [CLASSIC][80][the Ulduar]

Ulduar 奥杜尔副本介绍 奥杜尔共计14个BOSS&#xff0c;通常说的10H就是10个苦难模式就是全通&#xff0c;9H就是除了【观察者奥尔加隆】&#xff0c;特别说明开启【观察者奥尔加隆】&#xff0c;是需要打掉困难模式4个守护者的。 所以人们经常说的类似“10H 观察者”、“10H…

Python开发日记 -- 实现bin文件的签名

目录 1.数据的不同表现形式签名值不一样&#xff1f; 2.Binascii模块简介 3.问题定位 4.问题总结 1.数据的不同表现形式签名值不一样&#xff1f; Happy Muscle试运行了一段时间&#xff0c;组内同事再一次提出了新的需求&#xff1a;需要对bin文件签名。 PS&#xff1a;服…

react18中的函数组件底层渲染原理分析

react 中的函数组件底层渲染原理 react组件没有局部与全局之分&#xff0c;它是一个整体。这点跟vue的组件化是不同的。要实现 react 中的全局组件&#xff0c;可以将组件挂在react上&#xff0c;这样只要引入了react&#xff0c;就可以直接使用该组件。 函数式组件的创建 …

Kafka之消费者客户端

1、历史上的二个版本 与生产者客户端一样&#xff0c;在Kafka的发展过程当中&#xff0c;消费者客户端主要有两个大的版本&#xff1a; 旧消费者客户端&#xff08;Old Consumer&#xff09;&#xff1a;基于Scala语言开发的版本&#xff0c;又称为Scala消费者客户端。新消费…

【力扣】GO解决子序列相关问题

文章目录 一、引言二、动态规划方法论深度提炼子序列问题的通用解法模式 三、通用方法论应用示例&#xff1a;最长递增子序列&#xff08;LeetCode题目300&#xff09;Go 语言代码实现 四、最长连续递增序列&#xff08;LeetCode题目674&#xff09;Go 语言代码实现 五、最长重…

ffmpeg视频滤镜:定向模糊-dblur

滤镜简述 dblur 官网链接 > https://ffmpeg.org/ffmpeg-filters.html#dblur 有一个模糊滤镜&#xff0c;我试了一下&#xff0c;没有感觉到它的特殊之处, 这里简单介绍一下。 滤镜使用 滤镜的参数 angle <float> ..FV.....T. set angle (from 0 t…

找不到包的老版本???scikit-learn,numpy,scipy等等!!

废话不多说 直接上链接了&#xff1a; https://pypi.tuna.tsinghua.edu.cn/simple/https://pypi.tuna.tsinghua.edu.cn/simple/https://pypi.tuna.tsinghua.edu.cn/simple/xxx/ 后面的这个xxx就是包的名字 大家需要什么包的版本&#xff0c;直接输进去就可以啦 举个栗子&#…

零基础Java第十期:类和对象(一)

目录 一、拜访对象村 1.1. 什么是面向对象 1.2. 面向对象与面向过程 二、类定义和使用 2.1. 类的定义格式 2.2. 类的定义练习 三、类的实例化 3.1. 什么是实例化 3.2. 类和对象的说明 四、this引用 4.1. 什么是this引用 4.2. this引用的特性 一、拜访对象村 在…

<项目代码>YOLOv8路面病害识别<目标检测>

YOLOv8是一种单阶段&#xff08;one-stage&#xff09;检测算法&#xff0c;它将目标检测问题转化为一个回归问题&#xff0c;能够在一次前向传播过程中同时完成目标的分类和定位任务。相较于两阶段检测算法&#xff08;如Faster R-CNN&#xff09;&#xff0c;YOLOv8具有更高的…

STMicroelectronics意法半导体车规芯片系列--亿配芯城(ICgoodFind)

在汽车电子领域&#xff0c;意法半导体的车规级芯片系列一直备受瞩目。亿配芯城作为电子元器件领域的可靠供应商&#xff0c;为大家介绍意法半导体车规级芯片系列的卓越之处。 意法半导体在车规级芯片领域拥有深厚的技术积累和丰富的经验。 其车规级芯片涵盖了多个关键领域&am…

8.three.js相机详解

8.three.js相机详解 1、 认识相机 在Threejs中相机的表示是THREE.Camera&#xff0c;它是相机的抽象基类&#xff0c;其子类有两种相机&#xff0c;分别是正投影相机THREE.OrthographicCamera和透视投影相机THREE.PerspectiveCamera&#xff1a; 正投影和透视投影的区别是&am…

【Java】常用方法合集

以 DemoVo 为实体 import lombok.Data; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;Data ExcelIgnoreUnannotated public class ExportPromoteUnitResult {private String id;ExcelProperty(value &qu…

贪心算法记录 - 下

135. 分发糖果 困难 n 个孩子站成一排。给你一个整数数组 ratings 表示每个孩子的评分。 你需要按照以下要求&#xff0c;给这些孩子分发糖果&#xff1a; 每个孩子至少分配到 1 个糖果。相邻两个孩子评分更高的孩子会获得更多的糖果。 请你给每个孩子分发糖果&#xff0c…

一文搞懂指令周期,机器周期和时钟周期

如图&#xff1a; 指令周期 > 机器周期 > 时钟周期 指令周期&#xff1a;一个指令&#xff0c;从取值到执行的全部周期。一个指令执行过程包括取值&#xff0c;译码和执行阶段。 机器周期&#xff1a;,取指、间址、执行和中断等 时钟周期&#xff1a;时钟频率的倒数&am…

什么样的JSON编辑器才好用

简介 JSON&#xff08;JavaScript Object Notation&#xff09;是一种轻量级的数据交换格式&#xff0c;易于人阅读和编写&#xff0c;同时也便于机器解析和生成。随着互联网和应用程序的快速发展&#xff0c;JSON已经成为数据传输和存储的主要格式之一。在处理和编辑JSON数据…

python查询并安装项目所依赖的所有包

引言 如果需要进行代码的移植&#xff0c;肯定少不了在另一台pc或者服务器上进行环境的搭建&#xff0c;那么首先是要知道在已有的工程的代码中用到了哪些包&#xff0c;此时&#xff0c;如果是用人工去一个一个的代码文件中去查看调用了哪些包&#xff0c;这个工作甚是繁琐。…

推荐一款三维数值建模软件:3DEC

3DEC是一种用于土壤、岩石、地下水、结构支撑和砖石等高级岩土工程分析的三维数值建模软件。该软件的数值公式基于离散元法(DEM)进行不连续建模。UDEC是它的二维版本。不连续材料是一组离散的块。不连续性充当着块之间的边界条件。允许块的大位移和旋转。常见的结构可以直接从地…

HTML5教程(一)- 网页与开发工具

1. 什么是网页 网页 基于浏览器阅读的应用程序&#xff0c;是数据&#xff08;文本、图像、视频、声音、链接等&#xff09;展示的载体常见的是以 .html 或 .htm 结尾的文件 网站 使用 HTML 等制作的用于展示特定内容相关的网页集合。 2. 网页的组成 浏览器 代替用户向服务…