简体   繁体   English

我正在尝试从 newsapi.org 获取数据但遇到问题

[英]I am trying to fetch data from newsapi.org but having issue

here's my code这是我的代码

Error: NoSuchMethodError: Class 'Future' has no instance getter 'length'错误:NoSuchMethodError:Class 'Future' 没有实例 getter 'length'

void main() => runApp(MyApp());


class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key : key ) ;

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String urlToImage;
  // Future<Article> newslist;
  var newslist;

  @override
  void initState() {
    super.initState();
    newslist = fetchArticle();
  }

  @override
  Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Api calls',
          home: Scaffold(
            appBar: AppBar(title: Text('Api Calls'),),
            body: ListView.builder(
              shrinkWrap: true,
              itemCount: newslist.length,
          itemBuilder: (context, index) {
            return Image.network(newslist[index]['urlToImage']);
          })
      ),
      
    );
  }
}
class Article {
  final String author;
  final String title;
  final String description;
  final String publishedAt;
  final String urlToImage;
  final String url;

  Article({this.author, this.description, this.title, this.publishedAt, this.urlToImage, this.url});


  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
      author : json['author'],
      title: json['title'],
      description: json['description'],
      publishedAt: json['publishedAt'],
      url: json['url'],
      urlToImage: json['urlToImage']
    );
  
    
  }
  
}

  Future<Article> fetchArticle() async {

  var url = 
  'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';
  
  final response = await http.get(url);

  if (response.statusCode == 200) {
    return Article.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load Article');
  }

}

lutter: The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#c93f4): flutter: Class 'Future' has no instance getter 'length'. lutter:在构建 MyApp(dirty, state: _MyAppState#c93f4): flutter: Class 'Future' 没有实例时抛出了以下 NoSuchMethodError。 flutter: Receiver: Instance of 'Future' flutter: Tried calling: length flutter: flutter: The relevant error-causing widget was: flutter:接收器:“未来”实例 flutter:尝试调用:长度 flutter:flutter:相关错误是:-ca

flutter: When the exception was thrown, this was the stack: flutter: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5) flutter: #1 _MyAppState.build (package:api/main.dart:35:35) flutter: #2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28) flutter: #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15) flutter: #4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11) flutter: #5 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5) flutter: #6 ComponentEl flutter: When the exception was thrown, this was the stack: flutter: #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5) flutter: #1 _MyAppState.build (package:api/main.dart :35:35) flutter: #2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28) flutter: #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502 :15) flutter: #4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11) flutter: #5 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5 ) flutter:#6 ComponentEl ement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5) flutter: #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11) flutter: #8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5) flutter: #9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14) flutter: #10 Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18) flutter: #11 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1148:16) flutter: #12 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1119:5) Z5ACEBC ement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5) flutter: #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11) flutter: #8 ComponentElement. mount (package:flutter/src/widgets/framework.dart:4476:5) flutter: #9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14) flutter: #10 Element.updateChild ( package:flutter/src/widgets/framework.dart:3214:18) flutter: #11 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1148:16) flutter: #12 RenderObjectToWidgetElement.mount (package:颤振/src/widgets/binding.dart:1119:5) Z5ACEBC 4CB70DDBB074B0AC76AAB176AEZ: #13 RenderObjectToWidgetAdapter.attachToRenderTree. 4CB70DDBB074B0AC76AAB176AEZ:#13 RenderObjectToWidgetAdapter.attachToRenderTree。 (package:flutter/src/widgets/binding.dart:1061:17) flutter: #14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19) flutter: #15 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1060:13) flutter: #16 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:941:7) flutter: #17 WidgetsBinding.scheduleAttachRootWidget. (package:flutter/src/widgets/binding.dart:1061:17) flutter: #14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19) flutter: #15 RenderObjectToWidgetAdapter.attachToRenderTree (package :flutter/src/widgets/binding.dart:1060:13) flutter: #16 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:941:7) flutter: #17 WidgetsBinding.scheduleAttachRootWidget. (package:flutter/src/widgets/binding.dart:922:7) flutter: (elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch) flutter: flutter: (package:flutter/src/widgets/binding.dart:922:7) flutter: (elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch) flutter: flutter:

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
Step 1: You can use bool _isLoading to control loading status第 1 步:您可以使用 bool _isLoading来控制加载状态
Step 2: fetchArticle() return Future<List<Article>> not Future<Article>第 2 步: fetchArticle()返回Future<List<Article>>而不是Future<Article>
Step 3: Use payloadFromJson(response.body) , you can see Payload class definition in full code第三步:使用payloadFromJson(response.body) ,可以看到Payload class的完整代码定义
Step 4: When data is ready set _isLoading to false第 4 步:当数据准备好时,将_isLoading设置为false

void getData() async {
    newslist = await fetchArticle();
    setState(() {
      _isLoading = false;
    });
  }

working demo工作演示

在此处输入图像描述

full code完整代码

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.status,
    this.totalResults,
    this.articles,
  });

  String status;
  int totalResults;
  List<Article> articles;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        status: json["status"],
        totalResults: json["totalResults"],
        articles: List<Article>.from(
            json["articles"].map((x) => Article.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "totalResults": totalResults,
        "articles": List<dynamic>.from(articles.map((x) => x.toJson())),
      };
}

