How do I use SharedPreferences in flutter?
316
Solution 1
Add shared preference dependency in your pubspec.yaml
file.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
shared_preferences: ^0.5.12+4
Now run flutter pug get. After getting the package import in your file like this,
import 'package:shared_preferences/shared_preferences.dart';
Now that should work fine.
Solution 2
- open
pubspec.yaml
- add
shared_preferences: ^0.5.12+4
belowdependencies:
- run
flutter pub get
import 'package:shared_preferences/shared_preferences.dart';
here is link https://pub.dev/packages/shared_preferences/install
Comments
-
Bennett567 over 1 year
I am trying to get GoogleSign in working with a webapp in flutter, and for that I have been following an article. This is the function they said to use there for the login:
Future<String> signInWithGoogle() async { // Initialize Firebase await Firebase.initializeApp(); final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); final UserCredential userCredential = await _auth.signInWithCredential(credential); final User user = userCredential.user; if (user != null) { // Checking if email and name is null assert(user.uid != null); assert(user.email != null); assert(user.displayName != null); assert(user.photoURL != null); uid = user.uid; name = user.displayName; userEmail = user.email; imageUrl = user.photoURL; assert(!user.isAnonymous); assert(await user.getIdToken() != null); final User currentUser = _auth.currentUser; assert(user.uid == currentUser.uid); SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setBool('auth', true); return 'Google sign in successful, User UID: ${user.uid}'; } return null; }
It says that SharedPreferences is an undefined class. What does this do? Is it neccesary? If yes, how can I fix this? Thank you very much for your help, as this is my first time working with google sign-in in flutter web.
-
jdsflk over 3 yearsDid you add shared_dependencies to your pubspec.yaml?
-
Bennett567 over 3 yearsNo, where should I add it?
-
Sagar Acharya over 3 yearsif you have added the sharedprefrences in the pubspec.yaml some times the changed does not reflect in the project its better you restart the IDE and check again. Let me know if it works
-
jdsflk over 3 yearsIn the dependencies section, here is the official guide of installation: pub.dev/packages/shared_preferences/install
-