|
|
Log in / Subscribe / Register

Building a Flutter application (part 2)

By John Coggeshall
August 28, 2020

Our previous article explored the fundamentals of Flutter, a cross-platform open-source user-interface (UI) toolkit. We complete our introduction of Flutter by returning to the simple LWN RSS feed headline viewer that was introduced in part one. We will be adding several new features to that application in part two, including interactive elements to demonstrate some of the UI features of Flutter.

The LWNRssService class introduced in part one is responsible for fetching and processing the RSS feed from LWN using the http and dart_rss packages. This class was used in the former version of the application, implemented in such a way as to block the UI from starting until the feed was loaded. The result was an empty window in the interim, which is not an ideal user experience. There are several ways to solve that problem in Flutter, but here we incorporate the FutureBuilder widget into the LWNHeadlineScreen class (which provides the main interface). For reference purposes, below is the class we used for part one:

    class LWNHeadlineScreen extends StatelessWidget
    {
      final Rss1Feed feed;

      LWNHeadlineScreen(this.feed);

      @override
      Widget build(BuildContext context)
      {
        return Scaffold(
          appBar: AppBar(
            title: Text(feed.title)
          ),
          body: ListView.builder(
            itemCount: feed.items.length,
            itemBuilder: (BuildContext ctxt, int index) {
              final item = feed.items[index];
              return ListTile(
                title: Text(item.title),
                contentPadding: EdgeInsets.all(16.0),
              );
            }
          )
        );
      }
    }

