【问题标题】:Async function not being called on page creation创建页面时未调用异步函数
【发布时间】:2018-12-19 19:50:51
【问题描述】:

我有一个页面,用户在点击提交后发布“帖子”(如 twitter/ig),该帖子通过帖子请求发送到后端,然后页面路由到“主页”,这基本上是一个具有持久底部导航栏的脚手架,该导航栏根据按下导航栏中的图标(索引)创建主体。默认情况下,索引为 0(第一个图标),因此会显示相应的正文,其中还显示了用户通过对服务器执行 get 请求而新创建的帖子。 但问题是,除非我点击热重新加载,否则它不会显示帖子。 同样,如果我通过单击一个图标导航到不同的页面并返回第一页,帖子就会消失,直到我再次按下热重载。 如何确保每次创建正文/页面时都加载帖子?

显示帖子的页面的 Cody:

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)),

         ],
       ),
     ),
   );
 }
}

未来建设者的代码帖子:

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(),
          );
        }
      });
}

EDIT 似乎 GET 请求是在从共享首选项加载用户 ID/会话密钥之前发出的,添加 setState({}) 解决了这个问题,因为它导致小部件被重新绘制现在检索到用户 ID/会话密钥。但是发出了两个获取请求而不是一个,为了防止这种情况发生,我在调用之前检查了会话是否为空,否则我显示了一个空容器。

 session !=null?Posts(_client.getPostsOne(userID, session)):Container()

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    获取数据后忘记调用setState(重建小部件):

        Future GetInfo() async{
           session = await getSession("session");
           print("from get info "+ session);
           userID = await getUserID("userID");
           print("from get info "+ userID.toString());
           setState(() {
    
              });
    
         }
    

    【讨论】:

    • 这解决了我的问题!当我从不同的图标切换并返回时,在我的帖子出现之前似乎有短暂的延迟/滞后,无论如何我可以处理这个问题吗?
    • 这是一个异步调用,因此在您获得用户 ID 之前,您可以显示一个 CircleProgressIndicator。获得用户 ID 后,您将刷新小部件,并且应删除指示器
    猜你喜欢
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多