Скрытый ввод пароля в Flutter
Параметр obscureText у
TextField
заменяет символы пароля маркерами. Пока
он равен true, набранный текст
не читается с плеча.
Кнопку «показать пароль» обычно ставят
в suffixIcon у InputDecoration -
это IconButton
с иконкой глаза. Контроллер хранит
настоящие символы, меняется только
отображение. Флаг obscureText
хранят в State
и переключают через setState:
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: HomePage()));
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool hidePassword = true;
final passwordController = TextEditingController();
@override
void dispose() {
passwordController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: passwordController,
obscureText: hidePassword,
decoration: InputDecoration(
labelText: 'Password',
border: const OutlineInputBorder(),
suffixIcon: IconButton(
onPressed: () {
setState(() {
hidePassword = !hidePassword;
});
},
icon: Icon(
hidePassword
? Icons.visibility // hidden: tap to show
: Icons.visibility_off,
),
),
),
),
),
);
}
}
Соберите поле 'Password' с
obscureText и кнопкой в
suffixIcon, которая переключает
видимость. Начальное состояние -
пароль скрыт.