The open source library dart_suncalc calculates the sun position and can offer sun set and sun rise times for different locations and dates. It is a port of the JavaScript library suncalc into Dart and comes with Dart’s sound null-safety. In addition to sun position it can calculate also the position of the moon.

The easiest way to install is to add the following to the “dependencies” section of pubspec.yaml file:

dependencies:
  dart_suncalc: ^0.2.1

and run flutter pub get or dart pub get.

To use the library you can import it with

import 'package:dart_suncalc/dart_suncalc.dart';

Than you calculate sun light times with the following:

1
2
3
4
// get today's sunlight times for London
final times = SunCalc.getTimes(date, lat: 51.5, lng: -0.1);

final sunrise = times.sunrise?.toLocal();

Beside the sunrise time, out of the box you will get the sunset, dawn, dusk, nautical dawn, nautical dusk, night, goldenHour, noon, and nadir times. For other times, there is an interface to add additional times:

1
2
3
4
5
6
// set time for sun angle 45 degree
SunCalc.addTime(45.0, '45-rise', '45-set'});
// get sunlight times for London
final times = SunCalc.getTimes(date, lat: 51.5, lng: -0.1);
// get 45.0 degree time in the first half of the day
final custom = times.custom['45-rise'];

The position of the sun can be calculated with:

1
2
3
4
5
// get position of the sun (azimuth and altitude) at today's sunrise
final sunrisePos = SunCalc.getPosition(times.sunrise, lat: 51.5, lng: -0.1);

// get sunrise azimuth in degrees
final sunriseAzimuth = sunrisePos.azimuth * 180 / PI;