2

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
         }

     }


  }
kelsheikh
  • 1,278
  • 3
  • 17
  • 37

1 Answers1

6

Welcome to Flutter :D

Here's my demo app for you, it should work as you want. It uses LifecycleEventHandler extends from WidgetsBindingObserver class, which can observe the state of application and widget.

NP: I think you don't need to use shared_preferences package.

Here's the code of one dart page app. You just need to copy it to new Flutter project and see app yourself. Hope to be helpful.

Explain code, it's very simple, each time the app resumed, it check the date of NOW, and choose the appropriate content for the date.

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class LifecycleEventHandler extends WidgetsBindingObserver {
  final AsyncCallback resumeCallBack;

  LifecycleEventHandler({this.resumeCallBack});

  @override
  Future<Null> didChangeAppLifecycleState(AppLifecycleState state) async {
    switch (state) {
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
      case AppLifecycleState.suspending:
      case AppLifecycleState.resumed:
        await resumeCallBack();
        break;
    }
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Checking Date App Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Checking Date App'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  String _content = "";

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(
        new LifecycleEventHandler(resumeCallBack: () async => _refreshContent()));
  }

  void _refreshContent() {
    setState(() {
      // Here you can change your widget
      // each time the app resumed.
      var now = DateTime.now();

      // Today
      if (new DateTime(now.year, now.month, now.day) == new DateTime(2019, 8, 4)) {
        _content = "Happy Birthday :D";
      } 
      // Tomorrow
      else if (new DateTime(now.year, now.month, now.day) == new DateTime(2019, 8, 5)) {
        _content = "It passed ONE day for your birthday ;)";
      } 
      // After Tomorrow
      else if (new DateTime(now.year, now.month, now.day) == new DateTime(2019, 8, 6)) {
        _content = "Did your dreams come true ??";
      } 
      // Unknown date
      else {
        _content = "Sorry, this day is not allowed. :(";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _content,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _refreshContent,
        tooltip: 'Refresh',
        child: Icon(Icons.refresh),
      ),
    );
  }
}
Shady Boshra
  • 2,521
  • 3
  • 23
  • 35