flutter_timetable/lib/src/timetable.dart

110 lines
3 KiB
Dart
Raw Normal View History

2022-08-24 09:39:36 +02:00
part of timetable;
class Timetable extends StatefulWidget {
2022-08-24 11:01:50 +02:00
const Timetable({
2022-08-24 12:03:32 +02:00
this.timeBlocks = const [],
2022-08-24 11:01:50 +02:00
this.scrollController,
this.startHour = 0,
this.endHour = 24,
2022-08-24 12:03:32 +02:00
this.blockWidth = 50,
2022-08-24 11:01:50 +02:00
Key? key,
}) : super(key: key);
/// Hour at which the timetable starts.
final int startHour;
/// Hour at which the timetable ends.
final int endHour;
2022-08-24 12:03:32 +02:00
/// The time blocks that will be displayed in the timetable.
final List<TimeBlock> timeBlocks;
/// The width of the block if there is no child
final double blockWidth;
2022-08-24 11:01:50 +02:00
/// The scroll controller to control the scrolling of the timetable.
final ScrollController? scrollController;
2022-08-24 09:39:36 +02:00
@override
State<Timetable> createState() => _TimetableState();
}
class _TimetableState extends State<Timetable> {
2022-08-24 11:01:50 +02:00
late ScrollController _scrollController;
@override
void initState() {
super.initState();
_scrollController = widget.scrollController ?? ScrollController();
2022-08-24 12:13:24 +02:00
_scrollToFirstBlock();
2022-08-24 11:01:50 +02:00
}
@override
void dispose() {
if (widget.scrollController == null) {
_scrollController.dispose();
}
super.dispose();
}
2022-08-24 09:39:36 +02:00
@override
Widget build(BuildContext context) {
2022-08-24 11:01:50 +02:00
return SingleChildScrollView(
physics: const BouncingScrollPhysics(),
controller: _scrollController,
child: Stack(
children: [
Table(
startHour: widget.startHour,
endHour: widget.endHour,
),
2022-08-24 12:03:32 +02:00
Container(
margin: const EdgeInsets.only(left: 45),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (var block in widget.timeBlocks) ...[
Block(
start: block.start,
end: block.end,
startHour: widget.startHour,
blockWidth: widget.blockWidth,
child: block.child,
)
],
2022-08-24 12:13:24 +02:00
// TODO(anyone): 80 needs to be a calculated value
2022-08-24 12:03:32 +02:00
SizedBox(
width: 15,
height: 80 * (widget.endHour - widget.startHour) + 40,
),
],
),
),
),
),
2022-08-24 11:01:50 +02:00
],
),
);
2022-08-24 09:39:36 +02:00
}
2022-08-24 12:13:24 +02:00
void _scrollToFirstBlock() {
SchedulerBinding.instance.addPostFrameCallback((_) {
var earliestStart = widget.timeBlocks.map((block) => block.start).reduce(
(a, b) =>
a.hour < b.hour || (a.hour == b.hour && a.minute < b.minute)
? a
: b,
);
var initialOffset = (80 * (widget.endHour - widget.startHour)) *
((earliestStart.hour - widget.startHour) /
(widget.endHour - widget.startHour));
_scrollController.jumpTo(
initialOffset,
);
});
}
2022-08-24 09:39:36 +02:00
}