How to get App last Update time in flutter? - flutter

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

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

How to initialize SharedPreferences 2.0.15 in flutter? (Dart - Flutter)

I am using shared_preferences: ^2.0.15 and saving my values locally.
When I change my screen and get my values, I get an error.
How can I initialize SharedPreferences correctly?
Video
late SharedPreferences _preferences;
#override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
}
I've checked the video you shared.
You're just missing to call the getLocalData method inside the LoginViewModel.
I'd suggest adding a line inside your loginRequest method to call getLocalData method. Well, don't forget to await.
await getLocalData();
That's it :)
actually you are not fetching data from your shared preference
you have to get the data that u saved
first set data that you want to save
addStringToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', "email#email.com");
}
then in your second screen you can get your data
late SharedPreferences _preferences;
late String email;
#override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
// for exemple you saved a string value with key ='email'
email= _preferences.getString('email');
}
check this : https://medium.flutterdevs.com/using-sharedpreferences-in-flutter-251755f07127

How to store data after 24 hours in flutter? / How to update UI after some time when app is closed/killed in flutter?

I am making an app with flutter. I want to store data after 24 hours and update UI in app.
I try with Timer.periodic() but it does not count the time when app is close. It only works when the application is open.
Is it possible to execute a function after a specific time even if the app is closed?
Here is my current code:
void callbackDispatcher() async{
Workmanager().executeTask((task, inputData) {
switch(sdDaily){
case 'StoreDataDaily':
storeData.storeDailyData();
break;
default:
}
return Future.value(true);
});
}
void main() async{
WidgetsFlutterBinding.ensureInitialized();
Directory directory = await path_provider.getApplicationDocumentsDirectory();
print(directory.path);
Hive.init(directory.path);
await Hive.initFlutter(directory.path);
Hive.registerAdapter(UserAdapter());
Hive.registerAdapter(WaterAdapter());
Hive.registerAdapter(WeekAdapter());
Get.put(UserController());
Get.put(WaterController());
await Hive.openBox<User>('data');
await Hive.openBox<Water>('water_data');
await Hive.openBox<Week>('week_data');
await notificationPlugin.showNotification();
await Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
var uniqueId = DateTime.now().second.toString();
var userBox = Hive.box<User>('data');
if(userBox.get(0)?.status == 1){
await Workmanager().registerOneOffTask(uniqueId, sdDaily,);
}
runApp(const MyApp());
}
You can use : flutter_background_service. to execute background services and it'll also help you sending a custom notification when you are actually going to store that data later.
You can use firebase cloud funcitons to do schedule tasks or whatever you want to do even if app is closed or killed.

Flutter - Firebase Dynamic Link not Working while app is in kill mode

I have integrated Firebase Dynamic link in my Flutter application to open and navigate application users to specific screen in app.
For that first of all I have added below plugin in pubspec.yaml file:
firebase_dynamic_links: ^5.0.5
Then, I have created a separate class to handle related stuffs as below:
class DynamicLinkService {
late BuildContext context;
FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;
Future<void> initDynamicLinks(BuildContext context) async {
this.context = context;
dynamicLinks.onLink.listen((dynamicLinkData) {
var dynamicLink=dynamicLinkData.link.toString();
if (dynamicLink.isNotEmpty &&
dynamicLink.startsWith(ApiConstants.baseUrl) &&
dynamicLink.contains("?")) {
//Getting data here and navigating...
...
...
...
}
}).onError((error) {
print("This is error >>> "+error.message);
});
}
}
Now, I am initialising Deep-link as below in my home_screen:
final DynamicLinkService _dynamicLinkService = DynamicLinkService();
and then calling below method in initState()
#override
void initState() {
SchedulerBinding.instance.addPostFrameCallback((_) async {
await _dynamicLinkService.initDynamicLinks(context);
});
}
This is working like a charm! when my application is in recent mode or in background mode.
But the issue is when the application is closed/Killed, clicking on dynamic link just open the app but could not navigate.
What might be the issue? Thanks in advance.
Let me answer my own question, It might be useful for someone!
So, In above code I forgot to add code to handle dynamic link while the app is in closed/kill mode.
We need to add this code separately:
//this is when the app is in closed/kill mode
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
handleDynamicLink(initialLink);
}
So, final code looks like as below:
//this is when the app is in closed/kill mode
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
handleDynamicLink(initialLink);
}
//this is when the app is in recent/background mode
dynamicLinks.onLink.listen((dynamicLinkData) {
handleDynamicLink(dynamicLinkData);
}).onError((error) {
print("This is error >>> "+error.message);
});
Its working like a charm now! That's All.

how to retrieve a value from shared preferences instantly? - FLUTTER

I'm trying to show a page as an initial login, this is only displayed when my switch value is set to true.
The switch value is stored with shared preferences but when I open the application it is not recovered, only after an application update is it actually recovered. how can i get it to be recovered instantly when i open my application?
below the code:
Future<bool> saveSwitchState(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("switched", value);
print('Switch Value saved $value');
return prefs.setBool("switched", value);
}
Future<bool> getSwitchState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
SettingsPage.switched = prefs.getBool("switched")!;
print(SettingsPage.switched);
return SettingsPage.switched;
}
on another page then the value that is actually recovered:
if(AuthPage.authenticated == false && SettingsPage.switched == true ) {
yield ProfileNoAuth();
return; }
you can use dependency injection follow these steps :
get it package
create a Separate dart containing the following code file like this:
GetIt locator = GetIt.instance;
Future<void> setupLocator() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
locator.registerLazySingleton<SharedPreferences>(() => sharedPreferences);
}
call the setupLocator() method and wait for it in your main function
void main() async {
await setupLocator();
runApp(App());
}
access SharedPreferences Instance from anywhere like this:
locator();
now the SharedPreferences Instance if available anywhere in your project
please note that you dont have to wait for getting the Instance anymore, because you have only one Instance sharable across the application
bool getSwitchState() {
final prefs = locator<SharedPreferences>();
SettingsPage.switched = prefs.getBool("switched")!;
print(SettingsPage.switched);
return SettingsPage.switched;
}

Set state function on a key/value (shared_preferences) doesn't work for displaying the new value

I'm building a little pomodoro app with Flutter. I'm using the package shared_preferences to store a String and a Int.
Everything is working fine (loading and saving), but I'm trying to automatically change the displaying of the Int value with SetState, which doesn't work. The displaying value only change when I reload the app.
My saving method is :
_savePomo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setInt('pomodoro', pomodoro);
});
}
The method is called everytime the podomoro finish a cycle. Before calling the method I increment the pomodoro variable =+1.
I'm showing the value like this :
Text("It's your " + _pomodoro.toString() +"th pomodoro !");
Everything is happening in a stateful widget.
You can try below code:-
int pomodoro = 0;
_savePomo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('pomodoro', pomodoro);
pomodoro = await prefs.getInt('pomodoro');
}
You can use pomodoro variable in Text widget like below:-
Text("It's your " + pomodoro.toString() +"th pomodoro !");
Where you do this:
_pomodoro += 1;
Convert it into this:
setState(() {
_pomodoro += 1;
});
You also do not need to place the prefs.setInt in setState.