在 Flutter 中使用 api 和 http 请求

Using an api and http request in Flutter

    import 'dart:convert';
    import 'package:http/http.dart' as http;
    import 'package:newsapi_project/artical.dart';
    
    
    class News{ 
      List<ArticalModel> news =[];
      Future<void> getNews()async{
       String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=8efc3612216c44ccba7a8251dfbed587";
       var response=await http.get( url); //here its throwing the error//
       var jsonData= jsonDecode(response.body);
       if (jsonData["status"]=="ok"){
         jsonData["articles"].forEach(element){ //=> and even to in .forEach//
           if(element["urlToImagel"] != null && element["description"] != null ){
    
             ArticalModel articalmodel = ArticalModel(
               title:element["title"],
               author:element["author"],
               description:element["description"],
               url:element["url"],
              urlToImage:element["urlToImage"],
              content:element["content"]
             );
             news.add(articalmodel);
           }
         };
       }
      }
    
    }

 The argument type 'String' can't be assigned to the parameter type 'Uri'.dart

   var response=await http.get( url); // this is where I am getting error

  Function expressions can't be named Try removing the name, or moving the function expression to a function declaration statement.
 .forEach  this is where I am getting error

Expected an identifier.
.forEach  this is where I am getting error

我该如何解决这个问题?

试试下面的代码希望对你有帮助。 更改您的 API url 声明。

String url = 'https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=8efc3612216c44ccba7a8251dfbed587';

var response=await http.get(Uri.parse(url));

参考文档 here

试试这个!代码片段

 Future<void> getNews()async{
          String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=8efc3612216c44ccba7a8251dfbed587";
          var response=await http.get(Uri.parse(url)); //here its throwing the error//
          var jsonData= jsonDecode(response.body);
          if (**jsonData.statusCode==200**){
            jsonData["articles"].forEach(element){ //=> and even to in .forEach//
              if(element["urlToImagel"] != null && element["description"] != null ){
    
                ArticalModel articalmodel = ArticalModel(
                    title:element["title"],
                    author:element["author"],
                    description:element["description"],
                    url:element["url"],
                    urlToImage:element["urlToImage"],
                    content:element["content"]
                );
                news.add(articalmodel);
              }
            };
          }
        }

获取方法定义

Future<Response> get(
 Uri url,
  {Map<String, String>? headers}
  )

并且必须像这样解析 url

 String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=8efc3612216c44ccba7a8251dfbed587";

var response=await http.get( Uri.parse(url));