Landmarks Flutter

Our team dove in and attempted to faithfully reproduce the Landmarks app using Flutter. We’ve made the git repo publicly available so that anyone can download the code and see how it compares.

Prepping Assets

Prepping the Flutter app to use the assets in Apple’s example project was quick to set up. Simply copy the Resources folder over to the assets folder and make the folder known in the pubspec.yaml , and we now have access to all of the data that the iOS project has!

flutter:

assets:

- assets/

The User Interface

Stacks

Stacks in SwiftUI are comparable to Flex widgets in that they display their children in one-dimensional arrays. So a VStack is similar to a Column , an HStack is similar to a Row , and a ZStack lays out its children one on top of the other, which (surprise!) is the kind of Stack Flutter developers are familiar with. Composing views with HStack s and VStack s in SwiftUI feels very familiar to a Flutter developer.

The code in SwiftUI feels a bit lighter owing to the lack of return statements and child or children params everywhere. The naming of the SwiftUI Stack widgets will take some time to get used to since Flutter’s Row , Column , and Stack widgets seem to be more intuitively named.

ListViews

Table views in UIKit are now List s in SwiftUI. Wrap children objects in a List and you’re all set. This is a welcome improvement over implementing a number of delegate methods to set up a table view on iOS.

On the Flutter side, you have your choice of several options. You can use a ListView for displaying multiple children or a SingleChildScrollView if you have only one child to display. For our example in Flutter, we used a CustomScrollView and slivers in order to recreate the same animations with the navigation bar you get in the SwiftUI Landmarks example.

SwiftUI uses a ForEach command to generate List children on demand. We opted to use a SliverList and a SliverChildBuilderDelegate to leverage the builder callback to dynamically generate our LandmarkCell widgets. Slivers are optimized to lazily load their children and are Viewport-aware, so that child views aren’t built until they are displayed.

SwiftUI

ForEach(userData.landmarks) { landmark in

if !self.userData.showFavoritesOnly || landmark.isFavorite {

NavigationButton(

destination: LandmarkDetail(landmark: landmark)) {

LandmarkRow(landmark: landmark)

}

}

}

Flutter

SliverList(

delegate: SliverChildBuilderDelegate(

(context, index) {

final landmark = landmarks[index];

return LandmarkCell(

landmark: landmark,

onTap: () {

Navigator.push(

context,

CupertinoPageRoute(

builder: (context) => LandmarkDetail(

landmark: landmark,

),

),

);

},

);

},

childCount: landmarks.length,

),

),

Loading and Parsing Data

Loading

Loading our raw data from assets is similar in Dart and Swift. We have some data we know is JSON, and we want to create some models from it.

Swift

let file = Bundle.main.url(forResource: filename, withExtension: nil)

data = try Data(contentsOf: file)

Dart

final fileString = await rootBundle.loadString(‘assets/$filename’);

Parsing

Parsing our data into a list of Landmark objects is where the path diverges a bit. Flutter does not currently support reflection, so we are unable to parse JSON in the same way that Swift does it. Let’s take a look at the definition of the load function in Swift:

func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T

and with this, Swift is able to generate the data model with this simple call and no manual data parsing:

let landmarkData: [Landmark] = load(“landmarkData.json”)

The reason it can do this is because in Swift, Landmark is a Codable and therefore a Decodable . So by some underlying magic the type T can be instantiated and decoded.

As stated, this just isn’t currently possible in Flutter. Try to instantiate an object just by its type and you’ll find it quite impossible yourself! So, we need to manually parse this data. Our load function in the Flutter app is defined:

Future<T> load<T>(String filename, T Function(dynamic) builder) async

What this does is the generic function of loading the data, but leaves the building of the data up to the caller of the function. So we load the landmarkData in the following way:

Future<Null> loadData() async {

_landmarkData = await _load('landmarkData.json', (data) => List.unmodifiable((data).map((element) => Landmark.fromJSON(element))));

}

The fromJSON function of Landmark is a factory constructor that does exactly what you expect, constructs a Landmark from a Map . We opted to manually parse this small amount of data, but there are options for code generation if you’re interested.

Navigation

For most of our development in Flutter, we use Material widgets. But since we wanted to create a real apples-to-apples comparison, we decided use a Cupertino theme.

