Home > Blockchain >  i want to get data from api with bearer token flutter, no error, but data not showing
i want to get data from api with bearer token flutter, no error, but data not showing

Time:05-11

I want to get data jobs from API with bearer token flutter, no error, but data not showing.

I don't understand getting API with the bearer token.

please help me.

thanks..

jobs_service.dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:nyoba/models/jobs_model.dart';
import 'package:nyoba/models/user_model.dart';

class JobsServices {
  String baseUrl = 'https://link-id.com/api';
  var token = UserModel().token;

  Future<List<JobsModel>> getJobs() async {
    var url = Uri.parse('$baseUrl/vacancy');
    var headers = {
      'Content-Type': 'application/json',
      'Authorization': '$token',
    };
    var response = await http.get(url, headers: headers);

    print(response.body);
    print(token);

    if (response.statusCode == 200) {
      List data = jsonDecode(response.body)['data']['data'];
      List<JobsModel> jobs = [];
      for(var item in data){
        jobs.add(JobsModel.fromJson(item));
      }
      return jobs;
    } else {
      throw Exception('Failed to get jobs');
    }
  }
}

CodePudding user response:

Does your var token have 'Bearer' in it already? You might have to include it like this:

var headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer $token',
}

Though normally you'd get a 401 forbidden back, and not a 200 if you made the request with an invalid token

CodePudding user response:

user_model.dart

class UserModel {
  int? id;
  String? name;
  String? email;
  String? password;
  String? profilePhotoUrl;
  String? token;

  UserModel ({
    this.id,
    this.name,
    this.email,
    this.password,
    this.profilePhotoUrl,
    this.token,
  });

  UserModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    email = json['email'];
    password = json['password'];
    profilePhotoUrl = json['photo'];
    token = json['token'];
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'email': email,
      'password': password,
      'photo': profilePhotoUrl,
      'token': token,
    };
  }

}
  • Related