简体   繁体   English

如何解析 flutter 中的 json?

[英]How to parse json in flutter?

I want to create a news app and I've used newsapi.org as a source.我想创建一个新闻应用程序,我使用 newsapi.org 作为来源。

I am trying to fetch the JSON data coming by the Http library.我正在尝试获取来自 Http 库的 JSON 数据。

I've provided the entire code below.我在下面提供了整个代码。

It doesn't give me any error but no data loaded and when I print the data it prints everything okay but I can't display it.它没有给我任何错误,但没有加载数据,当我打印数据时,它打印一切正常,但我无法显示它。

I don't what is the problem but all my project has stopped on this problem.我不知道是什么问题,但我所有的项目都停止了这个问题。

I am looking for a solution for this code because it doesn't work.我正在寻找此代码的解决方案,因为它不起作用。

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:newly/services/networking.dart';
import 'package:newly/widgets/article.dart';

class NewsScreen extends StatefulWidget {
  @override
  _NewsScreenState createState() => _NewsScreenState();
}

class _NewsScreenState extends State<NewsScreen> {

  List<Article> articles = [];

  NetworkHelper networkHelper = NetworkHelper(
    url:
        'https://newsapi.org/v2/everything?q=bitcoin&apiKey=392495172bab4b3885ae93760df54b91',
  );

  Future<List<Widget>> getNews() async {
    var newsData = await networkHelper.getData();

    for (int i = 0; i < await newsData['articles'].length; i++) {
      var title = await newsData['articles'][i]['title'];
      var urlToImage = await newsData['articles'][i]['urlToImage'];
      var content = await newsData['articles'][i]['content'];
      var author = await newsData['articles'][i]['author'];
      var url = await newsData['articles'][i]['url'];

      print(title);
      print(urlToImage);
      print(url);
      print(content);
      print(author);
      print('123456789123456789123456789123456789');

      articles.add(
        Article(
          author: author,
          content: content,
          title: title,
          url: url,
          urlToImage: urlToImage,
        ),
      );

      print(articles[0].author);

    }

    return articles;
  }

  Future<List<Article>> showArticles() async {
    var data = await get(
      'https://newsapi.org/v2/everything?q=bitcoin&apiKey=392495172bab4b3885ae93760df54b91',
    );

    var dataDecoded = await json.decode(data.body);

    List<Article> articles = [];

    await dataDecoded.forEach(
      (article) {
        articles.add(
          Article(
            author: article['author'],
            content: article['content'],
            title: article['title'],
            url: article['url'],
            urlToImage: article['urlToImage'],
          ),
        );
      },
    );

    return articles;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        centerTitle: true,
        title: Text(
          'Newly',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      body: FutureBuilder(
        future: getNews(),
        builder: (context, snapshot) {
          return ListView(
            children: articles,
          );
        },
      ),

    );
  }
}

Network Helper:网络助手:

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

class NetworkHelper {
  NetworkHelper({this.url});

  final String url;

  Future getData() async {
    http.Response response = await http.get(url);

    if (response.statusCode == 200) {
      String data = response.body;

      return json.decode(data);
    } else {
      print('something wrong');
      print(response.statusCode);
    }
  }
}

While working with json data在使用json 数据

The good practice is to create a model for that and then just fetch the data through the api好的做法是为此创建一个 model ,然后通过 api 获取数据

creating a model and a class is easy enough and doesn't take effort and makes your work easy;)创建一个 model 和一个 class 很容易,不费力,让您的工作轻松;)

For creating a model for your project为您的项目创建 model

VISIT https://javiercbk.github.io/json_to_dart/访问https://javiercbk.github.io/json_to_dart/

just copy your json data and paste in the textField and you will get your Model Class ready with just one click只需copy your json datapaste in the textField文本字段中,您将获得 Model Class 只需单击一下即可

for accessing the data用于访问数据

Test _test = Test.fromJson(response.body);

that's it.而已。

refer image shown below参考下图

在此处输入图像描述

Try to setState before adding the articles to the array在将文章添加到数组之前尝试 setState

The problem is in showing the articles.问题在于显示文章。 and yaa also as @ISpam Ossama says, you have to use setState for adding the data to list like this.而且正如@ISpam Ossama 所说,您必须使用 setState 将数据添加到这样的列表中。

void getNews() async {
var newsData = await networkHelper.getData();

for (int i = 0; i < newsData['articles'].length; i++) {
  var title = newsData['articles'][i]['title'];
  var urlToImage = newsData['articles'][i]['urlToImage'];
  var content = newsData['articles'][i]['content'];
  var author = newsData['articles'][i]['author'];
  var url = newsData['articles'][i]['url'];

  print(title);
  print(urlToImage);
  print(url);
  print(content);
  print(author);
  print('123456789123456789123456789123456789');
  setState(() {
   articles.add(
    Article(
      author: author,
      content: content,
      title: title,
      url: url,
      urlToImage: urlToImage,
    ),
  );
  });
  print(articles[0].author);
}
}

Now, you have to display the articles like this.现在,您必须像这样显示文章。

ListView.builder(
          itemCount: articles.length,
          itemBuilder: (BuildContext ctxt, int index) {
            return Text(articles[index].title);
          },
        )

Hope it will help you!希望对您有所帮助!

You can also do it using FutureBuilder , If you want otherwise as @Mustafa answer will work.您也可以使用FutureBuilder来完成,如果您愿意,@Mustafa 的答案将起作用。

Future<List<Article>> showArticles() async {
var data = await networkHelper.getData();

List<Article> articlesArr = [];

await data['articles'].forEach(
  (article) {
    articlesArr.add(
      Article(
        author: article['author'],
        content: article['content'],
        title: article['title'],
        url: article['url'],
        urlToImage: article['urlToImage'],
      ),
    );
  },
);
return articlesArr;
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        centerTitle: true,
        title: Text(
          'Newly',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      body: FutureBuilder<List<Article>>(
        future: showArticles(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView(
              children: snapshot.data.map((article) {
                return Container(
                  padding: EdgeInsets.all(8.0),
                  child: Text(article.author),
                );
              }).toList(),
            );
          } else {
            return Container(
              color: Colors.blue,
            );
          }
        },
      ),
    );
  }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM