Jake
Jake

Reputation: 2056

Flutter - Error parsing HTML data

I've been trying to modify the code available here so that the title and dateAdded from VMoneyNews is visible in the apps listView.

Unfortunately, when I try to run the following edited code I get the error stated in the Image below.

http.Response response = await http.get('https://www.virtualmoneysnews.com/category/bitcoin-news/');

//parse and extract the data from the web site
dom.Document document = parser.parse(response.body);
document.getElementsByTagName('article').forEach((child) {
  jobsList.add(Job(
    title: child.getElementsByClassName('title').first.text,
    dateAdded: child.getElementsByClassName('thetime date updated').last.text,

  ));
});

method 'trim' called on null

Upvotes: 2

Views: 1854

Answers (1)

Richard Heap
Richard Heap

Reputation: 51750

You should probably remove this snippet, which relies on item.location, which you aren't populating.

            Text(
              item.location.trim(),
              style: TextStyle(
                  color: Colors.white, fontWeight: FontWeight.bold),
            ),

I'd refactor the Job class to rename it Article, Headline or Story i.e. something meaningful. For example:

class Story {
  String title;
  String dateAdded;

  Story(this.title, this.dateAdded);

  @override
  String toString() => '$title $dateAdded';
}

Your scraping code could then be written:

http.Response response = await http
    .get('https://www.virtualmoneysnews.com/category/bitcoin-news/');
dom.Document document = parser.parse(response.body);

List<Story> stories = document
    .getElementsByTagName('article')
    .map((e) => Story(
          e.getElementsByClassName('title').first.text,
          e.getElementsByClassName('thetime date updated').last.text,
        ))
    .toList();

Upvotes: 3

Related Questions