我想在Flutter中制作一个浮动的AppBar,使其覆盖在我的UI上,并在用户向上滚动时关闭。我尝试使用这种依赖性-https://pub.dev/packages/material_floating_search_bar,但这仅用于搜索某些内容。
更新: 这是我的代码-
DefaultTabController(
length: 2,
child: Scaffold(
body: Stack(
children: [
Positioned(
top: 15,
left: 15,
right: 15,
child: SafeArea(
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: AppBar(
title: Text('Hello', style: kTasksStyle),
centerTitle: true,
backgroundColor: kGreen,
),
),
),
),
],
)),
);
如何在TabBar
的底部参数中添加AppBar
?
答案 0 :(得分:2)
您可以使用Stack
,将内容和应用栏作为子菜单。
要在滚动时关闭,可以根据ScrollController的偏移量隐藏应用栏或使用“动画”。
答案 1 :(得分:1)
截屏:
为简单起见,我使用了ListView
。
代码:
class _MainPageState extends State<HomePage> {
final double _appBarHeight = 56;
final double _topPadding = 20;
ScrollController _controller;
double _opacity = 1;
@override
void initState() {
super.initState();
_controller = ScrollController();
_controller.addListener(_listener);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _listener() {
final offset = _controller.offset;
if (offset > _appBarHeight) {
if (_opacity != 0) {
setState(() {
_opacity = 0;
if (_opacity < 0) _opacity = 0;
});
}
} else {
setState(() {
_opacity = 1 - (offset / _appBarHeight);
if (_opacity > 1) _opacity = 1;
});
}
}
Widget get _mainContent {
return ListView.builder(
controller: _controller,
padding: EdgeInsets.only(top: _topPadding + _appBarHeight),
itemCount: 20,
itemBuilder: (_, i) => ListTile(title: Text('Item $i')),
);
}
Widget get _appBar {
return Opacity(
opacity: _opacity,
child: SizedBox.fromSize(
size: Size.fromHeight(_appBarHeight),
child: AppBar(
title: Text('AppBar'),
centerTitle: false,
backgroundColor: Colors.grey,
leading: Icon(Icons.menu),
actions: [
IconButton(
icon: Icon(Icons.place),
onPressed: () {},
)
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
_mainContent,
Positioned(
top: _topPadding,
left: 0,
right: 0,
child: _appBar,
),
],
),
);
}
}