Network Time Protocol (NTP) & Dart/Flutter

Paulo Cesar
2 min readApr 7, 2022

--

Working with Dates isn’t always easy and simple. If you will implementing something like a time-based one-time password (TOTP) wich is a temporary passcode generated by an algorithm that uses the current time of day as one of its authentication factors, you can face problems like incorrect time and this occurs because the user changed the time of the device.

If you are reading this, probably you are facing a pretty annoying problem with the time of the device because the user changed that. But dont worry, its easy to solve.

In Dart, we can use a plugin called Network Time Protocol (NTP) to solve this problem, you can find it here: https://pub.dev/packages/ntp.

Basically, this plugin let us to check the time based in a server of the google by default. I will show to you how to use it.

In the image below, you can see in the line 33 that I have started an DateTime variable called deviceTime, this variable are receiving the current time of the device, and formating it in the line 34.

Here, i have a get method that is basically doing the same, but now i am getting the time from the cloud using the Network Time Protocol (NTP).

Now, look at this:

I changed the time of the device to 20:23, but the correct time is 23:23, so, this will solve your problem when handling with users that change the device time.

The NTP are pretty great and let us do some motifications as we want, you can see more about the plugin at https://pub.dev/packages/ntp

--

--