Skip to content

Instantly share code, notes, and snippets.

@slightfoot
Last active August 12, 2023 18:45
Show Gist options
  • Save slightfoot/1e648a09560e6406be7330cc33340fec to your computer and use it in GitHub Desktop.
Save slightfoot/1e648a09560e6406be7330cc33340fec to your computer and use it in GitHub Desktop.
Segment Selector - by Simon Lightfoot - 9th August 2023 - Humpday Q&A - https://twitter.com/BrandoTrautmann/status/1688517737591545857
// MIT License
//
// Copyright (c) 2023 Simon Lightfoot
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
runApp(const MaterialApp(
debugShowCheckedModeBanner: false,
home: Home(),
));
}
@immutable
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: DefaultTextStyle(
style: const TextStyle(
color: Colors.black,
fontSize: 32.0,
),
child: SegmentSelector(
selectionDecoration: ShapeDecoration(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.lime.shade900,
width: 3.0,
),
borderRadius: const BorderRadius.all(
Radius.circular(12.0),
),
),
),
onChanged: (int value) {
print(value);
},
children: const [
_SelectionItem(label: '3d'),
_SelectionItem(label: '180d'),
_SelectionItem(label: '35d'),
],
),
),
),
);
}
}
@immutable
class _SelectionItem extends StatelessWidget {
const _SelectionItem({
required this.label,
});
final String label;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: Text(label),
);
}
}
@immutable
class SegmentSelector extends StatefulWidget {
const SegmentSelector({
super.key,
this.mainAxisAlignment = MainAxisAlignment.center,
this.mainAxisSize = MainAxisSize.min,
this.crossAxisAlignment = CrossAxisAlignment.center,
this.initialSelection = 0,
required this.selectionDecoration,
required this.onChanged,
required this.children,
});
final MainAxisAlignment mainAxisAlignment;
final MainAxisSize mainAxisSize;
final CrossAxisAlignment crossAxisAlignment;
final int initialSelection;
final Decoration selectionDecoration;
final ValueChanged<int>? onChanged;
final List<Widget> children;
@override
State<SegmentSelector> createState() => _SegmentSelectorState();
}
class _SegmentSelectorState extends State<SegmentSelector> {
late List<GlobalKey> keys;
late int _selectedIndex;
Rect? rect;
@override
void initState() {
super.initState();
_selectedIndex = widget.initialSelection;
keys = List.generate(widget.children.length, (_) => GlobalKey());
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateRectForSelection();
});
}
void _updateRectForSelection() {
final renderBox =
keys[_selectedIndex].currentContext!.findRenderObject() as RenderBox;
final parentData = renderBox.parentData as BoxParentData;
setState(() {
rect = parentData.offset & renderBox.size;
});
}
@override
void didUpdateWidget(covariant SegmentSelector oldWidget) {
super.didUpdateWidget(oldWidget);
final newLength = widget.children.length;
final oldLength = oldWidget.children.length;
if (newLength != oldLength) {
if (newLength < oldLength) {
keys = keys.sublist(0, newLength);
} else {
keys = [
...keys,
...List.generate((newLength - oldLength), (_) => GlobalKey()),
];
}
}
}
@override
void reassemble() {
super.reassemble();
WidgetsBinding.instance.addPostFrameCallback((_) {
_updateRectForSelection();
});
}
void _setSelectedIndex(int index) {
setState(() {
_selectedIndex = index;
_updateRectForSelection();
});
widget.onChanged?.call(index);
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
if (rect != null) //
AnimatedPositioned.fromRect(
duration: const Duration(milliseconds: 300),
curve: Curves.fastOutSlowIn,
rect: rect!,
child: DecoratedBox(
decoration: widget.selectionDecoration,
),
),
Row(
mainAxisSize: widget.mainAxisSize,
mainAxisAlignment: widget.mainAxisAlignment,
crossAxisAlignment: widget.crossAxisAlignment,
children: [
for (final (index, child) in widget.children.indexed) //
KeyedSubtree(
key: keys[index],
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: widget.onChanged != null //
? () => _setSelectedIndex(index)
: null,
child: child,
),
),
],
),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment