如何设置国家HTTP URL?

时间:2019-11-05 14:42:25

标签: json http parsing flutter dart

我想创建一个新闻应用,并且我也使用了newsapi.org,但是

问题实际上是我想在自己的

中添加类似搜索功能的功能

app,我的想法很简单。

我已经在AppBar中创建了一个TextField,我的想法是从中获取输入

user和setState以及新的用户输入网址。

我的代码:

import 'package:flutter/material.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 = [];

  String topic = 'google';

  var newsData;

  Future getNews(String topic) async {
    NetworkHelper networkHelper = NetworkHelper(
      url:
          'https://newsapi.org/v2/everything?q=$topic&from=2019-11-04&to=2019-11-04&sortBy=popularity&apiKey=392495172bab4b3885ae93760df54b91',
    );

    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'];
      setState(() {
        articles.add(
          Article(
            author: author,
            content: content,
            title: title,
            url: url,
            urlToImage: urlToImage,
          ),
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        centerTitle: true,
        title: TextField(
          textInputAction: TextInputAction.search,
          onChanged: (String text) async {
            setState(() {
              topic = text;
            });
            await getNews(topic);
            print(topic);
          },
          onSubmitted: (String text) async {
            setState(() {
              topic = text;
            });
            print(topic);
            await getNews(topic);
          },
          decoration: InputDecoration(
            suffixIcon: IconButton(
              onPressed: () async {
                await getNews(topic);
                print(topic);
              },
              icon: Icon(
                Icons.search,
              ),
            ),
            hintText: 'Search',
            filled: true,
            fillColor: Colors.white,
          ),
        ),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(15.0),
          child: FutureBuilder(
            future: getNews(topic),
            builder: (context, snapshot) {
              return ListView.builder(
                itemCount: newsData['articles'] == null
                    ? 0
                    : newsData['articles'].length,
                itemBuilder: (BuildContext ctxt, int index) {
                  return Article(
                    author: articles[index].author,
                    content: articles[index].content,
                    title: articles[index].title,
                    url: articles[index].url,
                    urlToImage: articles[index].urlToImage,
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

网络助手:

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);
    }
  }
}

0 个答案:

没有答案