I only want to fetch/get single api
data, i tried to print the response from service
i got all the api
data but when i try to pass it to the controller
the variable for model didn't correct,
i already look for the anwser for fetching single api with Service
and Controller
architecture with GetX
but i didn't find any suitable answer, i hope you can help me it's very important. thanks
im using http
and GetX
the problem is here
var user = <UserModel>{}.obs;
user.value = _user;
it tells
UserModel _user A value of type 'UserModel' can't be assigned to a variable of type 'Set'. Try changing the type of the variable, or casting the right-hand type to 'Set
here is the code
Api Service
class ApiService {
Future<UserModel> fetchApi(id) async {
var url = 'https://reqres.in/api/users/$id';
var response = await http.get(Uri.parse(url));
if(response.statusCode == 200){
var dataResponse = jsonDecode(response.body)['data'];
UserModel user = UserModel.fromJson(dataResponse);
return user;
} else {
throw Exception('Failed Get API');
}
}
}
Controller
class Controller extends GetxController {
var user = <UserModel>{}.obs;
Future fetchApi(id) async {
try {
var _user = await ApiService().fetchApi(id);
user.value = _user;
print(user);
} catch (e) {
print(e);
}
}
}
Model
class UserModel {
int id;
String email;
String name;
String avatar;
UserModel({
required this.id,
required this.email,
required this.name,
required this.avatar,
});
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json['id'],
email: json['email'],
name: json['first_name'] + ' ' + json['last_name'],
avatar: json['avatar'],
);
}
The main reason is that you are defining user as {} type and you need UserModel Type.
You need change this:
var user = <UserModel>{}.obs;
user.value = _user;
for this:
var user = UserModel().obs;
user.value = _user;