I'm new to Flutter and building a Flutter app thats really dependent on the date. Basically, I want the content loaded to remain the same for the day and then update when the user opens the app up the next day even if they closed out of the app 5 minutes to midnight.
I've noticed that initState only gets called once. If a user opens a flutter app and then closes out of it, the app opened again shows the same content. I would like to make sure the state updates if the user opens the app and it happens to be a future date but if it is still the current date, remain the same.
Right now, I'm using Shared Preferences to save the date and check it again but Im not sure how to make sure its checked every time the app is run.
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
class HomePage extends StatefulWidget {
@override
_HomePage createState() => _HomePage();
}
class _HomePage extends State<HomePage> {
String _todaysDate;
String _yesterdayDate;
final now = DateTime.now();
@override
void initState(){
super.initState();
_setupDateDisplay().then((_todaysDate){
_checkDate(_todaysDate);
});
}
Future<String> _setupDateDisplay() async {
_todaysDate = DateFormat.yMMMMd("en_US").format(now);
return _todaysDate;
}
_checkDate(String _todaysDate) async{
sharedPreferences = await SharedPreferences.getInstance();
String _yesterdayDate = sharedPreferences.getString('lastDate') ?? '';
if (_todaysDate != _yesterdayDate){
//SHOW NEW CONTENT
sharedPreferences.setString('lastDate', _todaysDate);
}else{
//SHOW SAME CONTENT
}
}
}