Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – Shared Preferences not fetching/saving variable data

Posted on November 11, 2022 By

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.

READ  [FIXED] android - Want to display more information when i click on see more button
Powered by Inline Related Posts

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

Android Tags:android, dart, flutter

Post navigation

Previous Post: [FIXED] Unable to connect Firebase in Android Emulator for Flutter Project
Next Post: [FIXED] android – Highlight only one Card in Compose through selection

Related Posts

[FIXED] android – Disable status and naviagation bars Android
[FIXED] android – Error while opening creating new Image Asset Android
[FIXED] How can I preview some data from xml to android studio? Android
[FIXED] Implement custom interface in RecyclerViewAdapter with Kotlin in Android Android
[FIXED] java – set image resource from android native resources, programmatically Android
[FIXED] android – Firestore updated values erasing existing ones Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • Can VPN be traced by police?
  • Where were Kaiser-Frazer cars built?
  • How do you make gold rose gold paint?
  • What are the newest type of dentures?
  • Can you wear joggers as dress pants?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme