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!

Abhi
  • 31
  • 6
  • If you get data from API refer my answer [here](https://stackoverflow.com/a/68709502/13997210) or [here](https://stackoverflow.com/a/68533647/13997210) or [here](https://stackoverflow.com/a/68594656/13997210) hope it's helpful to you – Ravindra S. Patil Oct 26 '21 at 04: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 https://flutter.dev/docs/cookbook/networking/fetch-data – rosh-dev851 Oct 26 '21 at 04:41
  • Thanks a lot man – Abhi Oct 26 '21 at 05:11

1 Answers1

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"))
              )
            );
          }
        }
      ),
Ananda Pramono
  • 899
  • 1
  • 6
  • 18