【问题标题】:How can i store the ID permanent? (Flutter)如何永久保存 ID? (扑)
【发布时间】:2021-03-14 17:43:21
【问题描述】:

我正在使用 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;
  }

【问题讨论】:

    标签: string firebase flutter sharedpreferences


    【解决方案1】:

    试试这个:

      void setName(String name) {
        const url = 'myurl';
        var body = json.encode({'name': name, 'description': name});
        var response = await http.post(url, body: body);
        String id = json.decode(response.body)['name'];
        addID(id);
      }
    
      addID(id) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('id', id);
      }
    
      Future<String> getID() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        //Return String
        String stringValue = prefs.getString('id');
        return stringValue;
      }
    

    您的 getID 是异步函数,因此它返回 Future 而不是 String..

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 1970-01-01
      • 2011-05-18
      • 2023-04-09
      • 2021-07-17
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多