How can I return two string values in dart flutter - flutter

I am working on my flutter project where I want to use sharedpreferences. Look at the code below:
Future<String?> getCredentials() async {
final localStorage = await SharedPreferences.getInstance();
final email = localStorage.getString('email');
final password = localStorage.getString('password');
return email, password;
}
This is my getCredentials funtion I want this function to return email and password as different parameters but dart doesn't allow me can you please help me How can I do it?
Whole SharedPreference Code:
import 'package:shared_preferences/shared_preferences.dart';
class sharedPreference {
Future<String?> saveCredentials({
required String email,
required String password,
}) async {
final localStorage = await SharedPreferences.getInstance();
await localStorage.setString('email', email);
await localStorage.setString('password', password);
}
Future<String?> getCredentials() async {
final localStorage = await SharedPreferences.getInstance();
final email = localStorage.getString('email');
final password = localStorage.getString('password');
return email, password;
}
}

Just create class. You can even add methods to Credentials later. Like secure compare to compare passwordHash with constant time.
class Credentials {
Credentials(this.email, this.passwordHash);
final String email;
final String passwordHash;
}
Future<Credentials> getCredentials() async {
final localStorage = await SharedPreferences.getInstance();
final email = localStorage.getString('email');
final passwordHash = localStorage.getString('passwordHash');
return Credentials(email, passwordHash));
}
Edit use crypto to get hash of password:
import 'dart:convert';
import 'package:crypto/crypto.dart';
String getHash(String plainPassword) {
return sha256.convert(utf8.encode(plainPassword)).toString();
}

change return type String to Map<String,dynamic>
Future<Map<String,dynamic>> getCredentials() async {
final localStorage = await SharedPreferences.getInstance();
final email = localStorage.getString('email');
final password = localStorage.getString('password');
return {
'email':email,
'password':password
};
}

Related

This expression has a type of 'void' so its value can't be used - Flutter

import 'package:demo_app/services/api.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthProvider extends ChangeNotifier{
bool isAuthenticated = false;
late String token;
late ApiService apiService;
AuthProvider() {
init();
}
Future<void> init() async {
token = await getToken();
if (token.isNotEmpty) {
isAuthenticated = true;
}
apiService = ApiService(token);
notifyListeners();
}
Future<void> register(String name, String email, String password, String passwordConfirm, String deviceName) async{
token = await apiService.register(name, email, password, passwordConfirm, deviceName);
isAuthenticated = true;
setToken();
notifyListeners();
}
Future<void> logIn(String email, String password, String deviceName) async{
token = await apiService.login(email, password, deviceName);
isAuthenticated = true;
setToken();
notifyListeners();
}
Future<void> logOut() async{
token = '';
isAuthenticated = false;
setToken();
notifyListeners();
}
Future<void> setToken() async{
final pref = await SharedPreferences.getInstance();
pref.setString('token', token);
}
Future<void> getToken() async{
final pref = await SharedPreferences.getInstance();
pref.getString('token') ?? '';
}
}
token = await getToken();
gives this error
This expression has a type of 'void' so its value can't be used.
Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.
Any clue on solving this issue?
Try the following code:
Future<void> init() async {
token = await getToken();
if (token.isNotEmpty) {
isAuthenticated = true;
}
apiService = ApiService(token);
notifyListeners();
}
Future<String> getToken() async {
final pref = await SharedPreferences.getInstance();
final token = pref.getString("token") ?? "";
return token;
}

Save authentication data to Firebase Realtime Database

I need the username and password that is created to be saved in the database, I have already created my database with realtime database that I am currently using to store data from a form that I create
import 'package:firebase_auth/firebase_auth.dart';
import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
abstract class BaseAuth {
Future<String> singInWithEmailAndPassword(String email, String password);
Future<String> createUserWithEmailAndPassword(String email, String password);
Future<String> currentUser();
Future<void> singOut();
}
class Auth implements BaseAuth {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final databaseRef = FirebaseDatabase.instance.ref();
#override
Future<String> singInWithEmailAndPassword(
String email, String password) async {
UserCredential user = await _firebaseAuth.signInWithEmailAndPassword(
email: email.toString(), password: password.toString());
return user.toString();
}
#override
Future<String> createUserWithEmailAndPassword(
String email, String password) async {
UserCredential user = await _firebaseAuth.createUserWithEmailAndPassword(
email: email.toString(), password: password.toString());
return user.toString();
}
#override
Future<String> currentUser() async {
User currentUser = _firebaseAuth.currentUser!;
return currentUser.toString();
}
#override
Future<void> singOut() async {
return _firebaseAuth.signOut();
}
}
This es my auth.dart,this is where i created my methods to create and login
I hope you can support me since this is part of my final project

How To Call values from provider Flutter

