上一节我们的不透明度是直接从 跳转0到1。它看起来并不顺畅,我们可以使用SliverAnimatedOpacity
来过渡。
SliverAnimatedOpacity
是一个动画版本,只要给定的不透明度发生变化,SliverOpacity
就会自动将 sliver
子项的不透明度转换为给duration
定的不透明度。构造函数:
const SliverAnimatedOpacity({
super.key,
this.sliver,
required this.opacity,//透明度 ,从 0.0 ~ 1.0
super.curve,//动画曲线
required super.duration,//动画的时间
super.onEnd,//动画执行完成回调的方法
this.alwaysIncludeSemantics = false,
})
例子:
import 'package:flutter/material.dart';
class SliverAnimatedOpacityPage extends StatefulWidget {
const SliverAnimatedOpacityPage({Key? key}) : super(key: key);
@override
State<SliverAnimatedOpacityPage> createState() => _SliverAnimatedOpacityPageState();
}
class _SliverAnimatedOpacityPageState extends State<SliverAnimatedOpacityPage> {
bool _isVisible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('SliverAnimatedOpacity'),),
body: CustomScrollView(
slivers: [
SliverAnimatedOpacity(
opacity: _isVisible ? 1.0: 0.0,
duration: const Duration(milliseconds: 1000),
sliver: SliverToBoxAdapter(
child:Container(
width: double.infinity,
height: 300,
alignment: Alignment.center,
decoration: const BoxDecoration(
image:DecorationImage(
image:AssetImage('images/liu.webp'),
alignment: Alignment.center,
fit: BoxFit.cover,
)
),
child: IconButton(
iconSize: 40,
icon: const Icon(Icons.ads_click),
onPressed: (){
setState(() {
_isVisible = !_isVisible;
});
},
),
)
),
),
],
),
);
}
}