繁体   English   中英

没有为 class 定义该方法

[英]The method isn't defined for the class

我正在尝试使用 newsapi.org 提供的 api 密钥创建一个应用程序,但是每当我尝试运行该项目时,都会出现以下错误:

    lib/pages/news_page.dart:17:5: Error: 'News' isn't a type.
    News news = News();
    ^^^^
lib/pages/news_page.dart:17:17: Error: The method 'News' isn't defined for the class '_NewsPageState'.
 - '_NewsPageState' is from 'package:cheapshorts/pages/news_page.dart' ('lib/pages/news_page.dart').
Try correcting the name to the name of an existing method, or defining a method named 'News'.
    News news = News();
                ^^^^
FAILURE: Build failed with an exception.

该页面的代码如下

import 'package:cheapshorts/models/fetch_data.dart';
import 'package:flutter/material.dart';

class NewsPage extends StatefulWidget {
  const NewsPage({Key? key, required this.category}) : super(key: key);
  final String category;
  @override
  State<NewsPage> createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {
  var newslist;
  bool _isLoading = true;
  void getNews() async {
    News news = News();
    await news.getNews(widget.category);
    newslist = news.news;
    setState(() {
      _isLoading = false;
    });
  }

  @override
  void initState() {
    _isLoading = true;
    super.initState();

    getNews();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading?const Center(child:LinearProgressIndicator()):PageView.builder(
          itemCount: newslist?.length,
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            return Column(
              children: [
                SizedBox(
                  height: 250,
                  width: MediaQuery.of(context).size.width,
                  child: FittedBox(
                      fit: BoxFit.fill,
                      child: Image.network(
                        newslist.urlToImage,
                        fit: BoxFit.fill,
                      )),
                ),
                Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: const EdgeInsets.all(20),
                      child: Text(
                        newslist.title,
                        style: const TextStyle(fontSize: 22),
                      ),
                    )),
                Padding(
                  padding: const EdgeInsets.only(left: 20, right: 20),
                  child: Text(
                    newslist.content,
                    style: Theme.of(context).textTheme.subtitle1,
                  ),
                )
              ],
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pop(context);
        },
        backgroundColor: Colors.yellow,
        child: const Icon(Icons.arrow_back),
      ),
    );
  }
}

fetch_data 代码是

import 'dart:convert';
import 'package:cheapshorts/models/get_articles.dart';
import 'package:http/http.dart' as http;

class News {

  List<Article> news  = [];

  Future<void> getNews(String category) async{
    String url = "https://newsapi.org/v2/top-headlines?country=in&category=$category&apiKey=$apiKey";
    Uri uri = Uri.parse(url);
    var response = await http.get(uri);

    var jsonData = jsonDecode(response.body);

    if(jsonData['status'] == "ok"){
      jsonData["articles"].forEach((element){

        if(element['urlToImage'] != null && element['description'] != null){
          Article article = Article(
            title: element['title'],
            author: element['author'],
            description: element['description'],
            urlToImage: element['urlToImage'],
            publshedAt: DateTime.parse(element['publishedAt']),
            content: element["content"],
            articleUrl: element["url"],
          );
          news.add(article);
        }

      });
    }
  }
}

我已经尝试运行 flutter clean 并重新启动 vs 代码,但错误仍然存​​在。 api 密钥已被省略。

我认为你必须将新闻 class 添加到你的 news_page.dart

应该是进口问题。 您可以使用黄色提示灯导入该 class 或者您可以在顶部手动执行。

暂无
暂无

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

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