Home > Mobile >  Flutter SharedPreferences
Flutter SharedPreferences

Time:09-27

I can't clear data, I need your help to understand the problem.

Future<void> _clearData() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('keydata');
}

full example:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);



  @override
  State<HomePage> createState() => _HomePageState();
}


class _HomePageState extends State<HomePage> {

  late double? savedData = 0.0;

  final TextEditingController textController = TextEditingController();


  Future retrieveData() async {
    final prefs = await SharedPreferences.getInstance();
         return savedData = prefs.getDouble('keydata');
  }

   Future saveData() async {
    final prefs = await SharedPreferences.getInstance();
   return prefs.setDouble('keydata', savedData!);
  }

   Future clearData()  async {
    final prefs = await SharedPreferences.getInstance();
     await prefs.clear();
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Test SharedPreferences'),
      ),
      body: InkWell(
      onTap: () {
      setState(() {
      FocusScope.of(context).requestFocus(FocusNode());
      });
      },
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 40.0),
          child:
          Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              const Spacer(),
              TextField(
                controller: textController,
                keyboardType: const TextInputType.numberWithOptions(decimal: true),
                decoration:
                const InputDecoration(labelText: 'Data to save'),
              ),
              const Spacer(),
              ElevatedButton(
                  onPressed: (() {
                    setState(() {
                      savedData = double.parse(textController.text);
                      saveData;
                    });
                    textController.clear();
                  }),
                  child: const Text('Save')
              ),
              const Spacer(),
                    Text('savedData : ${savedData!.toStringAsFixed(2)}',
                      style: const TextStyle(fontSize: 20),
                    ),
                    const Spacer(),
                    ElevatedButton(
                        onPressed: () {
                          setState: () {
                            clearData();

                          };
                          print(savedData);
                        },
                        child: const Text('Reset')
                    ),
                    const Spacer(),

            ],
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

Actually you are not removing a single sharedPreference but you are clearing all the sharedPreferences when you call clearData function

Don't call async in setState

try this:

ElevatedButton(
  onPressed: () async{
    await clearData(); //call it like this
  };
  print(savedData);
  },
  child: const Text('Reset')
 ),

CodePudding user response:

You should not call async function in setState method, so change this:

onPressed: () {
    setState: () {
        clearData();
    };
    print(savedData);
},

to:

onPressed: () async{
        await clearData();
        setState: () {
           savedData = 0.0;
        };
        print(savedData);
    },

also in your save method you are doing it wrong, change this:

ElevatedButton(
    onPressed: (() {
        setState(() {
           savedData = double.parse(textController.text);
           saveData;
        });
        textController.clear();
     }),
     child: const Text('Save')
),

to :

ElevatedButton(
              onPressed: () {
                setState(() {
                  savedData = double.parse(textController.text);
                  
                });

                saveData();
                textController.clear();
              },
              child: const Text('Save')),
  • Related