Flutter 並沒有特別提供 Password
,可透過 TextFormField
實現。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
TextFormField
實現 Password 輸入
TextFormField
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() {
return _Home();
}
}
class _Home extends State<Home> {
var _obscureText = true;
Widget build(BuildContext context) {
var appBar = AppBar(title: const Text('TextFormField Password'));
var password = TextFormField(
obscureText: _obscureText,
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility_off : Icons.visibility,
),
onPressed: () => setState(() => _obscureText = !_obscureText),
),
),
);
var submit = ElevatedButton(
onPressed: () {},
child: const Text('Submit'),
);
var body = Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
password,
const SizedBox(height: 20),
submit,
],
),
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 13
var _obscureText = true;
_obscureText
:是否顯示 password
Line 19
var password = TextFormField(
obscureText: _obscureText,
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility_off : Icons.visibility,
),
onPressed: () => setState(() => _obscureText = !_obscureText),
),
),
);
obscureText
:是否顯示輸入密碼,會搭配_obscureText
state 來 toggledecoration
:對 TextFormField 裝飾 stylelabelText
:設定 labelsuffixIcon
:設定是否顯示密碼的 icononPressed()
:toggle 是否顯示密碼
Conclusion
obscureText
可隱藏輸入,藉此模擬 password 輸入decoration
的suffixIcon
可設定在TextFormField
內的IconButton