Skip to content

Instantly share code, notes, and snippets.

@bizz84
Created January 14, 2024 10:22
Show Gist options
  • Save bizz84/6fffeac60756ceefdfb0dce7f64ccba4 to your computer and use it in GitHub Desktop.
Save bizz84/6fffeac60756ceefdfb0dce7f64ccba4 to your computer and use it in GitHub Desktop.
Example showing how to scroll to a list item by index when all items can have different heights
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:scroll_to_index/scroll_to_index.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyWidget(),
);
}
}
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late AutoScrollController controller;
final random = Random();
static const scrollDirection = Axis.vertical;
@override
void initState() {
super.initState();
controller = AutoScrollController(
viewportBoundaryGetter: () =>
Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
axis: scrollDirection);
}
@override
Widget build(BuildContext context) {
return NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
expandedHeight: 200.0,
floating: false,
pinned: true,
flexibleSpace: const FlexibleSpaceBar(
centerTitle: true,
title: Text("My AppBar"),
),
actions: [
TextButton(
onPressed: () => scrollToIndex(10), child: const Text('10')),
TextButton(
onPressed: () => scrollToIndex(20), child: const Text('20')),
TextButton(
onPressed: () => scrollToIndex(30), child: const Text('30')),
],
),
];
},
body: ListView.builder(
itemCount: 100,
scrollDirection: scrollDirection,
controller: controller,
itemBuilder: (context, index) {
return AutoScrollTag(
key: ValueKey(index),
controller: controller,
index: index,
child: Material(
child: Container(
height: (50 + random.nextInt(150)).toDouble(), // random heights
color:
index % 2 == 0 ? Colors.lightGreenAccent : Colors.redAccent,
child: Text('Item $index'),
),
),
);
},
),
);
}
Future scrollToIndex(int index) async {
await controller.scrollToIndex(index,
preferPosition: AutoScrollPosition.begin);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment