我使用rest api创建一个函数来获取一个用户数据:
码:
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;
}
我必须从当前登录到该系统的用户那里获取数据,因此我需要使用
id
从响应中获取他的sharedPreferences
:sharedPreferences.setInt("id", jsonResponse['id']);
但是我不知道如何创建一个
FutureBuilder
会将适当的ID插入我的rest api函数中,我尝试这样:
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(),
);
}
},
),
);
}
但是我无法将我的ID放入
apiService.getProfiles()
函数中,有谁能够帮助我?
谢谢你的帮助 :)
最佳答案
在您的apiService.getProfiles()
中,在执行API请求之前,您将从SharedPreferences获取ID。
getProfiles(){
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
int id = sharedPreferences.getInt("id");
// perform http request to get UserProfile
}
关于rest - 在Flutter中使用Rest API获取用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61330962/