Solution 1 :
I have tried to build an app from your code snippet. This should give you some hints. But be careful with storing passwords in shared preferences, since values of shared preferences are not stored encrypted on the device.
Check out solutions like the flutter_secure_storage
package:
https://pub.dev/packages/flutter_secure_storage
My current guess is that your setState()
didn’t work, because the targeted variables were declared outside the stateful widget.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Organizer',
initialRoute: '/home',
routes: {
'/home': (context) => const MyHomePage(),
},
),
);
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _textInputController = TextEditingController();
bool authenticated = false;
@override
void initState() {
super.initState();
_getVarSharedPref();
}
@override
void dispose() {
_textInputController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SizedBox(
height: 300,
child: Column(
children: [
TextField(
controller: _textInputController,
decoration: InputDecoration(prefixIcon: _getAuthIcon()),
),
ElevatedButton(
onPressed: checkPassKey,
child: const Text('sign in'),
),
],
),
),
),
);
}
Future<void> _setPassKEYSharedPref() async {
final prefs = await SharedPreferences.getInstance();
// It doesn't make much sense imho, better use a boolean
await prefs.setString('passKEY', 'ThisIsPassword');
}
Future<void> _getVarSharedPref() async {
final prefs = await SharedPreferences.getInstance();
final storedPasskey = prefs.getString('passKEY') ?? 'Not_yet_authorised';
setState(() {
authenticated = storedPasskey == 'ThisIsPassword';
});
}
void checkPassKey() {
final String enteredPassKey = _textInputController.text;
if (enteredPassKey == 'ThisIsPassword') {
setState(() {
authenticated = true;
});
_setPassKEYSharedPref();
}
}
Icon _getAuthIcon() {
return authenticated
? const Icon(Icons.check_circle_sharp, color: Colors.greenAccent)
: const Icon(Icons.lock, color: Colors.redAccent);
}
}
Problem :
I am trying to save a variable value using shared preferences and retrieve it every time the application is launched. Basically, I am trying to hardcode an authentication logic into the app. If the user knows the Pass key the app will return the right string. Also, the icon changes if the key is correct.
When the user reopens the application, the app is supposed to remember if the user had entered the correct Key.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
var authIcon = const Icon(Icons.lock, color: Colors.redAccent,);
late String enteredPassKEY;
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Organizer',
initialRoute: '/home',
routes: {
'/home': (context) => const MyHomePage(),
}
));
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
_getVarSharedPref();
}
@override
Widget build(BuildContext context) {
....
MaterialButton(onPressed: () { checkPassKey(); },),
....
}
Future<void> _setPassKEYSharedPref() async{
final prefs= await SharedPreferences.getInstance();
await prefs.setString('passKEY', 'enteredPassKEY');
}
Future<void> _getVarSharedPref() async {
final prefs= await SharedPreferences.getInstance();
setState((){
enteredPassKEY = prefs.getString('passKEY') ?? 'Not_yet_authorised';
if(enteredPassKEY=='ThisIsPassword') {
setState(() {
authIcon = const Icon(Icons.check_circle_sharp, color: Colors.greenAccent,);
});
}
});
}
void checkPassKey(){
if(enteredPassKEY=='ThisIsPassword'){
setState(() {
authIcon= const Icon(Icons.check_circle_sharp, color: Colors.greenAccent,);
});
_setPassKEYSharedPref();
}
}
}
Comments
Comment posted by Tim Brückner
Okay. Can you please add some information about what is not working as intended, or add a stack trace to your example. That would be helpful.
Comment posted by Nehal Hosalikar
Can you please tell me what was I doing wrong?
Comment posted by Nehal Hosalikar
What do you mean by ‘be careful with storing passwords in shared preferences’? What are the potential dangers?
Comment posted by Stefan de Kraker
The shared preferences are just stored in a