dart 使用API登录并转到主页

iyfjxgzm  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(161)

我有flutter和button的登录表单:

FloatingActionButton(
    onPressed: log_in,
)

我的log_in函数:

log_inc() async {

    var headers = {
      'Content-Type': 'text/html',
    };

    var data = '{"username":"XXXXX", "password":"XXXXX"}';

    var url = Uri.parse('http://XXXXX/api/auth/get_tokens');
    var res = await http.post(url, headers: headers, body: data);
    if (res.statusCode != 200)
      throw Exception('http.get error: statusCode= ${res.statusCode}');
    var data_res = jsonDecode(res.body);


    final storage = new FlutterSecureStorage();
    await storage.write(key: "token", value: data_res["access_token"]);
    var token = await storage.read(key: "token");
    print(token);
    return Home_page();
}

一切正常,我正在获取访问令牌并将其存储在FlutterSecureStorage中,但我无法重定向到Home_page。我做错了什么?

ltqd579y

ltqd579y1#

要导航到Home_page,可以使用Flutter中的Navigator类。

log_in() async {
  var headers = {
    'Content-Type': 'text/html',
  };

  var data = '{"username":"XXXXX", "password":"XXXXX"}';

  var url = Uri.parse('http://XXXXX/api/auth/get_tokens');
  var res = await http.post(url, headers: headers, body: data);
  if (res.statusCode != 200)
    throw Exception('http.get error: statusCode= ${res.statusCode}');
  var data_res = jsonDecode(res.body);

  final storage = new FlutterSecureStorage();
  await storage.write(key: "token", value: data_res["access_token"]);

  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => Home_page()),
  );
}

相关问题