I have this provider which retrieves data from a shared preference.
class AuthProvider with ChangeNotifier {
String? usertoken = '';
String? tokenExpiry = '';
Future<AuthResponse> getuserdata() async {
SharedPreferences _preferences = await SharedPreferences.getInstance();
String? userdata = _preferences.getString('userData');
var usersData = jsonDecode(userdata!);
AuthResponse authResponse = AuthResponse.fromJson(usersData);
usertoken = authResponse.token;
print('Test in provider : $usertoken');
notifyListeners();
return authResponse;
}
}
How can i get the values i need from the provider? to say another function?
getinterestList() async {
final test = Provider.of<AuthProvider>(context).usertoken; //gets Error
print(test);
}

How to delete data of shared-preferences from singleton in flutter?

I make one file to shared preferences to store data in it from my app. It's work fine.But now I want to delete data from store as button log-out for user. So if user click button of log-out data will be clear from shared preferences file. How I can do it from different class?
import 'package:shared_preferences/shared_preferences.dart';
class MyPreferences{
static const USER = "user";
static const PASSWORD = "password";
static final MyPreferences instance = MyPreferences._internal();
//Campos a manejar
SharedPreferences _sharedPreferences;
String user = "";
String password = "";
MyPreferences._internal(){
}
factory MyPreferences()=>instance;
Future<SharedPreferences> get preferences async{
if(_sharedPreferences != null){
return _sharedPreferences;
}else{
_sharedPreferences = await SharedPreferences.getInstance();
user = _sharedPreferences.getString(USER);
password = _sharedPreferences.getString(PASSWORD);
return _sharedPreferences;
}
}
Future<bool> commit() async {
await _sharedPreferences.setString(USER, user);
await _sharedPreferences.setString(PASSWORD, password);
}
Future<MyPreferences> init() async{
_sharedPreferences = await preferences;
return this;
}
}
Define your shared preference manager class as a singleton as given,
class SharedPreferenceManager{
static final SharedPreferenceManager _singleton = new SharedPreferenceManager._internal();
factory SharedPreferenceManager() {
return _singleton;
}
SharedPreferenceManager._internal() {
... // initialization logic here
}
... // rest of the class
}
By this, you can create and access the single, reusable instance of that class. You can define a static method in the class which will be accessible from outside. As the static method can have access to only static data members, You should define the sharedPrefernece member variable as static. Here is how you can clear all the data.
static Future<bool> clearSharedPrefs(){
SharedPreferences preferences = await SharedPreferences.getInstance();
await preferences.clear();
}
After this, you'll be able to call this method from any class, just as SharedPreferenceManager.clearSharedPrefs().
It's a good practice to follow the singleton pattern for database, network and shared preference related tasks.
Here is the code you should go with.
import 'package:shared_preferences/shared_preferences.dart';
class MyPreferences{
static const USER = "user";
static const PASSWORD = "password";
static final MyPreferences instance = MyPreferences._internal();
static SharedPreferences _sharedPreferences;
String user = "";
String password = "";
MyPreferences._internal(){}
factory MyPreferences()=>instance;
Future<SharedPreferences> get preferences async{
if(_sharedPreferences != null){
return _sharedPreferences;
}else{
_sharedPreferences = await SharedPreferences.getInstance();
user = _sharedPreferences.getString(USER);
password = _sharedPreferences.getString(PASSWORD);
return _sharedPreferences;
}
}
Future<bool> commit() async {
await _sharedPreferences.setString(USER, user);
await _sharedPreferences.setString(PASSWORD, password);
}
Future<MyPreferences> init() async{
_sharedPreferences = await preferences;
return this;
}
static Future<bool> clearPreference() async{
if(_sharedPreferences){
_sharedPreferences.clear();
}
}
}
You can use remove or clear on shared preferences.
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.clear();
// OR
preferences.remove("MY KEY HERE");

Access other Class method in Flutter/dart

I was working on login with preference. Everything is working fine when I wrote all code in main.dart.
Problem:
When I create separate class on MySharePref then I am getting some error.
MySharePref.dart
import 'package:first_app/UserModel.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharePrefClass {
void _saveData(UserModel model) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString("Username",model.userName);
await prefs.setString("Password", model.password);
}
Future<UserModel> _getData() async{
SharedPreferences preferences = await SharedPreferences.getInstance();
String username = preferences.getString("Username");
String password = preferences.getString("Password");
UserModel model = UserModel(username,password);
return model;
}
}
I want to access these both functions in main.dart:
_checkLogin() async {
UserModel userModel = new UserModel(
userNameEditText.text , passwordEditText.text);
SharePrefClass mySharedPref = new SharePrefClass();
final UserModel returnModel = mySharedPref._getData() ;
if(returnModel.userName == ""){
print("No data");
}else{
print("else executed");
}
}
I am getting error:
The prefix "_" means private field in dart.
Change the method name _getData() to getData() will let you can access this method in main.dart