0

I am developing a Stock app in which I have to display News related to the stocks. I made a News class for the same as well as a factory constructor to convert the data from json

class News {
  final String title;
  final String desc;
  final String imgURL;
  final String url;

  News(
      {required this.title,
      required this.desc,
      required this.imgURL,
      required this.url});

  factory News.fromJSON(Map<String, dynamic> json) {
    final title = json["title"] as String;
    final desc = json["description"] as String;
    final imgUrl = json["image_url"] as String;
    final url = json["url"] as String;
    return News(title: title, desc: desc, imgURL: imgUrl, url: url);
  }
}

I have made a method to fetch the data from the API:

Future getNews() async {
    final response = await http.get(Uri.parse(
        'https://api.stockdata.org/v1/news/all?&filter_entities=true&language=en&api_token=${api_token}&countries=${country}'));
    if (response.statusCode == 200) {
      final jsonResponse = json.decode(response.body);
      return jsonResponse.map((data) => News.fromJSON(data));
    } else {
      throw Exception('Unexpected error occurred!');
    }
  }

I am having trouble understanding how I can display the data in my app. I tried using FutureBuilder but I can't seem to understand how it's working. Any help would be appreciated!

3
  • If you get data from API refer my answer here or here or here hope it's helpful to you Commented Oct 26, 2021 at 4:39
  • @abhi hope you are new to here. please do some research before posting your question. posting question without much research may cause down vote to your question. refer this flutter.dev/docs/cookbook/networking/fetch-data Commented Oct 26, 2021 at 4:41
  • Thanks a lot man Commented Oct 26, 2021 at 5:11

1 Answer 1

1

For the FutureBuilder you can do it this way :

      FutureBuilder(
        future: getNews(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if(snapshot.hasData){
            // Save your data in a variable
            List<News> news = snapshot.data;
            // Create a listview to show all of the news
            return newsListView(news); //This is a list
          } else {
            return Center(
              child: Container(
                width: 300,
                height: 290,
                child: Center(child: Text("Error"))
              )
            );
          }
        }
      ),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.