I’m trying to fetch data from an api by passing bearer token but it is throwing this exception. Here’s my code below :
This is my afterLoginResponse.dart class –
class AfterLoginResponse {
LoginData? data;
bool? operator;
bool? success;
AfterLoginResponse({
required this.operator,
required this.success,
required this.data,
});
AfterLoginResponse.fromJson(Map<String, dynamic> json) {
operator = json['operator'];
success = json['success'];
data = LoginData.fromJson(json["data"]);
}
Map<String, dynamic> toJson() => {
"operator": operator,
"success": success,
"data": data!.toJson(),
};
}
Below is my loginData.dart class ->
class LoginData {
String? name;
String? ext;
String? dName;
String? password;
LoginData({
required this.name,
required this.ext,
required this.dName,
required this.password,
});
factory LoginData.fromJson(Map<String, dynamic> json) {
return LoginData(
name: json['name'],
ext: json['ext'],
dName: json['d_Name'],
password : json['password'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['name'] = name;
data['ext'] = ext;
data['d_Name'] = dName;
data['password'] = password;
return data;
}
}
This is my apiService.dart class –
class ApiService{
String? token;
var response1;
var response2;
Future<LoginResponseData> loginApiCall(Map<String, dynamic> param) async{
var url = Uri.parse(ApiUrls.login_url);
response1 = await http.post(url, body: param);
final data = jsonDecode(response1.body);
token = LoginResponseData.fromJson(json.decode(response1.body)).token;
return LoginResponseData(user: data['user'], token:
data['token'],error:data['error']);
}
Future<AfterLoginResponse> postLoginApiCall() async{
var afterLoginUrl = Uri.parse(ApiUrls.postLogin_url);
response2 = await http.get(afterLoginUrl , headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer
${LoginResponseData.fromJson(json.decode(response1.body)).token}'
});
if(response2.statusCode == 200){
var data = jsonDecode(response2.body);
return AfterLoginResponse.fromJson(data);
}else{
throw Exception('Failed to load data');
}
}
}
Here is my UI –
class HomePage extends StatefulWidget {
String email, password;
HomePage({Key? key, required this.email, required this.password})
: super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late Future<AfterLoginResponse> afterLoginResponse;
final apiService = ApiService();
callPostLoginApi(){
return FutureBuilder<AfterLoginResponse>(
future: afterLoginResponse,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!);
print(snapshot.data);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home page'),
centerTitle: true,
),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: callPostLoginApi,
child: const Text('Click me'))
],
),
)
);
}
The above code is throwing following exception –
Unhandled Exception: NoSuchMethodError: The getter ‘body’ was called on null.
Receiver: null
E/flutter (28599): Tried calling: body
E/flutter (28599): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
.
.
.
2
Answers
in the postLoginApiCall you are calling body with response1 variable which is at that very time null that is causing the issue change that to response2 like this:
You should call the
postLoginApiCall
after getting response from theloginApiCall