how to do an action all the time, when opening the application, except the first opening - flutter

I search how to make an action for each call of the initstate of my statefull widget exept the first call.
Thank you

The best method would be to use the SharedPreferences plugin which saves values to local storage.
Add the dependency to your pubspec.yaml file
dependencies:
shared_preferences: ^0.5.6
Import the plugin
import 'package:shared_preferences/shared_preferences.dart';
Reference the SharedPreferences class
SharedPreferences prefs = await SharedPreferences.getInstance();
Lastly check if it is the first time or not
// If the preference firstTime does not exist it means it is the first time
bool firstTime = prefs.getBool('firstTime') ?? true;
if(firstTime){
// This is the first time the user is opening the app
// Set firstTime preference value to false
await prefs.setBool('firstTime', false);
} else{
// The app has been opened before
}

Related

remove data inside the key in SharedPreferences

im using flutter 2.8.1 and shared_preferences: ^2.0.13
i build a todoapp with sharedpreferences all works fine from storing data to localstorage and load the data in initState but now i want to delete spesific item/selected item in the localstorage but when i use prefs.remove('key'); all the item is removed, i only want to remove the selected item only.
let me know if you need more information with the code.
the key contain this, for example i want to remove item with id: 64, not the key
I/flutter ( 9643): [{"id":64,"set_name":"asd"},{"id":55,"set_name":"asdasdwqe"}]
remove function code
Future deleteData() async {
final SharedPreferences prefs = await _prefs;
prefs.remove('sets');
setState(() {});
}
save function code
Future saveData() async {
final SharedPreferences prefs = await _prefs;
List items = c.setList.map((item) => item.toJson()).toList();
prefs.setString('sets', jsonEncode(items));
}
There isn't easy way but to overwrite new values over old value. This is one of the drawbacks of using SharedPreferences over traditional databases.
You will have to read the data from sharedPrefs, remove the concerned value and save it back to sharedPrefs.

Read data using from the device as soon as an app opens in flutter

I am saving the app's theme to the device using SharedPreferences, in this way:
void _serializeTheme() async {
SharedPreferences _preferences = await SharedPreferences.getInstance();
_preferences.setString("theme", "dark");
}
Upon opening the app I can use _preferences.getString("theme") to detect the theme, but as SharedPreferences.getInstance() is async, I need to wrap the home of my application in a FutureBuilder which waits for the theme to load before displaying the page and renders a container while waiting. My problem is that for the brief time that the app spends loading the theme the screen flashes with the color of the container which, as I have no idea of which theme the user has saved before loading it, has to be a fixed color which may be in discordance with the background color of the home page. To prevent this is there a way I can load the theme before displaying anything at all?
So, is there a way to run an asyncronous function before opening the application? Or if this isn't fiesable, is there a way to read data syncronously from the device so that I could read it inside initState() so that I can know the theme that the user saved before rendering anyting?
In your case, I would get await data in before runApp(),
Example:
main()async{
// Here
SharedPreferences _preferences = await SharedPreferences.getInstance();
runApp(YourApp());
}
or
void main() {
runZonedGuarded(() async {
// Here
SharedPreferences _preferences = await SharedPreferences.getInstance();
runApp(YourApp());
}, (_, s) {});
}
You have to show something. You can set a splash screen of your choice using https://pub.dev/packages/flutter_native_splash, and then use that same screen to show when the FutureBuilder doesn't yet have the completed future, before transitioning to your main theme when it's ready.

How to save data in my settings menu in Flutter?

I was wondering how to save data locally in Flutter. I am creating a Settings menu in my app, and I have a draft made of that UI, but I want to save the user's preferences when they close that menu, but I have no idea how to accomplish that.
Do you know some tutorial to do so? I have searched in Youtube, but I have no idea how to search for it. I have only found UI tutorials and I don't want that.
A picture of my UI is (I want to save that boolean option).
I would appreciate any help you could give to me!
You should use shared_preferences package. It's very simple and it's for non-critical data like this! Here is an example how to use it:
class SettingsRepository {
final SharedPreferences preferences;
SettingsRepositoryImpl(this.preferences);
Future<int> getDifficulty() {
return preferences.getInt(Keys.difficulty) ?? 1;
// this 1 in the end is a default value
}
Future setDifficulty(int difficulty) {
return preferences.setInt(Keys.difficulty, difficulty);
}
}
To learn more go to https://pub.dev/packages/shared_preferences. I assume you want to call preferences.setBool
You can save your boolean option using shared preferences.
Future<Null> saveOption(bool isSelected) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('option', isSelected);
}
Then you can get the option from there.
Future<bool> getOption() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool('option');
}
You can read more from here.

Flutter SharedPreferences resetting the data

I have this code in flutter using SharedPreferences to store data:
Future<bool> setUserStatus(String userStatus) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('userStatus', 'active');
return true;
}
Is it possible to use this same setUserStatus in another file, which will get this main.dart imported to it, and change the SharedPreferences data to something else based on the actions taken in the other file
Do this,
await setUserStatus( status );
if you don't want to wait for the future to complete just remove await from the begining.
Calling prefs.clear()will erase all the preferences set on the device. so I would suggest not to use that here. If you want to clear a particular preference just use
prefs.remove(key) or prefs.setString(key,null)

How to update value inside shared preferences in flutter

actually when saving data inside shared preferences.. I am using this code
add() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('data', "ok");
}
but, is there a way to update the value of data for example I want to change ok into fine
because when I try to re-save my data using that code... and call it using prefs.getString('data'); it always shows the old data not the update one
Just reassign it again
prefs.setString('data', "fine");
//shared-preferences
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('profileImg', data1['imagePath']);
prefs.setString('un', data1['username']);