Flutter手柄未来响应

irtuqstp  于 2022-12-27  发布在  Flutter
关注(0)|答案(1)|浏览(150)

我想存储令牌值和导航主页使用去路由器登录后。我不知道如何处理json数据一样显示或(检索)名称和角色。。我是新手编程。
帮助我。提前感谢。我尝试了futurebuilder的例子,它不工作。请给予简单的解决方案。

Future<Loginuser> fetchLoginuser(String mobile, String password) async {
    final response = await http.post(
        Uri.parse('https://random.url/api/login'),
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(
            <String, String>{'mobile': mobile, 'password': password}));

    if (response.statusCode == 200) {
      return Loginuser.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to update album.');
    }
  }

  
class Userinfo {
  double branchcode;
  double role;
  double name;

  Userinfo({required this.branchcode, required this.role, required this.name});

  factory Userinfo.fromJson(Map<String, dynamic> json) {
    return Userinfo(
        branchcode: json['branchcode'], role: json['role'], name: json['name']);
  }
}

class Loginuser {
  final String message;
  final String messagecode;
  final String token;
  final Userinfo userinfo;

  const Loginuser({
    required this.message,
    required this.messagecode,
    required this.token,
    required this.userinfo,
  });
  factory Loginuser.fromJson(Map<String, dynamic> json) {
    return Loginuser(
        message: json['message'],
        messagecode: json['messagecode'],
        token: json['token'],
        userinfo: json['userinfo']);
  }
}
nhaq1z21

nhaq1z211#

使用shared_preferences用法简单明了
就这样做

if (response.statusCode == 200) {
      Loginuser _user = Loginuser.fromJson(json.decode(response.body));

      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('token', _user.token');

      return _user;
    } else {
      throw Exception('Failed to update album.');
    }

下次您要检查用户是否已登录时

final prefs = await SharedPreferences.getInstance();
final String? action = prefs.getString('token');

if(token == null){ //not logged in}else{ //logged navigate to dashboard}

为共享首选项创建单独的助手/管理器。这只是一个示例

相关问题