Getting 'Future<String?>' is not a subtype of type 'String' error why scraping data from a website in flutter app?

Viewed 66

[This image contains the part of code wherEin I am getting the data from the website https://arprogramming.blogspot.com/ and storing the data in 3 separate lists. The link list is used to store the link of the blog so that I can use it as a link afterwards to redirect to the site from the app]2

These are all my imports

Thia is my pubspec.yaml file

This is the part of code where I am using the scraped data

THIS IS MY ERROR Below is my main code

Future<void> _getDataFromWeb() async{
    var uri =Uri.parse('https://arprogramming.blogspot.com/');
    final response = await http.get(uri);
    dom.Document document = parser.parse(response.body);
    final elements =  document.getElementsByClassName('entry-title');
    final content =  document.getElementsByClassName('entry-content');
    final link1 =  document.getElementsByClassName('entry-header blog-entry-header');

    setState(() {
      title =  elements.map((elements)=> elements.getElementsByTagName("a")[0].innerHtml.toString()).toList();
      post =  content.map((content)=> content.getElementsByTagName("p")[0].innerHtml.toString()).toList();
      link =  link1.map((link1) async => link1.getElementsByTagName("a")[0].attributes['href']).cast<String>().toList();
    });

  }
1 Answers

You can not use the Future as string. Because these may not be available when you want to use. Use "then", it allows us to know when the async function ends and we have variable to use.

NOTE: Please be more careful further repositories. Community should upload their code as code snippet and error messages clearly. Welcome

http.get(uri).then((String response){
        dom.Document document = parser.parse(response.body);
        final elements =  document.getElementsByClassName('entry-title');
        final content =  document.getElementsByClassName('entry-content');
        final link1 =  document.getElementsByClassName('entry-header blog-entry-header');
    
        setState(() {
          title =  elements.map((elements)=> elements.getElementsByTagName("a")[0].innerHtml.toString()).toList();
          post =  content.map((content)=> content.getElementsByTagName("p")[0].innerHtml.toString()).toList();
          link =  link1.map((link1) async => link1.getElementsByTagName("a")[0].attributes['href']).cast<String>().toList();
        });
    });
Related