Created with <3 with dartpad.dev.
Created
January 3, 2023 12:26
-
-
Save osharaki/c3bacd8b1594d218f8c357a43da81b92 to your computer and use it in GitHub Desktop.
Page scrolling with Scrollable.ensureVisible()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
MyHomePage({super.key, required this.title}); | |
final String title; | |
static const listItemCount = 25; | |
final globalKeyFirst = GlobalKey(); | |
final globalKeyLast = GlobalKey(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: Center( | |
child: SingleChildScrollView( | |
child: Column( | |
children: [ | |
for (var index in List<int>.generate(listItemCount, (j) => j + 1)) | |
Center( | |
key: index == 1 ? globalKeyFirst : (index == listItemCount ? globalKeyLast : null), | |
child: Padding( | |
padding: const EdgeInsets.symmetric( | |
vertical: 10, | |
), | |
child: Card( | |
child: Text( | |
"This is item $index", | |
style: const TextStyle(fontSize: 28), | |
), | |
), | |
), | |
), | |
], | |
), | |
), | |
), | |
floatingActionButton: Column( | |
mainAxisSize: MainAxisSize.min, | |
children: [ | |
Padding( | |
padding: const EdgeInsets.symmetric(vertical: 20), | |
child: FloatingActionButton( | |
onPressed: () { | |
Scrollable.ensureVisible(globalKeyFirst.currentContext!); | |
}, | |
child: const Icon(Icons.arrow_upward), | |
), | |
), | |
Padding( | |
padding: const EdgeInsets.symmetric(vertical: 20), | |
child: FloatingActionButton( | |
onPressed: () { | |
Scrollable.ensureVisible(globalKeyLast.currentContext!); | |
}, | |
child: const Icon(Icons.arrow_downward), | |
), | |
), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment