import 'package:calorimeter/perdate/perdate_widget.dart'; import 'package:flutter/material.dart'; class PerDatePageview extends StatefulWidget { // this is the date for which the PerDate widget will be shown on screen // left of it will be yesterday's PerDate widget // right of it will be tomorrow's PerDate widget final DateTime initalDate; const PerDatePageview({required this.initalDate, super.key}); @override State createState() => _PerDatePageviewState(); } class _PerDatePageviewState extends State { late PageController pageController; late DateTime displayedDate; late List visitedIndexes = []; final int initialOffset = 36500000; //TODO: that is just ugly bool backButtonWasPressed = false; @override void initState() { super.initState(); pageController = PageController(initialPage: initialOffset); displayedDate = widget.initalDate; visitedIndexes.add(initialOffset); } @override Widget build(BuildContext context) { return BackButtonListener( onBackButtonPressed: () async { if (visitedIndexes.length == 1) { return false; } visitedIndexes.removeLast(); backButtonWasPressed = true; pageController.jumpToPage(visitedIndexes.last); return true; }, child: PageView.builder( reverse: true, controller: pageController, onPageChanged: (value) { if (backButtonWasPressed) { backButtonWasPressed = false; return; } visitedIndexes.add(value); }, itemBuilder: (context, index) { var dateToBuildWidgetFor = displayedDate.subtract(Duration(days: index - initialOffset)); return PerDateWidget( key: ValueKey(dateToBuildWidgetFor.toString()), date: dateToBuildWidgetFor.copyWith(isUtc: true), onDateSelected: (dateSelected) { if (dateSelected == null) return; var diff = dateSelected.difference(dateToBuildWidgetFor); var newIndex = index - diff.inDays; pageController.jumpToPage(newIndex); }); }), ); } }