代码之家  ›  专栏  ›  技术社区  ›  Al C

为什么不在initState上加载异步数据?

  •  -1
  • Al C  · 技术社区  · 4 年前

    在查看了包括在内的资源后 this SO post ,我仍然不确定为什么我的数据没有加载到initState上:

    class _MyAppState extends State<MyApp> {
      List<NewsItem> itemList = [];
    
      void _getNews() async {
        final news = await http.get(Uri.parse(
            'https://newsapi.org/...'));
        if (news.statusCode == 200) {
          itemList.clear();
          var articles = jsonDecode(news.body)['articles'];
    
          for (int i = 0; i < articles.length; i++) {
            var newsItem = articles[i];
            var item = NewsItem.fromJson(newsItem);
            itemList.add(item);
          }
        } else {
          throw Exception('Failed to retrieve news.');
        }
      }
    
      Future<void> _getData() async {
        setState(() {
          _getNews();
        });
      }
    
      @override
      void initState() {
        super.initState();
        _getNews();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'NewsAPI.org Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            appBar: AppBar(title: const Text("News App")),
            body: RefreshIndicator(
              onRefresh: _getData,
              child: ListView.builder(
                itemCount: itemList.length,
                itemBuilder: (context, i) {
                  return GestureDetector(
                    onTap: () {
                      if (itemList[i].url != null) {
                        var _url = itemList[i].url!;
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => DisplayWebPage(_url)),
                        );
                      }
                    },
                    child: Card(
                      elevation: 10,
                      shadowColor: Colors.black,
                      child: Padding(
                        padding: const EdgeInsets.all(10),
                        child: Column(
                          children: [
                            Image.network(itemList[i].urlToImage ?? ''),
                            Text(itemList[i].title ?? '',
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 14)),
                            Text(itemList[i].description ?? ''),
                            const Divider(
                              color: Colors.black,
                              height: 25,
                              thickness: 2,
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ),
        );
      }
    }
    

    加载应用程序时,屏幕为空白。如果我拉动以刷新,即调用 _getData() ,然后加载预期的web数据。我没想过打电话 setState() 初始化期间会很重要,但我尝试调用 _getNews() 在启动时也是如此。(没关系。)

    应该使用什么代码才能在应用程序启动时加载web数据?

    0 回复  |  直到 4 年前