建立並設計文字欄位 (text field)
如何實作文字欄位 (text field)。
文字欄位 (text fields) 允許使用者在應用程式中輸入文字。 它們常用於建立表單、傳送訊息、打造搜尋體驗等多種情境。 在本教學中,將介紹如何建立並設計文字欄位 (text fields)。
Flutter 提供了兩種文字欄位 (text fields):
TextField
與 TextFormField。
TextField
#
TextField 是最常用的文字輸入元件 (Widget)。
預設情況下,TextField 會以底線進行裝飾 (underline)。
你可以透過提供 InputDecoration
作為 TextField 的 decoration
屬性,
來加入標籤 (label)、圖示 (icon)、內嵌提示文字 (inline hint text) 以及錯誤訊息 (error text)。
若要完全移除裝飾(包含底線與為標籤預留的空間),
請將 decoration 設為 null。
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
若要在值變更時取得其值,請參考 處理文字欄位變更 教學。
TextFormField
#
TextFormField
包裝了一個 TextField,並將其與外層的 Form
整合。
這樣可以提供額外的功能,例如驗證,以及與其他
FormField
元件 (Widgets) 的整合。
TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
),
互動範例
#import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Form Styling Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(title: const Text(appTitle)),
body: const MyCustomForm(),
),
);
}
}
class MyCustomForm extends StatelessWidget {
const MyCustomForm({super.key});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Padding(
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term',
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
),
),
],
);
}
}
如需有關輸入驗證(input validation)的更多資訊,請參閱 建立具有驗證功能的表單 教學範例。
Unless stated otherwise, the documentation on this site reflects Flutter 3.44.0. Page last updated on 2026-06-14. View source or report an issue.