面试题答案
一键面试1. 主要用到的Widget
InkWell
: 用于处理点击交互,它能提供水波纹效果,增加用户反馈。AnimatedContainer
: 用于实现动画效果,比如在按钮点击时改变按钮的大小、颜色等。
2. Dart代码结构示例
import 'package:flutter/material.dart';
class AnimatedButtonPage extends StatefulWidget {
@override
_AnimatedButtonPageState createState() => _AnimatedButtonPageState();
}
class _AnimatedButtonPageState extends State<AnimatedButtonPage> with SingleTickerProviderStateMixin {
bool _isButtonPressed = false;
late AnimationController _animationController;
late Animation<Color?> _colorTween;
late Animation<double> _sizeTween;
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
_colorTween = ColorTween(begin: Colors.blue, end: Colors.green).animate(_animationController);
_sizeTween = Tween<double>(begin: 100, end: 120).animate(_animationController);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _handleButtonPress() {
setState(() {
_isButtonPressed = !_isButtonPressed;
if (_isButtonPressed) {
_animationController.forward();
} else {
_animationController.reverse();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Animated Button'),
),
body: Center(
child: InkWell(
onTap: _handleButtonPress,
child: AnimatedBuilder(
animation: _animationController,
builder: (context, child) {
return Container(
width: _sizeTween.value,
height: _sizeTween.value,
decoration: BoxDecoration(
color: _colorTween.value,
borderRadius: BorderRadius.circular(50),
),
child: const Center(
child: Text(
'Click Me',
style: TextStyle(color: Colors.white),
),
),
);
},
),
),
),
);
}
}
在上述代码中:
AnimatedButtonPage
是一个状态ful widget,用于管理按钮的状态。_isButtonPressed
变量用于记录按钮是否被按下。AnimationController
控制动画的播放、停止等。ColorTween
和Tween<double>
分别定义了颜色和大小的动画变化。InkWell
的onTap
回调函数_handleButtonPress
用于处理按钮点击,在点击时更新按钮状态并控制动画播放。AnimatedBuilder
根据动画的状态更新Container
的属性,实现动画效果。