Home > database >  The method isn't defined for the class
The method isn't defined for the class

Time:07-02

I am trying to create an app using an api key provided by newsapi.org but whenever I try to run the project the following error comes:

    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.

The code for the page is following

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

The fetch_data code is

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

      });
    }
  }
}

I have tried running flutter clean and restarting vs code but the error still persists. The api key has been omitted.

CodePudding user response:

i think you have to add import the News class into your news_page.dart

CodePudding user response:

Probably it's the import issue. You can use the yellow suggestion light to import that class or you can do it manually at the top.

  • Related