首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我试图从newsapi.org中获取数据,但是有问题

我试图从newsapi.org中获取数据,但是有问题
EN

Stack Overflow用户
提问于 2020-07-20 03:17:45
回答 2查看 1.6K关注 0票数 1

这是我的密码

错误: NoSuchMethodError:类“未来”没有实例获取“长度”

代码语言:javascript
运行
复制
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']);
          })
      ),
      
    );
  }
}
代码语言:javascript
运行
复制
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']
    );
  
    
  }
  
}
代码语言:javascript
运行
复制
  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:抛出以下NoSuchMethodError构建MyApp(脏,状态:_MyAppState#c93f4):颤振:类“未来”没有实例获取“长度”。颤振:接收者:“未来”颤振的实例:尝试调用:长度颤振:颤振:相关的导致错误的小部件是:

颤栗:当异常被抛出时,这是堆栈:(package:flutter/src/widgets/framework.dart:4502:15):#0 Object.noSuchMethod (dart:core-Object.noSuchMethod/object_patch.dart:53:5)颤振:#1 _MyAppState.build (包:api/main.dart:35:35)颤振:#2 StatefulElement.build StatefulElement.build颤振:#3 ComponentElement.performRebuild ComponentElement.performRebuild颤振:#4 StatefulElement。(package:flutter/src/widgets/framework.dart:4675:11)颤振:#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)颤振:#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)颤振:#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)颤振:#8 ComponentElement.mount (包: performRebuild /src/widget/颤振:#9 (package:flutter/src/widgets/framework.dart:3446:14)颤振:#10 Element.updateChild颤振:#11 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1148:16)颤振:#12 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1119:5)颤振:#13 RenderObjectToWidgetAdapter.attachToRenderTree.(package:flutter/src/widgets/binding.dart:1061:17)颤振:#14 (package:flutter/src/widgets/framework.dart:2607:19)颤振:#15 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1060:13)颤振:#16 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:941:7)颤振:#17 WidgetsBinding.scheduleAttachRootWidget。(package:flutter/src/widgets/binding.dart:922:7)颤振:(从类_RawReceivePortImpl、类_Timer、dart:异步和dart:异步补丁中删除11帧)颤振:颤振:

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-20 04:13:38

您可以复制粘贴,运行下面的完整代码

步骤1:您可以使用bool _isLoading来控制加载状态。

步骤2:fetchArticle()返回Future<List<Article>>而不是Future<Article>

第3步:使用payloadFromJson(response.body),您可以看到完整代码中的Payload类定义

步骤4:当数据准备就绪时,将_isLoading设置为false

代码语言:javascript
运行
复制
void getData() async {
    newslist = await fetchArticle();
    setState(() {
      _isLoading = false;
    });
  }

工作演示

全码

代码语言:javascript
运行
复制
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);
                  })),
    );
  }
}
票数 2
EN

Stack Overflow用户

发布于 2020-07-20 04:16:38

已经被其他人做了。但我试着上传代码。

有一些问题。

  • fetchAricle方法只获得一篇文章.

所以我改了从url那里得到文章。使用'FutureBuilder‘只需构建一个带有文章的列表视图。

代码语言:javascript
运行
复制
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']);
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62988139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档