Flutter自定义输入框同时出现多种字体颜色
在Flutter中,要创建一个支持多种字体颜色的自定义输入框,你可以使用TextField
控件并结合TextSpan
和TextPainter
来自定义绘制文本。以下是一个简单的示例,展示了如何实现这一功能:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MultiColorTextField extends StatefulWidget {
@override
_MultiColorTextFieldState createState() => _MultiColorTextFieldState();
}
class _MultiColorTextFieldState extends State<MultiColorTextField> {
final TextEditingController _controller = TextEditingController();
final FocusNode _focusNode = FocusNode();
@override
void dispose() {
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
focusNode: _focusNode,
style: TextStyle(color: Colors.black), // 默认字体颜色
decoration: InputDecoration(
hintText: '请输入文本',
hintStyle: TextStyle(color: Colors.grey), // 提示文字颜色
),
onTap: () {
_focusNode.requestFocus();
},
buildCounter: _buildCounter,
);
}
Widget _buildCounter(
BuildContext context,
{
required int currentLength,
required int maxLength,
required bool isFocused,
},
) {
final textSpan = TextSpan(
text: '${_controller.text}',
style: TextStyle(
color: Colors.red, // 这里可以根据需要设置不同的颜色
fontSize: 18,
),
children: <TextSpan>[
TextSpan(
text: '${_controller.text}',
style: TextStyle(
color: Colors.blue, // 另一种颜色
fontSize: 18,
),
),
],
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout(minWidth: 0, maxWidth: double.infinity);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 5.0),
child: CustomPaint(
size: Size(200, 1.0),
painter: TextPainterPainter(textPainter),
),
);
}
}
class TextPainterPainter extends CustomPainter {
TextPainterPainter(this.textPainter);
final TextPainter textPainter;
@override
void paint(Canvas canvas, Size size) {
textPainter.paint(canvas, Offset.zero);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
评论已关闭