Home > Back-end >  Initial date range not set on DateRangePicker
Initial date range not set on DateRangePicker

Time:11-05

I'm working on application where I need to persist the selected date range with shared preferences. For date picker I'm using an external package, for state handling I work with provider.

At the beginning in provider model I'm reading the value from shared preferences :

class DateRangeFilterModel extends ChangeNotifier {
  PickerDateRange? _dateRange;

  DateRangeFilterModel() {
    loadDateRange();
  }

  PickerDateRange? get dateRange => _dateRange;

  Future<void> loadDateRange() async {
    _dateRange = await SharedPreferencesManager.getFilterDateRange();
    notifyListeners();
  }

  Future<PickerDateRange?> getDateRange() async {
    return await SharedPreferencesManager.getFilterDateRange();
  }

  Future<void> setDateRange(PickerDateRange? dateRange) async {
    _dateRange = dateRange;

    await SharedPreferencesManager.saveFilterDateRange(
        dateRange?.startDate, dateRange?.endDate);

    notifyListeners();
  }
}

With Consumer widget I try to set up the initial value, for an example I also show the result on Text widget. On Text widget saved date range appears but on SfDateRangePicker not.

Consumer<DateRangeFilterModel>(
    builder: (context, model, child) => Column(
      children: [
        Text(model.dateRange.toString()),
        SfDateRangePicker(
          initialSelectedRange: model.dateRange,
          showTodayButton: false,
          enablePastDates: false,
          selectionMode: DateRangePickerSelectionMode.range,
          minDate: DateTime.now(),
          onSelectionChanged: (DateRangePickerSelectionChangedArgs args) {
            if (args.value is PickerDateRange) {
              final DateTime? startDate = args.value.startDate;
              final DateTime? endDate = args.value.endDate;

              if (startDate != null && endDate != null) {
                context
                    .read<DateRangeFilterModel>()
                    .setDateRange(PickerDateRange(startDate, endDate));
              }
            }
          },
        ),
      ],
    ),
  ),

My ChangeNotifierProvider

ChangeNotifierProvider(
      create: (context) => DateRangeFilterModel(),
      child: const DateRangePicker()
),

I think there is some concurrency problems. Where I made mistake? Thanks for any advice.

CodePudding user response:

My solution is was to set initial range through controller.

final DateRangePickerController _controller = DateRangePickerController();
.....
SfDateRangePicker(
          initialSelectedRange: _controller.selectedRange = model.dateRange,
          controller: _controller,
         ...
)
  • Related