[譯]TextField/TextFormField 如何顯示/隱藏密碼

原文:Flutter: Show/Hide Password in TextField/TextFormField

TextField/TextFormField 里隱藏輸入的密碼,只需要設(shè)置屬性 obscureTexttrue

TextField(
   obscureText: true,
   /* ... */
),

效果如圖:

顯示輸入的密碼以便用戶可以看到實(shí)際輸入的內(nèi)容,設(shè)置屬性obscureTextfalse

TextField(
   obscureText: false,
   /* ... */
),

效果如圖:

完整示例

App 預(yù)覽

我們制作了一個(gè)簡(jiǎn)單的Flutter應(yīng)用,在屏幕中心包含 TextField widget(你也可以使用TextFormField)。用戶可以輸入密碼,并且可以通過(guò)widget右邊的“眼型”圖標(biāo)按鈕控制密碼的顯示和隱藏。

完整代碼

// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isObscure = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(25),
        child: Center(
          child: TextField(
            obscureText: _isObscure,
            decoration: InputDecoration(
                labelText: 'Password',
                suffixIcon: IconButton(
                    icon: Icon(
                        _isObscure ? Icons.visibility : Icons.visibility_off),
                    onPressed: () {
                      setState(() {
                        _isObscure = !_isObscure;
                      });
                    })),
          ),
        ),
      ),
    );
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容