Skip to content

Instantly share code, notes, and snippets.

@RyouMon
Last active December 23, 2022 14:26
Show Gist options
  • Save RyouMon/7d31f982059c751e30fc4005de4fd7d4 to your computer and use it in GitHub Desktop.
Save RyouMon/7d31f982059c751e30fc4005de4fd7d4 to your computer and use it in GitHub Desktop.
Flutter Demo, ScrollController Example: addListener and animateTo
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class ScrollControllerTest extends StatefulWidget {
final String title;
const ScrollControllerTest({super.key, required this.title});
@override
State<ScrollControllerTest> createState() => _ScrollControllerTestState();
}
class _ScrollControllerTestState extends State<ScrollControllerTest> {
ScrollController controller = ScrollController();
bool showtoTopBtn = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Scrollbar(
controller: controller,
child: ListView.builder(
itemCount: 100,
itemExtent: 50.0,
controller: controller,
itemBuilder: ((context, index) => ListTile(
title: Text("$index"),
)))),
floatingActionButton: !showtoTopBtn
? null
: FloatingActionButton(
onPressed: (() {
controller.animateTo(.0,
duration: const Duration(seconds: 2), curve: Curves.ease);
}),
child: const Icon(Icons.arrow_upward),
),
);
}
@override
void initState() {
super.initState();
controller.addListener(() {
print(controller.offset);
if (controller.offset < 1000 && showtoTopBtn) {
setState(() {
showtoTopBtn = false;
});
} else if (controller.offset >= 1000 && !showtoTopBtn) {
setState(() {
showtoTopBtn = true;
});
}
});
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const ScrollControllerTest(
title: 'ScrollController Example: addListener and animateTo'),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment