Reputation:
I created a function using rest API to get one user data:
code:
Future<User> getUser(int id) async{
final response = await client.get('$baseUrl/user/$id');
if(response.statusCode == 200){
return userFromJson(response.body);
}else return null;
}
I must get data from user which is current logged in to this sytem, so I get his id
from response with using sharedPreferences
:
sharedPreferences.setInt("id", jsonResponse['id']);
but i don't know how to create an FutureBuilder
which
would insert the appropriate id into my rest api function,
I try this:
class _HomeScreenState extends State<HomeScreen> {
BuildContext context;
ApiService apiService;
SharedPreferences sharedPreferences;
@override
void initState() {
super.initState();
apiService = ApiService();
}
checkStorageStatus() async {
sharedPreferences = await SharedPreferences.getInstance();
}
@override
Widget build(BuildContext context) {
this.context = context;
return SafeArea(
child: FutureBuilder(
future: apiService.getProfiles(), //I DON'T KNOW HOW TO PUT ID INTO THI FUNCTION
builder: (BuildContext context, AsyncSnapshot<List<Profile>> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
"Something wrong with message: ${snapshot.error.toString()}"),
);
} else if (snapshot.connectionState == ConnectionState.done) {
User user = snapshot.data;
return _buildListView(user);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
but i can't put my ID into apiService.getProfiles()
function,
can anybody help me?
thanks for any help :)
Upvotes: 1
Views: 7247
Reputation: 1219
class _HomeScreenState extends State<HomeScreen> {
BuildContext context;
ApiService apiService;
SharedPreferences sharedPreferences;
@override
void initState() {
super.initState();
apiService = ApiService();
fetchUser();
}
Future<List<Profile>> fetchUser() async {
sharedPreferences = await SharedPreferences.getInstance();
int id = sharedPreferences.getInt("id");
final response = await client.get('$baseUrl/user/$id');
if(response.statusCode == 200){
return userFromJson(response.body);
}else return null;
}
@override
Widget build(BuildContext context) {
this.context = context;
return SafeArea(
child: FutureBuilder(
future: fetchUser(),
builder: (BuildContext context, AsyncSnapshot<List<Profile>> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
"Something wrong with message: ${snapshot.error.toString()}"),
);
} else if (snapshot.connectionState == ConnectionState.done) {
User user = snapshot.data;
return _buildListView(user);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
Upvotes: 1
Reputation: 7660
In your apiService.getProfiles()
you get the id from SharedPreferences before performing your API request
getProfiles(){
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
int id = sharedPreferences.getInt("id");
// perform http request to get UserProfile
}
Upvotes: 1