Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我正在尝试从newsapi.org获取数据,但出现问题_Api_Http_Flutter - Fatal编程技术网

我正在尝试从newsapi.org获取数据,但出现问题

我正在尝试从newsapi.org获取数据,但出现问题,api,http,flutter,Api,Http,Flutter,这是我的密码 错误:NoSuchMethodError:类“Future”没有实例获取程序“length” void main() => runApp(MyApp()); class MyApp extends StatefulWidget { MyApp({Key key}) : super(key : key ) ; @override _MyAppState createState() => _MyAppState(); } class _MyAppStat

这是我的密码

错误:NoSuchMethodError:类“Future”没有实例获取程序“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']);
          })
      ),
      
    );
  }
}
void main()=>runApp(MyApp());
类MyApp扩展了StatefulWidget{
MyApp({Key}):超级(Key:Key);
@凌驾
_MyAppState createState()=>\u MyAppState();
}
类MyAppState扩展了状态{
字符串urlToImage;
//未来新闻列表;
var新闻列表;
@凌驾
void initState(){
super.initState();
newslist=fetchArticle();
}
@凌驾
小部件构建(构建上下文){
返回材料PP(
debugShowCheckedModeBanner:false,
标题:“Api调用”,
家:脚手架(
appBar:appBar(标题:文本('Api调用'),),
正文:ListView.builder(
收缩膜:对,
itemCount:newslist.length,
itemBuilder:(上下文,索引){
返回Image.network(新闻列表[索引]['urlToImage']);
})
),
);
}
}
类文章{
最终字符串作者;
最后的字符串标题;
最终字符串描述;
最终字符串发布日期;
最终字符串urlToImage;
最终字符串url;
文章({this.author,this.description,this.title,this.publishedAt,this.urlToImage,this.url});
factory Article.fromJson(映射json){
退货(
作者:json['author'],
标题:json['title'],
description:json['description'],
publishedAt:json['publishedAt'],
url:json['url'],
urlToImage:json['urlToImage']
);
}
}
Future fetchArticle()异步{
变量url=
'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=2e8e3846c42a4f64a6b1d98370bdeeea';
最终响应=等待http.get(url);
如果(response.statusCode==200){
return Article.fromJson(json.decode(response.body));
}否则{
抛出异常(“加载项目失败”);
}
}
lutter:生成MyApp时抛出以下NoSuchMethodError(脏,状态:_MyAppState#c93f4): 颤振:类“Future”没有实例getter“length”。 颤振:接收器:“未来”的实例 颤振:尝试呼叫:长度 颤振: 颤振:导致错误的相关小部件是:

颤振:抛出异常时,这是堆栈: 颤振:#0 Object.noSuchMethod(省道:核心补片/对象补片。省道:53:5) flatter:#1 MyAppState.build(包:api/main.dart:35:35) flatter:#2 StatefulElement.build(包:flatter/src/widgets/framework.dart:4619:28) flatter:#3 ComponentElement.performRebuild(包:flatter/src/widgets/framework.dart:4502:15) flatter:#4 StatefulElement.performRebuild(包:flatter/src/widgets/framework.dart:4675:11) flatter:#5 Element.rebuild(包:flatter/src/widgets/framework.dart:4218:5) flatter:#6 ComponentElement._firstBuild(包:flatter/src/widgets/framework.dart:4481:5) flatter:#7 StatefulElement._firstBuild(包:flatter/src/widgets/framework.dart:4666:11) flatter:#8 ComponentElement.mount(包:flatter/src/widgets/framework.dart:4476:5) flatter:#9 Element.inflateWidget(包:flatter/src/widgets/framework.dart:3446:14) flatter:#10 Element.updateChild(包:flatter/src/widgets/framework.dart:3214:18) flatter:#11 RenderObjectToWidgetElement._重建(包:flatter/src/widgets/binding.dart:1148:16) flatter:#12 RenderObjectToWidgetElement.mount(包:flatter/src/widgets/binding.dart:1119:5) 颤振:#13 RenderObjectToWidgetAdapter.attachToRenderTree。(软件包:flatter/src/widgets/binding.dart:1061:17) flatter:#14 BuildOwner.buildScope(包:flatter/src/widgets/framework.dart:2607:19) flatter:#15 RenderObjectToWidgetAdapter.attachToRenderTree(包:flatter/src/widgets/binding.dart:1060:13) flatter:#16 WidgetsBinding.attachRootWidget(包:flatter/src/widgets/binding.dart:941:7) 颤振:#17 widgetsbind.scheduleAttachRootWidget。(包:flatter/src/widgets/binding.dart:922:7) 颤振:(从类RawReceivePortImpl、类计时器、dart:async和dart:async补丁中删除了11帧) 颤振:
颤振:

您可以复制下面的粘贴运行完整代码
步骤1:您可以使用bool
\u isLoading
来控制加载状态
步骤2:
fetchArticle()
return
Future Payload.fromJson(json.decode(str));
字符串payloadToJson(有效负载数据)=>json.encode(data.toJson());
类有效载荷{
有效载荷({
这个,身份,,
这个结果,,
这篇文章,
});
字符串状态;
综合结果;
列出文章;
工厂负载.fromJson(映射json)=>负载(
状态:json[“状态”],
totalResults:json[“totalResults”],
文章:List.from(
json[“articles”].map((x)=>Article.fromJson(x)),
);
映射到JSON()=>{
“地位”:地位,
“totalResults”:totalResults,
“articles”:List.from(articles.map((x)=>x.toJson()),
};
}
班级文章{
文章({
这个消息来源,,
这位作者,
这个名字,
这个.说明,,
这个.url,
这个.urlToImage,
这个.dat,
这个.内容,,
});
来源;
字符串作者;
字符串标题;
字符串描述;
字符串url;
字符串urlToImage;
日期时间发布日期;
字符串内容;
factory Article.fromJson(映射json)=>Article(
source:source.fromJson(json[“source”]),
作者:json[“作者”],
标题:json[“标题”],
description:json[“description”],
url:json[“url”],
urlToImage:json[“urlToImage”],
publishedAt:DateTime.parse(json[“publishedAt”]),
content:json[“content”]==null?null:json[“content”],
);
映射到JSON()=>{
“source”:source.toJson(),
“作者”:作者,
“头衔”:头衔,
“描述”:描述,
“url”:url,
“urlToImage”:urlToImage,
“publishedAt”:publishedAt.toiso8601字符串(),
“内容”:内容==null?
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');
  }

}
void getData() async {
    newslist = await fetchArticle();
    setState(() {
      _isLoading = false;
    });
  }
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);
                  })),
    );
  }
}
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']);
  }
}