与Flutter共享偏好,我在做什么错了?

时间:2018-10-03 15:18:13

标签: dart flutter sharedpreferences data-persistence

我正在尝试使用sharedprefs来简化数据持久性 跨不同的页面/片段,(忽略此处到处写的“ json”) 在您询问之前,这只是用于一次性数据,该应用程序将基于SQL构建。

所以我创建了一个用于处理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');
  }
}

和一个“简单”首页,如此简单以至于无法正常工作

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

我在做什么错? 预先感谢您的帮助

2 个答案:

答案 0 :(得分:0)

这是因为您的方法getJson是异步的,您可以使用iris[findin(iris[:Species],["setosa"]),:] 来获取响应,在这里看看:https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html

FutureBuilder

答案 1 :(得分:0)

您也可以不用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');
      }
    }