97 lines
3.4 KiB
Dart
97 lines
3.4 KiB
Dart
import 'package:flutter/foundation.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||
|
||
/// ============================================================
|
||
/// TextField 输入框演示页(登录表单)
|
||
///
|
||
/// 一、两种使用方式:
|
||
/// 1. 直接运行本页面:runApp(const MaterialApp(home: InputDemoPage()))
|
||
/// 2. 复制 body 核心代码到任意 Scaffold 的 body 中。
|
||
///
|
||
/// 二、核心知识点:
|
||
/// 1. TextEditingController 管理输入框内容,读取用 controller.text;
|
||
/// 2. 控制器必须在 dispose() 里释放,否则内存泄漏;
|
||
/// 3. obscureText 控制密码明文/密文(配合 setState 做"眼睛"切换);
|
||
/// 4. 注意:Scaffold 没有 padding 参数!外层间距要用 body 里的 Padding。
|
||
/// ============================================================
|
||
class InputDemoPage extends StatefulWidget {
|
||
const InputDemoPage({super.key});
|
||
|
||
@override
|
||
State<InputDemoPage> createState() => _InputDemoPageState();
|
||
}
|
||
|
||
class _InputDemoPageState extends State<InputDemoPage> {
|
||
// 控制器:负责管理输入框内容
|
||
final TextEditingController _userCtrl = TextEditingController();
|
||
final TextEditingController _pwdCtrl = TextEditingController();
|
||
// 密码是否明文显示(默认密文)
|
||
bool _showPwd = false;
|
||
|
||
@override
|
||
void dispose() {
|
||
// 释放控制器,防止内存泄漏
|
||
_userCtrl.dispose();
|
||
_pwdCtrl.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return Scaffold(
|
||
appBar: AppBar(title: const Text('TextField 登录表单 Demo')),
|
||
body: Padding(
|
||
// Scaffold 没有 padding 参数,间距写在 body 的 Padding 上
|
||
padding: EdgeInsets.all(20.w),
|
||
child: Column(
|
||
children: [
|
||
TextField(
|
||
controller: _userCtrl,
|
||
keyboardType: TextInputType.phone, // 弹数字键盘
|
||
decoration: const InputDecoration(
|
||
labelText: "手机号",
|
||
hintText: "请输入11位手机号",
|
||
prefixIcon: Icon(Icons.phone),
|
||
border: OutlineInputBorder(),
|
||
),
|
||
),
|
||
SizedBox(height: 16.h),
|
||
TextField(
|
||
controller: _pwdCtrl,
|
||
obscureText: !_showPwd, // 密文/明文由状态决定
|
||
decoration: InputDecoration(
|
||
labelText: "密码",
|
||
hintText: "请输入密码",
|
||
prefixIcon: const Icon(Icons.lock),
|
||
border: const OutlineInputBorder(),
|
||
// suffixIcon:右侧小眼睛,点击切换明文
|
||
suffixIcon: IconButton(
|
||
icon: Icon(_showPwd ? Icons.visibility : Icons.visibility_off),
|
||
onPressed: () {
|
||
setState(() {
|
||
_showPwd = !_showPwd; // 修改状态触发重建
|
||
});
|
||
},
|
||
),
|
||
),
|
||
),
|
||
SizedBox(height: 24.h),
|
||
ElevatedButton(
|
||
onPressed: () {
|
||
// 获取输入内容
|
||
String user = _userCtrl.text;
|
||
String pwd = _pwdCtrl.text;
|
||
if (kDebugMode) {
|
||
print("账号:$user,密码11:$pwd");
|
||
}
|
||
},
|
||
child: const Text("登录"),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|