class Article {
  Article({
    this.source,
    this.author,
    this.title,
    this.description,
    this.url,
    this.urlToImage,
    this.publishedAt,
    this.content,
  });

  Source source;
  String author;
  String title;
  String description;
  String url;
  String urlToImage;
  DateTime publishedAt;
  String content;

  factory Article.fromJson(Map<String, dynamic> json) => Article(
        source: Source.fromJson(json["source"]),
        author: json["author"],
        title: json["title"],
        description: json["description"],
        url: json["url"],
        urlToImage: json["urlToImage"],
        publishedAt: DateTime.parse(json["publishedAt"]),
        content: json["content"] == null ? null : json["content"],
      );

  Map<String, dynamic> toJson() => {
        "source": source.toJson(),
        "author": author,
        "title": title,
        "description": description,
        "url": url,
        "urlToImage": urlToImage,
        "publishedAt": publishedAt.toIso8601String(),
        "content": content == null ? null : content,
      };
}

class Source {
  Source({
    this.id,
    this.name,
  });

  String id;
  String name;

  factory Source.fromJson(Map<String, dynamic> json) => Source(
        id: json["id"] == null ? null : json["id"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id == null ? null : id,
        "name": name,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String urlToImage;
  // Future<Article> newslist;
  List<Article> newslist;
  bool _isLoading = true;

  Future<List<Article>> fetchArticle() async {
    var url =
        'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';

    final response = await http.get(url);

    if (response.statusCode == 200) {
      Payload payload = payloadFromJson(response.body);

      return payload.articles;
    } else {
      throw Exception('Failed to load Article');
    }
  }

  void getData() async {
    newslist = await fetchArticle();
    setState(() {
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Api calls',
      home: Scaffold(
          appBar: AppBar(
            title: Text('Api Calls'),
          ),
          body: _isLoading
              ? Center(child: CircularProgressIndicator())
              : ListView.builder(
                  shrinkWrap: true,
                  itemCount: newslist.length,
                  itemBuilder: (context, index) {
                    return Image.network(newslist[index].urlToImage);
                  })),
    );
  }
}

Already done by other people.已经被其他人完成了。 But I tried and upload code.但我尝试上传代码。

there is some problem.有一些问题。

  • fetchAricle method gets a one article only. fetchAricle 方法只获取一篇文章。

So I changed to get articles from url.所以我改为从 url 获取文章。 And using 'FutureBuilder' just build a list view with articles.使用“FutureBuilder”只需构建一个包含文章的列表视图。

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String urlToImage;
  Future<List<Article>> newslist;

  Future<List<Article>> fetchArticle() async {
    var url =
        'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';

    final response = await http.get(url);

    if (response.statusCode == 200) {
      var data = json.decode(response.body);
      List<Article> listArticle = data["articles"].map<Article>((article) {
        return Article.fromJson(article);
      }).toList();
      return listArticle;
    } else {
      throw Exception('Failed to load Article');
    }
  }

  @override
  void initState() {
    super.initState();
    newslist = fetchArticle();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Api calls',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Api Calls'),
        ),
        body: FutureBuilder<List<Article>>(
          future: newslist,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              // return Container();
              return ListView.builder(
                shrinkWrap: true,
                itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
                  return Image.network(snapshot.data[index].urlToImage);
                },
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
            return Container();
          },
        ),
      ),
    );
  }

  Widget _buildBody() {
    return Container();
  }
}

class Article {
  final String author;
  final String title;
  final String description;
  final String publishedAt;
  final String urlToImage;
  final String url;

  Article(
      {this.author,
      this.description,
      this.title,
      this.publishedAt,
      this.urlToImage,
      this.url});

  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
        author: json['author'],
        title: json['title'],
        description: json['description'],
        publishedAt: json['publishedAt'],
        url: json['url'],
        urlToImage: json['urlToImage']);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试从 newsapi.org 获取数据,但最终出现 403 错误、未找到 paramType 2048 等 - trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc 从 NewsApi (react, axios) 获取数据 - Fetch data from NewsApi (react, axios) 我们如何创建自己的新闻 JSON API 就像 newsapi.org 网站上提供的那样? - How can we create our own news JSON API like provided on the newsapi.org website? 我正在尝试从 API 获取数据但出现错误 - I am trying to get data from API but having error 我正在尝试使用 getx 获取 slider 图像但出现错误 - i am trying to fetch slider image using getx but having error 当我尝试通过表单中输入的数据来编辑API URL并从API提取数据时,代码不起作用 - Code is not working when i am trying to edit the API URL by data entered in form and fetch data from API 我正在尝试从 api 获取数据并将其显示在 DropDownButton 中。 问题是快照返回 null - I am trying to fetch data from the api and display it in a DropDownButton. problem is that snapshot is returning null 我正在尝试通过反应从 Api 获取数据,一个 api 取决于第二个的“id”, - I am trying to fetch data from Api with react, one api depends on "id" the second's one, 我正在尝试从 Companies House API 获取 pdf 文档 - I am trying to fetch a pdf document from Companies House API 我无法从此 API 获取数据。 这是代码 - I am unable to fetch data from this API. Here is the code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM