【问题标题】:Storing a data permanent with Flutter使用 Flutter 永久存储数据
【发布时间】:2021-06-12 13:11:24
【问题描述】:

我正在使用 Flutter 和 Firebase 开发一个应用程序。

我想用 SharedPreferences 永久存储 _id。

因此,我照顾它,但我的代码根本不起作用。它总是抛出错误:

类型“未来”不是类型“字符串”的子类型

这是我的代码:

class Profile with ChangeNotifier {
  String _id;
  void setName(String name) {
    const url =
        'myurl';
    http
        .post(url, body: json.encode({'name': name, 'description': name}))
        .then((response) {
      _id = json.decode(response.body)['name'];
    });
    addID();
  }

  Future<void> updateName(String name, String id) async {
    String url =
        'myurl';
    await http.patch(url,
        body: json.encode({'name': 'Ein Titel', 'description': name}));
  }

这是我使用 SharedPrefs 的方法:

String getID() {
    return getIDOffline();
  }

  addID() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('id', _id);
  }

  getIDOffline() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return String
    String stringValue = prefs.getString('id');
    return stringValue;
  }

【问题讨论】:

    标签: firebase flutter http mobile


    【解决方案1】:

    当您使用异步时,请始终尝试添加 Future。

    喜欢:

     Future<returnType> methodName() async { }
    

    在您的代码中尝试更改 String getID(){ }Future&lt;String&gt;getID() async{ }

    【讨论】:

      【解决方案2】:

      您使用了错误的返回字符串方法,因此您必须将String getID() 更改为Future&lt;String&gt; getID()。你可以这样使用。

      getValue()async{
      String value = await getID();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-22
        • 2021-08-27
        • 1970-01-01
        • 2016-12-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多