Shared Preferences not fetching/saving variable data

Issue

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();
    }
  }
}

Solution

I have tried to build an app from your code snipped. This should give you some hints. But be careful with storing passwords in shared preferences.

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);
  }
}

Answered By – Tim Brückner

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published