📅  最后修改于: 2023-12-03 15:42:29.743000             🧑  作者: Mango
当我们使用 Flutter 中的 TextField 组件时,有时候需要在用户输入文本后清空其值。为了实现这一目标,我们可以使用颤振 (Shake) 动画来清除 TextField 的值。
我们可以使用 Flutter 的动画库 (Animations) 来实现颤振动画。具体步骤如下:
final TextEditingController _controller = TextEditingController();
void clear() {
setState(() {
_controller.clear();
});
// 定义一个颤振动画
_animationController = AnimationController(
duration: Duration(milliseconds: 200),
vsync: this,
);
_animationController.forward(from: 0.0);
}
@override
Widget build(BuildContext context) {
return TextFormField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Enter text to clear',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
// 添加动画到输入框
inputFormatters: [
ShakeFormatter(
animationController: _animationController,
valueChanged: () {
setState(() {}); // 触发重绘
},
),
],
);
}
class ShakeFormatter extends TextInputFormatter {
final AnimationController animationController;
final ValueChanged valueChanged;
ShakeFormatter({
this.animationController,
this.valueChanged,
});
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isEmpty) {
animationController.forward(from: 0.0);
valueChanged();
}
return newValue;
}
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ClearableTextField extends StatefulWidget {
const ClearableTextField({Key key}) : super(key: key);
@override
_ClearableTextFieldState createState() => _ClearableTextFieldState();
}
class _ClearableTextFieldState extends State<ClearableTextField>
with SingleTickerProviderStateMixin {
final TextEditingController _controller = TextEditingController();
AnimationController _animationController;
void clear() {
setState(() {
_controller.clear();
});
_animationController = AnimationController(
duration: Duration(milliseconds: 200),
vsync: this,
);
_animationController.forward(from: 0.0);
}
@override
Widget build(BuildContext context) {
return TextFormField(
controller: _controller,
decoration: InputDecoration(
labelText: 'Enter text to clear',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
inputFormatters: [
ShakeFormatter(
animationController: _animationController,
valueChanged: () {
setState(() {}); // 触发重绘
},
),
],
);
}
}
class ShakeFormatter extends TextInputFormatter {
final AnimationController animationController;
final ValueChanged valueChanged;
ShakeFormatter({
this.animationController,
this.valueChanged,
});
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isEmpty) {
animationController.forward(from: 0.0);
valueChanged();
}
return newValue;
}
}
以上是 Flutter 中实现颤振 TextField 清除值的方法。来试试看吧!