Flutter handle future response

230 Views Asked by At

i want to store token value and navigate home page using go router after login. i dont know how to handle json data like display or (retrieve)name and role.. i am newbie for programming.

Help me.thanks in advance.i tried futurebuilder examples it not worked. kindly give simple solution.


  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']);
  }
}
1

There are 1 best solutions below

5
On BEST ANSWER

Use shared_preferences usage is straight forward

here just do this

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

And next time you want to check wether user was logged in or not

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

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

///Create a separate helper/manager for shared preferences. This is just an example///