i coded a section that shows the current date and time. the problem is whenever I load a page. the date and time first writes null for about a second before it shows the actual date and time. Please how can I write my code more efficiently so I dont have to see null anytime I load the page. I just want to see the actual date and time text as soon as possible. or is there anyway for me to write the date and time code more efficiently? This is my code.
class CurrentDate extends StatefulWidget {
@override
_CurrentDateState createState() => _CurrentDateState();
}
class _CurrentDateState extends State<CurrentDate> {
String _timeString;
@override
void initState() {
super.initState();
Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
}
void _getTime() {
final String formattedDateTime =
DateFormat('y MMMM EEEE d\n kk:mm:ss').format(DateTime.now().toUtc().add(Duration(hours: 3))).toString();
setState(() {
_timeString = formattedDateTime;
print(_timeString);
});
}
@override
Widget build(BuildContext context) {
return Text(
_timeString.toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Cairo',
color: Theme.of(context).iconTheme.color,
height: 1.2,
letterSpacing: -1,
fontSize: 23,
fontWeight: FontWeight.bold),
);
}
}
CodePudding user response:
you are getting null because its instantiated as a null. its waiting for a value. what you can do is show a CircularProgressIndicator()
widget or a loading widget of your choice until you get a value.
you can use a ternary operator like this:
// on the build method that you have posted you can write this.
@override
Widget build(BuildContext context) {
//if _timeString is null show CircularProgressIndicator() else show the text
return _timeString == null ? CircularProgressIndicator() : Text(
_timeString.toString(),
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Cairo',
color: Theme.of(context).iconTheme.color,
height: 1.2,
letterSpacing: -1,
fontSize: 23,
fontWeight: FontWeight.bold),
);
}
CodePudding user response:
First of all, I'd really recommend upgrading your flutter version, because this code doesn't even compile with null safety.
Instead of having an unnecessary null, you can just assign default value to the _timeString variable.
String _timeString = '';
Time.periodic()
execute the code every second, but nothing stops you from invoking the function by hand immediately for the first time.
@override
void initState() {
super.initState();
_getTime();
Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime());
}
Also .toString()
method has totally no sense here since you clearly specified type of _timeString
as String.