与 Flutter 共享首选项,我做错了什么?

Shared Prefs with Flutter, what am I doing wrong?

我正在尝试使用 sharedprefs 来简化数据持久性 跨越不同的 Pages/Fragment,(忽略这里和那里写的 "json") 在您询问之前,这仅适用于一次性数据,该应用程序将在 SQL.

上构建

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

还有一个"simple"主页,简单得不行

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

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

那是因为你的方法 getJson 是异步的,你可以使用 FutureBuilder 来获取响应,看这里:https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html

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

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

不用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');
      }
    }