Search code examples
dartfluttersharedpreferencesdata-persistence

Shared Prefs with Flutter, what am I doing wrong?


I'm trying to use a sharedprefs to simplify data persistency across different Pages/Fragment, (ignore the "json" written here and there) and before you ask, this is just for disposable data, the app will be build over SQL.

so I created a class to handle the sharedprefs

import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

class JsonHelper {
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

   getJson(String _key) async {
    final SharedPreferences prefs = await _prefs;
    final String _json = prefs.getString('$_key');
    return _json;
  }

  setJson(String _key, String _json) async {
    final SharedPreferences prefs = await _prefs;
    prefs.setString('$_key', _json);
  }

  delJson(String _key) async {
  final prefs = await SharedPreferences.getInstance();
  prefs.remove('$_key');
  }
}

and a "simple" homepage, so simple that doesn't work

import 'package:flutter/material.dart';
import 'package:flutter_3/DATABASE/JsonHelper.dart';

class LandingPage extends StatefulWidget {
  @override
  _LandingPageState createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {
  JsonHelper _jHelp;
  String _localKey = 'test';
  TextEditingController _textCTRL;

  @override
  void initState() {
    _jHelp.setJson(_localKey, "start");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(_jHelp.getJson(_localKey)),
        ),
        body: Center(
          child: Column(
            children: [
              TextField(
                controller: _textCTRL,
                decoration: InputDecoration(labelText: 'write here'),
              ),

              RaisedButton(onPressed:_pressButton)
            ],
          ),
        ),
      ),
    );
  }

  void _pressButton () {
    _jHelp.setJson(_localKey, _textCTRL.toString());
    Navigator.of(context).pop();
  }
}

What am I doing wrong? thank you in advance for the help


Solution

  • You can also achieve without FutureBuilder.

       import 'dart:async';
        import 'package:flutter/material.dart';
        import 'package:shared_preferences/shared_preferences.dart';
    
        void main() {
          runApp(MyApp());
        }
    
        class MyApp extends StatelessWidget {
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              title: 'SharedPreferences Demo',
              home: LandingPage(),
            );
          }
        }
    
        class LandingPage extends StatefulWidget {
          @override
          _LandingPageState createState() => _LandingPageState();
        }
    
        class _LandingPageState extends State<LandingPage> {
          JsonHelper _jHelp;
          String _localKey = "test";
          TextEditingController _textCTRL;
          Future<String> data;
          String text = "start";
          final myController = TextEditingController();
    
          @override
          void initState() {
            _jHelp = JsonHelper();
            _jHelp.setJson(_localKey, "start");
            super.initState();
          }
    
          @override
          void dispose() {
            myController.dispose();
            super.dispose();
          }
    
    
    
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              home:  Scaffold(
                appBar: AppBar(
                  title: Text(text),
                ),
                body: Center(
                  child: Column(
                    children: [
                      TextField(
                        controller: myController,
                        decoration: InputDecoration(labelText: 'write here'),
                      ),
    
                      RaisedButton(
                        onPressed:_pressButton,
                        child: new Text("check"),
                      )
                    ],
                  ),
                ),
              )
            );
          }
    
          void _pressButton () async{
            await _jHelp.setJson(_localKey,myController.text.toString());
            String getdata = await _jHelp.getJson(_localKey) as String;
            setState(() {
              text = getdata;
            });
          }
        }
    
        class JsonHelper {
    
    
           Future<String> getJson(String _key) async {
             SharedPreferences prefs = await SharedPreferences.getInstance();
            String _json = prefs.getString('$_key') ?? "start";
            return _json;
          }
    
           setJson(String _key, String _json) async {
            SharedPreferences prefs = await SharedPreferences.getInstance();
            prefs.setString('$_key',_json);
          }
    
          delJson(String _key) async {
            final prefs = await SharedPreferences.getInstance();
            prefs.remove('$_key');
          }
        }