The FutureBuilder widget is a wrapper widget for asynchronous data that "builds itself based on the latest snapshot of interaction with a Future". We will use this widget in the Scaffold class's body parameter above, replacing the call to ListView.builder(). The change will allow the application to choose the widget that will render in our main view, depending on the state of the asynchronous LWNRssService.getFeed() operation. Below we will walk through the changes needed to implement FutureBuilder in the LWNHeadlineScreen class step-by-step (full class available here):

    class LWNHeadlineScreen extends StatelessWidget
    {
        Future<Rss1Feed> feed;

This version of the class has changed the data type of feed from Rss1Feed to Future<Rss1Feed>. In the application from part one, LWNHeadlineScreen used a concrete instance of Rss1Feed for feed, requiring the data to exist before an instance of the interface could be created. The new version, using a Future<Rss1Feed> for feed, allows LWNHeadlineScreen to be instantiated prior to feed being fetched. This Future<Rss1Feed> is provided to LWNHeadlineScreen via the constructor defined in (shorthand) form below:

    LWNHeadlineScreen(this.feed);

The build() method is responsible for returning the widget to be rendered. In this case, the widget will consist of a Scaffold with an application bar type of AppBar:

    @override
    Widget build(BuildContext context)
    {
      return Scaffold(
        appBar: AppBar(
            title: Text("LWN RSS Reader")
        ),

This defines the "application bar" at the top of our UI, where toolbars or other interface elements can be added if desired. In this example we assign only a Text widget to give the application a title. The body of the Scaffold class is the most important part of the application; it contains the widgets that build the primary user interface; it uses FutureBuilder:

    body: FutureBuilder<Rss1Feed>(
        future: feed,
        builder: (BuildContext context, AsyncSnapshot snapshot) {

Here we create a FutureBuilder instance for a Rss1Feed type (matching the type of the feed property). The instance of the class is provided two parameters: future, which is the Future<Rss1Feed> variable we are working with, and builder, which takes a function with two parameters as a value. We will be focusing on the snapshot parameter, which is an instance of AsyncSnapshot and offers an "immutable representation of the most recent interaction with an asynchronous operation". In practical terms, snapshot provides several properties that allow a developer to choose the rendered widget based on the current state of the asynchronous operation. Here is how snapshot is used:

   if(snapshot.hasData) {
        return ListView.builder(
            itemCount: snapshot.data.items.length,
            itemBuilder: (BuildContext ctxt, int index) {
                final item = snapshot.data.items[index];
                return ListTile(
                    title: Text(item.title),
                    contentPadding: EdgeInsets.all(16.0),
                 );
             }
         );
    } else if(snapshot.hasError) {
         return Text("{$snapshot.error}");
    }

    return Center(
        child: CircularProgressIndicator()
    );

In the example above, we use the hasData and hasError properties of snapshot to render a ListView widget once the asynchronous operation has completed successfully (or a Text widget for an error), and a centered CircularProgressIndicator widget while a request is in progress. The result is a better UI that displays an appropriate spinner while a HTTP request is in progress, replacing it with the original list view upon successful completion.

Making things clickable

To add the interactivity to the application, we will be working exclusively with the code contained within the ListView.builder method, and more accurately the ListTile instances created by it. For reference, here is how we defined the UI for each news item in part one:

    return ListTile(
        title: Text(item.title),
        contentPadding: EdgeInsets.all(16.0),
    ); 

To improve upon this implementation, we start by incorporating the item.description property (a summary of an article taken from the RSS feed). The description provided by the RSS feed is in HTML format and must be rendered to make the embedded links work. To convert HTML to a Flutter widget, the pub.dev community has provided the flutter_html package. This package accepts a block of HTML code and creates the necessary widget components for it to be rendered in the UI. The flutter_html package provides the Html class used below, which is later assigned to the subtitle parameter of ListTile:

    Html(
        data: "<p>" + item.description.trim() + "</p>",
        onLinkTap: (String url) async {
            if(await canLaunch(url)) {
                await launch(url);
            } else {
                throw 'Could not launch $url';
            }
        }
    )

The Html widget is created using two parameters: data, the HTML content to render, and onLinkTap, which is called when a user clicks a generated link. The data parameter is straightforward, taking the HTML content directly from the item.description property with minor modifications.

The function passed to onLinkTap implements features included in another Flutter package, url_launcher, which provides a reliable method of opening a URL in a browser without worrying about platform specifics. By using the URL passed to onLinkTap in conjunction with the url_launcher package, we direct all links rendered by flutter_html to open into a browser.

To make an entire list item (outside of embedded links) clickable to open a full article, we need to return to the ListTile class and add the onTap parameter. The onTap parameter is a function that is called when a user clicks on an item in the list (outside of an embedded link). The onTap implementation is not as straightforward as onLinkTap; the links provided by the LWN RSS go to the RSS view of the item rather than the full article. The difference between the full content URL and the RSS version on LWN is simply rss being added to the URL. For example, here is a representative link we might find in the feed:

    https://lwn.net/Articles/826124/rss

To make list items clickable and take users to a full article on the site, we need a direct link, which can be achieved by manipulating an item's RSS feed URL. Here is the implementation of the function provided to the onTap method to do so:

    
    () async {
        
        Uri rssLink = Uri.parse(item.link);
        String linkUrl = "https://lwn.net/Articles/${rssLink.pathSegments[1]}/";

        if(await canLaunch(linkUrl)) {
            await launch(linkUrl);
        } else {
            throw 'Could not launch $linkUrl';
        }
    }

We use the Uri class to parse the provided link, and create a new String linkUrl to store the full article URL. To extract the article ID, we use the pathSegments list provided by the Uri class, which contains a list item for each part of the parsed URI path. Since the Article ID is the second item in the list we reference it using rssLink.pathSegments[1] when creating the linkUrl string. This value can then be used to create a new URL and launch a browser to open that location when the list item is clicked.

With a few more slight modifications to the user interface (such as adjusting each list item's margins and bolding the title of the article), our enhancements to the application are complete. Readers who would like to see the full application code with all of the changes can do so in the project repository. Here is how the application now looks running on Ubuntu 20.04 (with the security updates item highlighted):

[Enhanced LWN RSS Reader]

As described, each hyperlink can be clicked to open up the relevant content in an appropriate web browser for the platform, and clicking on an item opens a link to a full article. In all, the first basic implementation of a simple headline reader discussed in part one was roughly 60 lines of code; this more useful version was double that at around 120 lines of code. Overall, Flutter was reasonably easy to use for this project, and I found the documentation to be an excellent reference. The ability to execute small chunks of code in a web browser using DartPad was also a great help to test snippets of code as needed. For Linux (and mobile) application development, Flutter provides an experience worth checking out.



to post comments


Copyright © 2020, Eklektix, Inc.
This article may be redistributed under the terms of the Creative Commons CC BY-SA 4.0 license
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds