Home > Enterprise >  How to Store a User ID after Login and access from another page in flutter?
How to Store a User ID after Login and access from another page in flutter?

Time:07-07

** API RESPONSE { "data": { "CityName": null, "DOB": "7/07/2022", "DeviceType": "0", "Email": "[email protected]", "MobileNo": "1234567891", "ProfileImage": "", "UserID": "1", "UserName": "xyz", "UserType": "3" }, "message": "Successfully login", "status": 200 **

// Api Services
````Future<Loginmodel?> login() async {
if (passwordController.text.isNotEmpty && nameController.text.isNotEmpty) {
  var response = await http.post(
      Uri.parse(
        'XYZ',
      ),
      headers: {"Content-Type": "application/json"},
      body: (jsonEncode({
        'UserName': nameController.text,
        'Password': passwordController.text,
        'DeviceToken': '',
        'DeviceType': ''
      })));
  if (response.statusCode == 200) {
    var data = jsonDecode(response.body);

    print(data);

    print(data['data']['UserID'].toString());

    if (data['data']['UserID'] == null) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Invaild Credentials")));
    } else {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => Homescreen()));

      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text("Succesfully Credentials")));
    }

    // await Storage.write(key: "token", value: output["token"]);
  }
} else {
  ScaffoldMessenger.of(context)
      .showSnackBar(SnackBar(content: Text("Black Field Not Allowed")));
}
}

CodePudding user response:

Create a class you can use it as per your need. Here is an dummy example change as per your need.

import 'package:shared_preferences/shared_preferences.dart';
class SessionManager {
  final String auth_token = "auth_token";
   late final SharedPreferences prefs;

//set data into shared preferences like this
  Future<void> setAuthToken(String auth_token) async {
    prefs = await SharedPreferences.getInstance();
    prefs.setString(this.auth_token, auth_token);
  }

//get value from shared preferences
  Future<String?> getAuthToken() async {
    final SharedPreferences pref = await SharedPreferences.getInstance();
    String? auth_token;
    auth_token = (pref.getString(this.auth_token) ?? null);
    return auth_token;
  }




  clearAll() async {
    prefs = await SharedPreferences.getInstance();
    await prefs.clear();
  }
}

Call SessionManager globally inside your class.

 SessionManager prefs = SessionManager();

And then set user id as follows when success.

 prefs.setAuthToken(data['data']['UserID']);

You can get the data as follows anywhere in project:

  prefs.getAuthToken();// it returns future 

For getting value

 prefs.getAuthToken().then((value) {
  print(value); //this is your used id
}

CodePudding user response:

create model from https://ashamp.github.io/jsonToDartModel/

create model of just your data no need to create whole model. for you simplicity i created for you.

class UserModel {
  String? CityName;
  String? DOB;
  String? DeviceType;
  String? Email;
  String? MobileNo;
  String? ProfileImage;
  String? UserID;
  String? UserName;
  String? UserType;

  UserModel({
    this.CityName,
    this.DOB,
    this.DeviceType,
    this.Email,
    this.MobileNo,
    this.ProfileImage,
    this.UserID,
    this.UserName,
    this.UserType,
  });
  UserModel.fromJson(Map<String, dynamic> json) {
    CityName = json['CityName']?.toString();
    DOB = json['DOB']?.toString();
    DeviceType = json['DeviceType']?.toString();
    Email = json['Email']?.toString();
    MobileNo = json['MobileNo']?.toString();
    ProfileImage = json['ProfileImage']?.toString();
    UserID = json['UserID']?.toString();
    UserName = json['UserName']?.toString();
    UserType = json['UserType']?.toString();
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['CityName'] = CityName;
    data['DOB'] = DOB;
    data['DeviceType'] = DeviceType;
    data['Email'] = Email;
    data['MobileNo'] = MobileNo;
    data['ProfileImage'] = ProfileImage;
    data['UserID'] = UserID;
    data['UserName'] = UserName;
    data['UserType'] = UserType;
    return data;
  }
}

in your main function

late final SharedPreferences prefs;

void main() async {
  prefs = await SharedPreferences.getInstance();
  runApp(const MyApp());
}

Then in your login api call do this changes

prefs.setString("userData", data['data']);

Then in any other page do like below

LoginModelDataUser userData = LoginModelDataUser();

userData= UserModel.fromJson(prefs.readString("userData"));

Use it like this in you widget

Text(userData.UserName??"")
  • Related