flutter中appbar的backgroundColor实现滚动渐变完整代码
时间: 2024-09-07 10:02:00 浏览: 42
Flutter 自定义AppBar实现滚动渐变
在Flutter中,要实现AppBar背景颜色的滚动渐变效果,通常需要自定义` AppBar `并使用动画插件如` AnimatedContainer `或者直接操作` Paint `对象。这里是一个简单的示例,展示如何使用` AnimatedContainer `配合` Alignment `实现滚动渐变:
```dart
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
class GradientAppBar extends StatefulWidget {
final Color startColor;
final Color endColor;
GradientAppBar({required this.startColor, required this.endColor});
@override
_GradientAppBarState createState() => _GradientAppBarState();
}
class _GradientAppBarState extends State<GradientAppBar> with SingleTickerProviderStateMixin {
Animation<double> appBarAnimation = CurvedAnimation(parent: this);
AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500), // 设置动画持续时间
);
controller.forward(); // 开始动画
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AppBar(
elevation: 0.0, // 降低阴影以便于观察渐变
backgroundColor: Container(
height: 64,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [widget.startColor, widget.endColor],
stops: List.generate(2, (index) => index.toDouble()),
),
borderRadius: BorderRadius.circular(8),
),
child: AnimatedContainer(
duration: Duration(milliseconds: 500),
width: double.infinity,
alignment: Alignment.center,
margin: EdgeInsets.zero,
child: Text('标题', style: TextStyle(fontSize: 18)),
animation: AlignmentTween(begin: Alignment.topCenter, end: Alignment.bottomCenter).animate(appBarAnimation),
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.menu),
onPressed: () {},
)
],
);
}
}
// 如果需要用户选择颜色,可以添加一个颜色选择器
// 示例:
// ElevatedButton(
// onPressed: () async {
// var pickedColor = await showColorPicker(
// pickerBuilder: (context) => MaterialColorPicker(),
// );
// setState(() {
// if (pickedColor != null) {
// // 更新startColor和endColor
// widget.startColor = pickedColor ?? Colors.blue;
// widget.endColor = pickedColor ?? Colors.blueAccent;
// }
// });
// },
// child: Text('选择颜色'),
// ),
```
这个例子中,我们创建了一个名为`GradientAppBar`的自定义组件,它会根据滚动方向实时改变颜色渐变的位置。
阅读全文