【发布时间】:2020-08-03 23:39:55
【问题描述】:
我创建了一个函数,使用 rest api 到 get 用户数据并使用他的 ID。
我在 UI 中的代码:
SharedPreferences sharedPreferences;
UserApiService userApiService;
@override
void initState() {
super.initState();
getUserData();
userApiService = UserApiService();
}
Future<User> getUserData() async {
sharedPreferences = await SharedPreferences.getInstance();
int id = sharedPreferences.getInt('id');
return userApiService.getUser(id);
}
我在 api_service 中的代码:
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;
}
这是我的FutureBuilder:
@override
Widget build(BuildContext context){
return FutureBuilder(
future: getUserData(),
builder: (context, snapshot){
if(!snapshot.hasData){
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
iconTheme: IconThemeData(color: Colors.black),
title: Text('Profil', style: TextStyle(color: Colors.black, letterSpacing: 1),),
elevation: 0.0,
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.more_vert),
onPressed: () {
//
},
)
],
bottom: PreferredSize(child: Container(color: Colors.black, height: 0.1), preferredSize: Size.fromHeight(0.1),),
),
body: Center(
child: CircularProgressIndicator(),
),
);
}
User user = snapshot.data;
return Scaffold(
backgroundColor: Colors.white,
body: Container(
child: Text(user.firstName),
),
);
},
);
}
而且我有一个问题,每次我转到完成请求的页面时,都会重新加载函数并再次从服务器检索信息。
如何让这些数据只从我的rest api下载一次,然后流畅显示,而无需再次向数据库请求该数据。
我知道我必须使用状态管理,但我不知道该怎么做。
感谢您的任何回答:)
【问题讨论】:
-
您的意思是您希望未来在整个应用生命周期内触发一次?还是只在整个页面生命周期内触发?
-
整个应用 /////
-
所以下面的答案不能解决你的问题吧?
-
仍在重新加载我的页面
标签: rest api flutter dart state