【问题标题】:My Content from API is not being shown in Flutter我的 API 内容未在 Flutter 中显示
【发布时间】:2021-02-18 12:07:05
【问题描述】:

我用 Flutter 编写代码,并使用 NewsAPI.org 获取有关新闻的内容,例如标题、图像、内容等。我创建了一个“新闻”类和 ArticleModel() 用于检索和使用信息。我使用条件运算符 (? :) 检查是否收到数据,然后显示它,否则显示 CircularProgressIndiactor()。运行应用程序后,CircularProgressIndiactor() 出现,并且没有显示/加载任何信息。有人可以帮我吗??

不显示错误或警告,代码编译成功,但不显示任何信息。

这里是主文件 home.dart -

import 'package:flutter/material.dart';
import 'package:news_app/helper/data.dart';
import 'package:news_app/helper/news.dart';
import 'package:news_app/models/article_model.dart';
import 'package:news_app/models/category_models.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<CategoryModel> categories = new List<CategoryModel>();
  List<ArticleModel> articles = new List<ArticleModel>();
  bool loading = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    categories = getCategories();
    getNews();
  }

  getNews() async {
    News newsClass = News();
    await newsClass.getNews();
    articles = newsClass.news;
    setState(() {
      loading = false;
      print('Done');
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Flutter',
                style: TextStyle(
                  color: Colors.black,
                ),
              ),
              Text(
                'News',
                style: TextStyle(
                  color: Colors.blue,
                ),
              ),
            ],
          ),
          //elevation: 2.0,
        ),
        body: loading
            ? Center(
                child: Container(
                  child: CircularProgressIndicator(),
                ),
              )
            : SingleChildScrollView(
                child: Container(
                  child: Column(
                    children: <Widget>[
                      ///Categories
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 16.0),
                        height: 70.0,
                        child: ListView.builder(
                          itemCount: categories.length,
                          scrollDirection: Axis.horizontal,
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            return CategoryTile(
                              imageUrl: categories[index].imageUrl,
                              categoryName: categories[index].categoryName,
                            );
                          },
                        ),
                      ),

                      ///Blogs
                      Container(
                        child: ListView.builder(
                          shrinkWrap: true,
                          itemCount: articles.length,
                          itemBuilder: (context, index) {
                            return BlogTile(
                              imageUrl: articles[index].urlToImage,
                              title: articles[index].title,
                              desc: articles[index].description,
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }
}

class CategoryTile extends StatelessWidget {
  final imageUrl, categoryName;
  CategoryTile({this.imageUrl, this.categoryName});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {},
      child: Container(
        margin: EdgeInsets.only(right: 16.0),
        child: Stack(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(6.0),
              child: Image.network(
                imageUrl,
                width: 120.0,
                height: 160.0,
                fit: BoxFit.cover,
              ),
            ),
            Container(
              alignment: Alignment.center,
              width: 120.0,
              height: 60.0,
              decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.circular(6.0)),
              child: Text(
                categoryName,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 14.0,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class BlogTile extends StatelessWidget {
  final String imageUrl, title, desc;
  BlogTile(
      {@required this.imageUrl, @required this.desc, @required this.title});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Image.network(imageUrl),
          Text(title),
          Text(desc),
        ],
      ),
    );
  }
}

这是 News.dart 文件 -

import 'dart:convert';

import 'package:news_app/models/article_model.dart';
import 'package:http/http.dart' as http;

class News {
  List<ArticleModel> news = [];

  Future<void> getNews() async{
    String url="http://newsapi.org/v2/top-headlines?country=in&category=business&apiKey=xxxxxxxxxxxxxxxxxx";

    var response = await http.get(url);

    var jsonData = jsonDecode(response.body);

    if(jsonData["status"] == "ok") {
      jsonData["articles"].forEach((element){
        if(element['urlToImage'] != null && element['description'] != null) {
          ArticleModel articleModel = ArticleModel(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            url: element['url'],
            urlToImage: element['urlToImage'],
            content: element['content'],
          );
          news.add(articleModel);
        }
      });
    }
  }
}

最后是 ArticleModel.dart -

class ArticleModel {
  String author, title, description;
  String url, urlToImage;
  String content;

  ArticleModel({this.title, this.description, this.author, this.content, this.url, this.urlToImage});
}

【问题讨论】:

  • 我有一个使用GetX的NewsAPI项目,如果你有兴趣源代码是here
  • Ουιλιαμ Αρκευα 非常感谢

标签: api flutter dart


【解决方案1】:

将您的请求 URL 从 http 更新为 https 将会得到预期的结果。

更新网址为:"https://newsapi.org/v2/top-headlines?country=in&amp;category=business&amp;apiKey="

注意:出于安全原因,请勿在任何开放平台上共享您的 API 密钥。

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2021-11-02
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多