Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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';
    }
  }
like image 531
Benkot Avatar asked Jul 19 '19 21:07

Benkot


2 Answers

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';
}
like image 90
Richard Heap Avatar answered Oct 10 '22 22:10

Richard Heap


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

like image 26
Paresh Mangukiya Avatar answered Oct 10 '22 21:10

Paresh Mangukiya