[英]CustomScrollView Custom Scrolling Flutter
I have been studing and trying to do some projects and stack in this.我一直在研究并尝试做一些项目并在其中进行堆叠。 So, I created CustomScrollView and the SliverAppBar has to be either fully opened or fully closed.因此,我创建了 CustomScrollView 并且 SliverAppBar 必须完全打开或完全关闭。 I tried to do but have problems with animation scrolling.我尝试这样做,但在 animation 滚动时遇到问题。
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepPurple,
),
body: const MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _scrollController = ScrollController();
bool isClosed = false;
@override
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.offset >= 5 && _scrollController.offset <= 200) {
if (isClosed) {
_scrollController.jumpTo(0);
close();
} else {
_scrollController.jumpTo(202);
close();
}
}
});
}
close() {
setState(() {
isClosed = !isClosed;
});
}
@override
Widget build(BuildContext context) {
return CustomScrollView(
controller: _scrollController,
slivers: [
SliverAppBar(
expandedHeight: 200,
flexibleSpace: SizedBox(
child: Container(
height: 200,
decoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS5-OgasVpm-kc2HaOUloxKVlLzLuM6Q53mfA&usqp=CAU"),
fit: BoxFit.cover)),
),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
color: Color(index),
height: 100,
width: MediaQuery.of(context).size.width,
child: Text("$index"),
);
},
childCount: 10,
))
],
);
}
}
It works when jumpTo is used but has problems when animateTo is used.它在使用 jumpTo 时有效,但在使用 animateTo 时出现问题。 Thank You!谢谢你!
You need to wrap .animateTo()
inside a Future delay
.您需要将.animateTo()
包装在Future delay
中。 The below code worked for me下面的代码对我有用
Future.delayed(
Duration(milliseconds: 600),
() {
_scrollController.animateTo(
202,
duration: Duration(
milliseconds: 600),
curve: Curves.ease);
});
Or you can also wrap inside PostFrameCallback
或者你也可以包装在PostFrameCallback
里面
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollController.animateTo(
202,
duration: Duration(
milliseconds: 600),
curve: Curves.ease);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.