Flutter:在 ChangeNotifier 中使用(未来)http post 请求

Flutter: Using a (Future) http post request in ChangeNotifier

在我的 ChangeNotifier 之一中,如果有验证方法。这是一种方法,即 使用 Future gettoken 函数获取 auth - 令牌,然后设置 LoginController class.

的一些值

当我使用 Provider.of() 调用 .authentificate 时,我想,我改变了结果 getToken 从 Future 到简单的 (通过 .then(...)) 然后尝试评估是否收到令牌。 很遗憾, 打印的最后一件事是来自 get getToken 函数的“API 身份验证成功”,而不是 评估令牌。 我在这里做错了什么?

class LoginController extends ChangeNotifier {
  int pagenr          = 0;
  bool is_logged_in   = false;
  String token_string = "";

  void change_page_nr(int item) {
    pagenr = item;
    notifyListeners();
  }

  void authenticate(String username,String password) {
    getToken(username, password).then((String result){token_string = result;});
    
    // Code seems to stop working here, at least nothing is printed or changed even though
    // the token request exits without an error.

    print("Evaluating the token");
    if (token_string.length > 0) {
      print("Logging in succesful!");
      is_logged_in = true;
      int pagenr   = 1;
    } else {
      print("Logging in failed!");
      is_logged_in = false;
      int pagenr   = 0;
    }
    notifyListeners();
  }

Future<String> getToken(String username, String password) async {
  print("TokenURL in api_connection.dart");
  print(_tokenURL);

  final http.Response response = await http.post(
      Uri.parse(_tokenURL),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
        'Access-Control-Allow-Origin': '*'
      },
      body: jsonEncode(<String, String>{
        'username': username,
        'password': password
      }
      )
);
  if (response.statusCode == 200) {
    print("API Authentification successful!");
    return json.decode(response.body)["token"];
  } else {
    print(json.decode(response.body).toString());
    print("API Authentification failed");
    return "";
  }
}

authenticate 函数更改为异步并等待 getToken

  Future<void> authenticate(String username,String password) async {
    final token_string = await getToken(username, password);
    
    ...

    notifyListeners();
  }