Skip to content

Instantly share code, notes, and snippets.

@omarzer0
Created February 9, 2023 15:35
Show Gist options
  • Save omarzer0/2eb1fd9aab1df440bd6f3a59d4dde0a4 to your computer and use it in GitHub Desktop.
Save omarzer0/2eb1fd9aab1df440bd6f3a59d4dde0a4 to your computer and use it in GitHub Desktop.
shared preferences
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: QuranScreen(),
),
);
}
class QuranScreen extends StatelessWidget {
const QuranScreen({Key? key}) : super(key: key);
void saveData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.setString("name", "Omar");
await preferences.setString("Ui color", "Blue");
await preferences.setBool("Dark Theme", false);
await preferences.setInt("undo count", 30);
var name = preferences.getString("name");
print(name);
var username = preferences.getString("username") ?? "not found";
print(username);
// remove with key
preferences.remove("name");
// // clear all preferences
// preferences.clear();
}
void saveLogged() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setBool("loggedIn", true);
}
void checkLogged() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
var loggedIn = preferences.getBool("loggedIn") ?? false;
print(loggedIn);
}
void logOut() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
ElevatedButton(onPressed: saveData, child: Text("Save data")),
ElevatedButton(onPressed: saveLogged, child: Text("save logged")),
ElevatedButton(onPressed: checkLogged, child: Text("check logged")),
ElevatedButton(onPressed: logOut, child: Text("logOut")),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment