Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter how to get all the days of the week as string in the users locale

Tags:

flutter

AS stated in the title: Is there an easy way to get all the days of the week as string(within a list ofcourse) in the users locale?

like image 672
Robin Dijkhof Avatar asked Jan 19 '19 18:01

Robin Dijkhof


Video Answer


1 Answers

My suggestion is:

static List<String> getDaysOfWeek([String locale]) {
  final now = DateTime.now();
  final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
  return List.generate(7, (index) => index)
      .map((value) => DateFormat(DateFormat.WEEKDAY, locale)
          .format(firstDayOfWeek.add(Duration(days: value))))
      .toList();
}

The idea is we define the date of the first day in the current week depending on current week day. Then just do loop 7 times starting from calculated date, add 1 day on each iteration and collect the result of DateFormat().format method with pattern DateFormat.WEEKDAY. To increase performance you can use lazy initialization. For example:

/// Returns a list of week days
static List<String> _daysOfWeek;
static List<String> get daysOfWeek {
  if (_daysOfWeek == null) {
    _daysOfWeek = getDaysOfWeek(); // Here you can specify your locale
  }
  return _daysOfWeek;
}
like image 69
BambinoUA Avatar answered Nov 15 '22 11:11

BambinoUA