📅  最后修改于: 2023-12-03 15:26:13.256000             🧑  作者: Mango
在Flutter中,TextField是常见的组件之一。而文本字段占位符的颜色通常与文字颜色相同,有时很难引起用户的注意。因此,在此提供一个文本字段占位符颜色颤动的主题,以增强用户体验。
我们可以通过使用TextField的decorator属性来自定义文本字段装饰器。在此示例中,我们将使用InputDecoration对象并通过更改占位符颜色来实现动画效果。以下是示例代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
inputDecorationTheme: InputDecorationTheme(
labelStyle:
TextStyle(color: Colors.blueGrey), // 文字颜色
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blueGrey)), // 下划线颜色
),
),
home: MyHomePage(title: 'Flutter Demo Home Page'));
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
String get _text => _controller.text;
bool get _isTextFieldFocused => _focusNode.hasFocus;
final FocusNode _focusNode = FocusNode();
@override
void initState() {
super.initState();
_focusNode.addListener(_onTextFieldFocusChange);
}
@override
void dispose() {
_focusNode.removeListener(_onTextFieldFocusChange);
_controller.dispose();
super.dispose();
}
void _onTextFieldFocusChange() {
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: TextField(
controller: _controller,
focusNode: _focusNode,
decoration: InputDecoration(
labelText: "Enter text",
labelStyle: TextStyle(
color: _isTextFieldFocused ? Colors.blue : Colors.grey), // 如果文字获得焦点则变色
),
),
),
);
}
}
以上就是如何通过更改TextField的decorator属性自定义文本字段样式。这可以提高用户体验,特别是在需要吸引用户注意的情况下。