AnimatedContainer
在小部件内部使用怎么样Stack
?
像这样的东西...
import 'package:flutter/material.dart';
import 'package:vector_math/vector_math_64.dart' hide Colors;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ScrollController scrollController = ScrollController();
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.blue,
),
home: Scaffold(
body: Stack(
children: <Widget>[
SafeArea(
child: ListView(
controller: scrollController,
padding: const EdgeInsets.only(top: 100),
children: List.generate(
100,
(index) => ListTile(
title: Text('This is item #$index'),
),
),
),
),
AnimatedAppBar(
scrollController: scrollController,
child: PreferredSize(
preferredSize: Size.fromHeight(100),
child: const Center(child: Text('APP BAR')),
),
),
],
),
),
);
}
}
class AnimatedAppBar extends StatefulWidget {
AnimatedAppBar({
required this.scrollController,
this.child,
this.toolbarHeight,
});
final ScrollController scrollController;
final PreferredSize? child;
final double? toolbarHeight;
@override
_AnimatedAppBarState createState() => _AnimatedAppBarState();
}
class _AnimatedAppBarState extends State<AnimatedAppBar> {
late double _totalHeight;
late double _lastPosition;
late bool _isShown;
@override
void initState() {
super.initState();
_totalHeight = widget.toolbarHeight ??
kToolbarHeight + (widget.child?.preferredSize.height ?? 0.0);
_lastPosition = widget.scrollController.offset;
_isShown = true;
widget.scrollController.addListener(_scrollListener);
}
void _scrollListener() {
if (_isShown && _lastPosition < widget.scrollController.offset) {
setState(() => _isShown = false);
} else if (!_isShown && _lastPosition > widget.scrollController.offset) {
setState(() => _isShown = true);
}
_lastPosition = widget.scrollController.offset;
}
@override
Widget build(BuildContext context) {
return AnimatedContainer(
width: double.infinity,
height: _totalHeight,
padding: EdgeInsets.only(top: kToolbarHeight),
duration: const Duration(milliseconds: 250),
curve: Curves.easeIn,
transform: Matrix4.translation(
Vector3(0, _isShown ? 0 : -_totalHeight, 0),
),
color: Theme.of(context).primaryColor,
child: widget.child,
);
}
@override
void dispose() {
widget.scrollController.removeListener(_scrollListener);
super.dispose();
}
}