Navigation controllers in UIKit have been replaced with a NavigationView . In Flutter, we used a CupertinoPageScaffold with a CustomScrollView child. To get the expanding/collapsing animation of the navigation bar, such as in the SwiftUI example, a CupertinoSliverNavigationBar was perfect. When expanded, the widget passed into the largeTitle property of the CupertinoSliverNavigationBar is displayed. When you scroll down and the navigation bar collapses, a smaller version of the title is displayed in the middle of the collapsed navigation bar.

We’ve become accustomed to using callbacks on the children of a ListView to communicate data back to the parent widget when the user taps a cell. SwiftUI’s approach of wrapping List children in NavigationButton s to control the presentation of the next route is an interesting approach that we’ll have to explore in future posts.

Architecture

iOS

For architecture, we attempted to mimic the same flow of data seen in the iOS app. The iOS app used some nifty Swift features so that the UI of the application updates in response to changes in the data. For example, when you dive into a Landmark detail and favorite it, the app just updates the isFavorite boolean of the Landmark like this:

self.userData.landmarks[self.landmarkIndex].isFavorite.toggle()

and the star turns yellow in response. There is no explicit changing of this color, it just updates when the model updates. There is a similar flow of data for the favorites toggle on the Landmark list screen.

So how does this work on the iOS side? The answer is in the UserData object which is a BindableObject . A BindableObject is defined by Apple as:

A type of object that notifies the framework when changed.

So, the two bits of data we use to update UI ( showFavoritesOnly and landmarkData ) will notify the framework when they change. The views that wish to be notified, LandmarkDetail for example, add…

@EnvironmentObject var userData: UserData

…to the declaration the view. The usage of @EnvironmentObject is defined as:

A linked View property that reads a `BindableObject` supplied by an ancestor view that will automatically invalidate its view when the object changes.

So, whenever one of those two pieces of data are updated, the views that listen to them will be invalidated and rebuild.

Flutter

We were able to get a similar flow in the Flutter app. We simply set the Landmark model’s isFavorite value:

landmark.setFavorite(value);

and the UI updates in response. We achieved this by having the Landmark model extend the ChangeNotifier class. We added the following function to the class:

void setFavorite(bool value) {

isFavorite = value;

notifyListeners();

}

and now anyone who cares to listen to changes in the model can do so. Here’s an example from our LandmarkDetail widget. Did you know that AnimatedBuilder can listen to a ChangeNotifier ?

AnimatedBuilder(

animation: landmark,

builder: (context, widget) {

return StarButton(

isFavorite: landmark.isFavorite,

onTap: (value) {

landmark.setFavorite(value);

},

);

},

),

For toggling the favorites list, we simply have a boolean on the StatefulWidget that builds the list, and when the toggle occurs we call setState .

You may notice a subtle difference in this flow, which is that in the iOS app, the view will be notified whenever the landmarkData list is updated, including any of the data of its children. We only listen to changes in a single Landmark object. Due to how Flutter builds, the favorites list will still update when we pop back to the list from a detail which works perfectly for our needs.

It is certainly possible to create an architecture where we listen to changes in any child of the list, and it depends on the size and efficiency of your data. For example Listenable.merge(landmarkData) with ListenableBuilder would work here, but you can imagine this could get inefficient with a huge list of data.

Future Improvements to the Flutter version

You may notice that a few things are missing from our Flutter implementation.

First, the separator line between empty cells on the main screen’s SliverList is missing. This is the default behavior in a native iOS implementation (and is not often desired).

Second, you’ll see that when toggling the favorites switch, the table cells don’t animate in and out as they do in a standard iOS table view. We are working on implementing this functionality on a separate branch. We are using the AnimatedList widget and got the animations pretty close but not perfect.

One challenge is that AnimatedList is not a SliverList and can’t be used inside a CustomScrollView . It must be wrapped inside a SliverToBoxAdapter . A SliverList is more efficient because it instantiates only child widgets that are actually visible through the scroll view’s viewport. This is not an issue for small lists as in this example, but could introduce a performance problem for much larger ones. We have reached out to the Flutter team for some guidance on these issues.

Do you have any ideas for improvements on making the code cleaner or simpler? Please file a pull request!