如何让 AnimatedContainer 在键盘关闭时恢复到之前的状态(1)?目前更改容器的位置是通过 onTap 进行的
Widget _formAuth(String labelForm, String labelButton, void func()) {
return AnimatedContainer(
duration: Duration(seconds: 1),
curve: Curves.ease,
margin: EdgeInsets.fromLTRB(13, _marginFormAuth, 13, 50),
Widget _inputLoginOrPassword(
Icon icon, String hint, TextEditingController controller, bool obscure) {
return Container(
margin: EdgeInsets.fromLTRB(10, 35, 10, 0),
child: TextField(
onTap: () {
setState(() {
_marginFormAuth = 20;
});
},
您可以在状态类中定义一个布尔变量,并在构建方法中分配其值,如下所示:
bool isKeyboardOpened;
build () {
isKeyboardOpened = MediaQuery.of(context).viewInsets.bottom > 0;
_marginFormAuth = isKeyboardOpened ? 20 : whateverYouHadBefore;
...
}
这种在打开键盘时移动容器的解决方案并不是最好的方法,但是,您应该修改代码背后的整个概念,并使用当您聚焦字段时自然滚动的可滚动对象:)
检测键盘状态使用:https://github.com/adee42/flutter_keyboard_visibility
import 'package:keyboard_visibility/keyboard_visibility.dart';
@protected
void initState() {
super.initState();
KeyboardVisibilityNotification().addNewListener(
onChange: (bool visible) {
print(visible);
},
);
}
要为容器设置动画,请使用 AnimationController 而不是 AnimatedContainer: https://flutter.dev/docs/development/ui/animations/tutorial
我发现有人通过将
duration
更改为零然后将设置更改为您喜欢的任何内容来解决它,然后重置持续时间。
AnimatedContainer(
duration: _duration,
width: _isAutoClicking ? _size!.width : 0,
height: 20,
onEnd: () async {
if (_isAutoClicking) {
_duration = Duration.zero;
setState(() {
_isAutoClicking = false;
});
await Future.delayed(const Duration(milliseconds: 1));
_duration = autoNextDuration;
}
},
alignment: Alignment.bottomLeft,
color: const Color.fromARGB(120, 120, 120, 120),
)