How can I show greetings like Good Moring, afternoon or evening base on users time in flutter

5,547

Solution 1

Try using DateTime.now(), for example:

String greeting() {
  var hour = DateTime.now().hour;
  if (hour < 12) {
    return 'Morning';
  }
  if (hour < 17) {
    return 'Afternoon';
  }
  return 'Evening';
}

Solution 2

Fetch the current time and Parse it and fetch only hours.

var timeNow = DateTime.now().hour;

Now, our timeNow a variable has the hour value in integer format we only need to check the condition and Change messages according to time like this

String greetingMessage(){

  var timeNow = DateTime.now().hour;
  
  if (timeNow <= 12) {
    return 'Good Morning';
  } else if ((timeNow > 12) && (timeNow <= 16)) {
  return 'Good Afternoon';
  } else if ((timeNow > 16) && (timeNow < 20)) {
  return 'Good Evening';
  } else {
  return 'Good Night';
  }
}

And use as

String greetingMes = greetingMessage();

enter image description here

Solution 3

TimeOfDay.now().period; 
// This will return DayPeriod.am or DayPeriod.pm, you can show the greeting message accordingly

Link: https://api.flutter.dev/flutter/material/TimeOfDay/period.html

import 'package:flutter/material.dart';

void main(){
  TimeOfDay day = TimeOfDay.now();
  switch(day.period){
    case DayPeriod.am: print('its morning');
      break;
    case DayPeriod.pm: print('its evening/night');
  }
}
Share:
5,547
Benkot
Author by

Benkot

Updated on December 12, 2022

Comments

  • Benkot
    Benkot over 1 year

    I want to greet user when they visit my app

    I have tried using TimeOfDay but it isn't working.

    TimeOfDay now = TimeOfDay.now();
    
      greetings(String greeting){
        var greeting = now;
        if(greeting <= '11: 59'){
          return 'Morning';
        } else if (greeting > '11:59' && <= '16:59'){
          return 'Afternoon';
        } else if (greeting > '16:59' && <= '23:59'){
          return 'Afternoon';
        } else {
          return 'Morning';
        }
      }
    
  • Benkot
    Benkot almost 5 years
    Excellent response. Thanks very much.
  • Abiud Orina
    Abiud Orina over 3 years
    The best and simplest answer out there. Thank you
  • MJ12358
    MJ12358 almost 3 years
    This is great but I would use a switch on the enum itself, day.period, instead of a string.
  • ritz
    ritz over 2 years
    @MJ12358 Yeah you are right! "toString()" is unnecessary here. I changed it!