Search code examples
flutterdarttoken

saved token in login page and how to receive it on List page in flutter?


I have two pages,

  1. Login page
  2. list page

Already saved token in login page, but how to receive it on list page inside Future?

Login page response

Future<Album> createAlbum(String employee_custom_id, String password) async {
    final response = await http.post(
      Uri.parse('https://portal-api.jomakhata.com/api/auth/login'),
      headers: <String, String>{
        'Content-Type': 'application/json',
      },
      body: jsonEncode(<String, String>{
        'employee_custom_id': employee_custom_id,
        'password': password,
      }),
    );

    final data = json.decode(response.body);

    if (response.statusCode == 200) {
     saveToken(data);
      log('$data');
      return Album.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to create album.');
    }
  }
 //save token
  void saveToken(data) async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.setString("token", data['token']);
    sharedPreferences.setInt("userId", data['userId']);
  }

Now i want to received it on list page, but can't set it on token section

**List page **

    Future<List<ListAlbum>> listData() async {
      final token = // I want to receive token here that i saved in login page.
      String url =
          'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';
    
      Dio dio = new Dio();
      dio.options.headers['Content-Type'] = 'application/json';
      final body = {'limit': 100, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
      final response = await dio.post(url, data: body);
   }

Solution

  • If I understand correctly you are asking this

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    final token = sharedPreferences.getString("token");