Home > database >  how to write a list to local storage in flutter using get storage?
how to write a list to local storage in flutter using get storage?

Time:09-29

In my app i am using API Auth and when user logged in i want to store the user info in local storage using get_storage package. so how can i store a list of objects. what i need is to store the list when user logged in and read that file afterwards in the app.

I've tried to encode the json and assign it to log.write('user', json.encode(value.body)) but the result of which it gives the list but with all items there is "" sign. like "{\"id\":1, \"name\":\"Admin\",.... result. how can i set it appropriately?

user model

import 'role_model.dart';
import 'dart:convert';

List<User> usersFromJsonFromModel(String str) =>
    List<User>.from(json.decode(str).map((json) => User.fromJson(json)));
String usersToJsonFromModel(List<User> data) =>
    json.encode(List<dynamic>.from(data.map((e) => e.toJson())));

class User {
  int? id;
  String? name;
  String? username;
  String? email;
  String? emailVerifiedAt;
  String? twoFactorConfirmedAt;
  String? currentTeamId;
  String? profilePhotoPath;
  String? warehouseId;
  String? createdAt;
  String? updatedAt;
  String? profilePhotoUrl;
  List<Roles>? roles;

  User(
      {this.id,
      this.name,
      this.username,
      this.email,
      this.emailVerifiedAt,
      this.twoFactorConfirmedAt,
      this.currentTeamId,
      this.profilePhotoPath,
      this.warehouseId,
      this.createdAt,
      this.updatedAt,
      this.profilePhotoUrl,
      this.roles});

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    username = json['username'];
    email = json['email'];
    emailVerifiedAt = json['email_verified_at'];
    twoFactorConfirmedAt = json['two_factor_confirmed_at'];
    currentTeamId = json['current_team_id'];
    profilePhotoPath = json['profile_photo_path'];
    warehouseId = json['warehouse_id'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
    profilePhotoUrl = json['profile_photo_url'];
    if (json['roles'] != null) {
      roles = <Roles>[];
      json['roles'].forEach((v) {
        roles!.add(Roles.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['id'] = id;
    data['name'] = name;
    data['username'] = username;
    data['email'] = email;
    data['email_verified_at'] = emailVerifiedAt;
    data['two_factor_confirmed_at'] = twoFactorConfirmedAt;
    data['current_team_id'] = currentTeamId;
    data['profile_photo_path'] = profilePhotoPath;
    data['warehouse_id'] = warehouseId;
    data['created_at'] = createdAt;
    data['updated_at'] = updatedAt;
    data['profile_photo_url'] = profilePhotoUrl;
    if (roles != null) {
      data['roles'] = roles!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

api call

Future loginAuth(String email, String password) async {
  Uri url = Uri.parse("${BASE_URL}login");
  final loginState = GetStorage();
  final response = await http
      .post(url,
          headers: <String, String>{
            'Content-Type': 'application/json; charset=UTF-8',
            'Accept': 'application/json; charset=UTF-8'
          },
          body: jsonEncode(<String, dynamic>{
            'email': email,
            'password': password,
          }))
      .then((value) {
    var data = value.body;
    if (value.statusCode == 200) {
      loginState.write('login', true);
      Get.snackbar(
          "success", "Logged in as ${json.decode(value.body)['username']}");
      print(json.decode(value.body));
      Get.to(Index());
    } else if (value.statusCode == 404) {
      Get.snackbar("failed", "${json.decode(value.body)['message']}");
      print('bad login not workng, ${value.body}');
    } else {
      Get.snackbar("Failed", "Failed to Login, Try Again");
      print('bad login, ${value.body}');
    }
  });
}

Future logoutAuth() async {
  Uri url = Uri.parse("${BASE_URL}login");
  final loginState = GetStorage();
}

so is there a way to store list in local storage or do i have to store every items separately? and if there is how can i read or access that storage in my app?

CodePudding user response:

You can save value.body in local storage because it is already json and don't need to encode it to json. Then every time read it from local storage try to decode it from json and parse it.

Future loginAuth(String email, String password) async {
  Uri url = Uri.parse("${BASE_URL}login");
  final loginState = GetStorage();
  final response = await http
      .post(url,
          headers: <String, String>{
            'Content-Type': 'application/json; charset=UTF-8',
            'Accept': 'application/json; charset=UTF-8'
          },
          body: jsonEncode(<String, dynamic>{
            'email': email,
            'password': password,
          }))
      .then((value) {
    var data = value.body;
    if (value.statusCode == 200) {
      log.write('user', value.body); // <--- add this
      loginState.write('login', true);
      Get.snackbar(
          "success", "Logged in as ${json.decode(value.body)['username']}");
      print(json.decode(value.body));
      Get.to(Index());
    } else if (value.statusCode == 404) {
      Get.snackbar("failed", "${json.decode(value.body)['message']}");
      print('bad login not workng, ${value.body}');
    } else {
      Get.snackbar("Failed", "Failed to Login, Try Again");
      print('bad login, ${value.body}');
    }
  });
}

Note that in this way still you need call json.decode on the result of local storage when you try to read it.

  • Related