Skip to content

Instantly share code, notes, and snippets.

@yeasin50
Last active November 2, 2024 14:57
Show Gist options
  • Save yeasin50/46f502e70de001e159b6dcf2e7a0a39a to your computer and use it in GitHub Desktop.
Save yeasin50/46f502e70de001e159b6dcf2e7a0a39a to your computer and use it in GitHub Desktop.
Custom ScrollBar position in Flutter
import 'dart:ui';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: MyListView(),
),
),
);
}
class MyListView extends StatefulWidget {
const MyListView({super.key});
@override
State<MyListView> createState() => _MyListViewState();
}
class _MyListViewState extends State<MyListView> {
final ScrollController controller = ScrollController();
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: ScrollConfiguration(
behavior: ScrollBehavior().copyWith(scrollbars: false),
child: Column(
children: [
Container(
height: 200,
width: double.infinity,
color: Colors.cyan,
),
Expanded(
child: ListView.builder(
controller: controller,
itemCount: 23,
itemBuilder: (context, index) => ListTile(
tileColor: index.isEven ? Colors.red : Colors.white,
),
),
)
],
),
),
),
const SizedBox(width: 48),
SizedBox(
height: double.infinity,
width: 48,
child: NotificationListener<ScrollNotification>(
onNotification: (notification) {
return true;
},
child: CustomPaint(
painter: MyScrollBarPainter(controller),
)),
)
],
);
}
}
class MyScrollBarPainter extends CustomPainter {
const MyScrollBarPainter(this.controller) : super(repaint: controller);
final ScrollController controller;
@override
void paint(Canvas canvas, Size size) {
if (controller.hasClients == false) return;
///FIXME: currently I am falling to get the ratio of (viewPortHeight/MaxScrollExtent)
final barHeight = controller.position.maxScrollExtent / 10;
final t = controller.offset / controller.position.maxScrollExtent;
final double top = lerpDouble(0, size.height - barHeight, t) ?? 1;
debugPrint("t $t height $barHeight");
final rrect = RRect.fromRectAndRadius(
Rect.fromLTWH(0, top, 10, barHeight),
Radius.circular(12),
);
canvas.drawRRect(rrect, Paint()..color = Colors.green);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment