我有一个页面,用户在点击提交后创建一个“帖子”(如 twitter/ig),该帖子通过帖子请求发送到后端,然后页面路由到“主页”,这基本上是一个带有持久底部导航栏的脚手架,它根据按下导航栏中的哪个图标(索引)创建主体。默认情况下,索引为 0(第一个图标),因此显示相应的主体,其中还显示用户通过向服务器执行获取请求而创建的新帖子。 但问题是它不会显示帖子,除非我点击热重载。同样,如果我通过点击其中一个图标导航到另一个页面并返回到第一页,帖子就会消失,直到我再次按下热重载。 如何确保每次创建正文/页面时都加载帖子?
显示帖子的页面代码:
class PostPage extends StatefulWidget {
@override
_PostPageState createState() => _PostPageState();
}
class _PostPageState extends State<PostPage> {
ApiClient _client = ApiClient();
String session;
int userID;
var refreshKey = GlobalKey<RefreshIndicatorState>();
Future GetInfo() async{
session = await getSession("session");
print("from get info "+ session);
userID = await getUserID("userID");
print("from get info "+ userID.toString());
}
@override
void initState() {
// TODO: implement initState
super.initState();
GetInfo();
print("called");
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text("Posts", style: Style.AppBarStyle),
bottom: TabBar(
tabs: [
Tab(
text: "Text1",
),
Tab(
text: "Text2",
),
],
),
),
body: TabBarView(
children: [
Posts(_client.getPostsOne(userID, session)),
Posts(_client.getPostsTwo(userID, session)),
],
),
),
);
}
}
future build 者帖子的代码:
Widget Posts(Future<List<Post>> future) {
return FutureBuilder<List<Post>>(
future: future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFF585B8D), Color(0xFF252642)])),
child: CustomScrollView(
scrollDirection: Axis.vertical,
shrinkWrap: false,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 24.0),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => PostCard(
snapshot.data[index], false, true, false),
childCount: snapshot.data.length,
),
),
)
],
));
}
if (snapshot.data == null) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xFF585B8D), Color(0xFF252642)])),
child: Container());
}
if (snapshot.connectionState != ConnectionState.done) {
return Center(
child: CircularProgressIndicator(),
);
}
});
}
编辑 似乎在从共享首选项加载用户 ID/ session key 之前发出了 GET 请求,添加 setState({}) 解决了这个问题,因为它导致小部件被重新绘制现在检索到用户 ID/ session key 。但是发出了两个 get 请求而不是一个,为了防止这种情况,我在调用之前检查 session 是否为空,否则我会显示一个空容器。
session !=null?Posts(_client.getPostsOne(userID, session)):Container()
最佳答案
获取数据后忘记调用setState
(重建小部件):
Future GetInfo() async{
session = await getSession("session");
print("from get info "+ session);
userID = await getUserID("userID");
print("from get info "+ userID.toString());
setState(() {
});
}
关于dart - 创建页面时未调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53858272/