简体   繁体   中英

How can i store the ID permanent? (Flutter)

I am developing an app with Flutter and Firebase.

I want to store the _id with SharedPreferences permanently.

Therefore, i looked after it, but my code doesnt work at all. It always throws the error:

type 'Future' is not a subtype of type 'String'

Here is my code:

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

And here are my methods with the 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;
  }

Try this:

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

Your getID is async function so it return Future and not String..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM