Home > Net >  How to get App last Update time in flutter?
How to get App last Update time in flutter?

Time:05-28

I want to get last app updates time in flutter, I tried but I can't get that time.

CodePudding user response:

Hei, I don't know if there is a package which manages this but I think you can manage it with some combinations. Add shared_preferences and package_info_plus as dependencies into your pubspec.yaml file as usual. Then in a uppest stateful widget in your widget tree, define a function as below (runApp -> MyApp -> HomePage(stateful) on Homepage for example):

    //import on top
    import 'package:shared_preferences/shared_preferences.dart';
    import 'package:package_info_plus/package_info_plus.dart';
    // .........
    void checkUpdateTime() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var previousVersion = prefs.getString("version");
    var previousTime = prefs.getString("latestTimeUpdated");
    String currentVersion = packageInfo.version   " "   packageInfo.buildNumber;
    String now = DateTime.now().toUtc().toString();

    // First launch after app downloaded
    if(previousVersion == null && previousTime == null){
        await prefs.setString("latestTimeUpdated", now);
        await prefs.setString("version", currentVersion);
    }
    
    // There is previous version instance saved before so check if its the same with the current version
    if (previousVersion != null) {
      // check saved version and current version is different
      if (previousVersion != currentVersion) {
        // Update time
        await prefs.setString("latestTimeUpdated", now);
        await prefs.setString("version", currentVersion);
      }
      // Do nothing if saved version and current version is the same
    }
  }

Do not forget to call the function on initState:

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

Basically; This will cross-check your app's current version and last saved version. If these are not same, it will update the latestTimeUpdated. Then in your app anywhere you want:

SharedPreferences prefs = await SharedPreferences.getInstance();
String updateTimeUTCString = prefs.getString("latestTimeUpdated");

Format this updateTimeUTCString as you wish and use it. I hope this becomes useful for you.

  • Related