點燈坊

失くすものさえない今が強くなるチャンスよ

TextFormField 實現 Password 輸入

Sam Xiao's Avatar 2024-10-23

Flutter 並沒有特別提供 Password,可透過 TextFormField 實現。

Version

Flutter 3.24

Flutter

password01

  • 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 來 toggle
  • decoration:對 TextFormField 裝飾 style
    • labelText:設定 label
    • suffixIcon:設定是否顯示密碼的 icon
      • onPressed():toggle 是否顯示密碼

Conclusion

  • obscureText 可隱藏輸入,藉此模擬 password 輸入
  • decorationsuffixIcon 可設定在 TextFormField 內的 IconButton