Building the SwiftUI Sample App in Flutter

Albert Lardizabal
Jun 10 · 12 min read

Very Good Ventures re-built the SwiftUI sample app to do a side-by-side comparison of SwiftUI and Flutter, and found there’s a lot to love about both.

Kevin Gray (Principal Engineer), Martin Rybak (Engineering Director), and Albert Lardizabal (Principal Engineer) contributed to the writing of this article and the development of the Flutter Landmarks project. Read more of their content on the Very Good Ventures blog.

SwiftUI (Left) and Flutter (Right)

How Does SwiftUI Compare to Flutter?

When Apple announced SwiftUI at WWDC 2019, the team at Very Good Ventures got really excited as did many other mobile developers. We’ve been building iOS and Android apps for a long time, and for the last two years we’ve been building declarative UIs with Flutter. We wanted to learn more about Apple’s approach to building a declarative and composable layout system.

So, we enthusiastically downloaded the Xcode 11 beta app and started exploring SwiftUI. Apple provided an excellent example project, Landmarks, with a step-by-step tutorial to learn how to get up and running with SwiftUI.

Since the declarative nature of SwiftUI has similarities with Flutter and we have a lot of experience with Flutter, we wanted to know: “How does SwiftUI compare to Flutter?”

We decided it would be a fun challenge and a fruitful educational exercise to recreate the Landmarks app in Flutter. Then, we could compare the resulting codebases and identify similarities and differences between the two.


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 folder over to the folder and make the folder known in the , 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 widgets in that they display their children in one-dimensional arrays. So a is similar to a , an is similar to a , and a lays out its children one on top of the other, which (surprise!) is the kind of Flutter developers are familiar with. Composing views with s and s in SwiftUI feels very familiar to a Flutter developer.

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

ListViews

Table views in UIKit are now s in SwiftUI. Wrap children objects in a 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 for displaying multiple children or a if you have only one child to display. For our example in Flutter, we used a and slivers in order to recreate the same animations with the navigation bar you get in the SwiftUI Landmarks example.

SwiftUI uses a command to generate children on demand. We opted to use a and a to leverage the builder callback to dynamically generate our 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

Parsing

Parsing our data into a list of 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 function in Swift:

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

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

As stated, this just isn’t currently possible in Flutter. Try to instantiate an object just by its and you’ll find it quite impossible yourself! So, we need to manually parse this data. Our 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 in the following way:

Future<Null> loadData() async {
  _landmarkData = await _load('landmarkData.json', (data) =>   List.unmodifiable((data).map((element) =>         Landmark.fromJSON(element))));
}

The function of is a constructor that does exactly what you expect, constructs a from a . 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 . In Flutter, we used a with a child. To get the expanding/collapsing animation of the navigation bar, such as in the SwiftUI example, a was perfect. When expanded, the widget passed into the property of the 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 to communicate data back to the parent widget when the user taps a cell. SwiftUI’s approach of wrapping children in 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 detail and favorite it, the app just updates the boolean of the Landmark like this:

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 list screen.

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

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

…to the declaration the view. The usage of 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 model’s value:

landmark.setFavorite(value);

and the UI updates in response. We achieved this by having the model extend the 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 widget. Did you know that can listen to a ?

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 on the that builds the list, and when the toggle occurs we call .

You may notice a subtle difference in this flow, which is that in the iOS app, the view will be notified whenever the list is updated, including any of the data of its children. We only listen to changes in a single object. Due to how Flutter builds, the favorites list will still update when we 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 with 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 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 widget and got the animations pretty close but not perfect.

One challenge is that is not a and can’t be used inside a . It must be wrapped inside a . A 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!


Early Takeaways From Our Comparison

Code Complexity

At first glance, it appears as if the Flutter version has a bit more lines of code and complexity. That’s the elephant in the room, so let’s explore why that is. It’s important to recognize that Apple has fine-tuned SwiftUI for working exclusively within Apple’s design system. That is, elements like the navigation bar and table animations appear trivial to implement because they are magically implemented behind the scenes. But if you want to tweak or modify this behavior, there is not much you can do.

In contrast, nothing in Flutter, including the fancy navigation bar, is implemented in a black box. Everything is explicit, composable, and modifiable. So in this example, special-looking things (such as fancy scrolling effects) have special-looking code (slivers). Flutter has a Cupertino theming library that makes it easier to build iOS-style experiences, but that’s not its mainstay. Flutter excels at empowering custom UI experiences that let your unique brand shine through, on multiple platforms. That said, where there is room for improvement to make iOS-only development easier, let the Flutter team know! We’ve already pointed out a few issues above.

Declarative UI FTW

Ultimately, we’re excited that Apple is moving towards the declarative programming paradigm. We think SwiftUI affirms what React Native and Flutter have already embraced.

Combined with Swift’s concise syntax, SwiftUI feels very modern to work with, compared to the often unwieldy layout constraint code that usually comprised half of the code in a class on iOS.

On the other hand, we were able to rebuild the SwiftUI Landmarks with Flutter in a really short amount of time. That’s an endorsement of Flutter, but also of the overall trend towards declarative UI—which of course now includes SwiftUI!

SwiftUI (Left) and Flutter (Right)

SwiftUI is just getting started

It’s important to note that SwiftUI is very new — it probably wont be ready for wide-scale production for some time (it is only an early beta after all). Flutter, on the other hand has been in the wild for a couple of years and officially out of beta since December 2018.

There are a few things in SwiftUI that are particularly promising. For instance, the designer is pretty cool, PreviewProviders that let you pin views with data is useful, and built-in support for things like accessibility, dark mode, and RTL are impressive. SwiftUI’s new ability to “hot reload” is something that Flutter developers have been enjoying for a while, and while it’s not quite the same, it’ll certainly make a lot of iOS developers happier.

It’s going to a take some time for SwiftUI to really get into the mainstream, but it’ll be fun to see how it evolves. At the end of the day, we anticipate it’ll lead to more high quality apps as developer productivity increases. It’ll also be fun to observe how Flutter and React Native evolve in parallel.

Design Guidelines (or are they rules?)

It’s an obvious statement to say that SwiftUI is for creating apps for Apple’s platforms. At the moment, SwiftUI really isn’t great if you want to create an app that doesn’t look and feel like an Apple app. There’s nothing really wrong with that, but it may be limiting from a design perspective.

This is in contrast to Flutter’s design goals — Flutter has always been about creating unique branded app experiences, not necessarily something wholly conforming to the design guidelines of a specific platform. So, as of this moment, Flutter is more flexible for creating a unique and custom UI experience compared to SwiftUI.

This is a huge topic with many camps and opinions. For now, it’ll suffice to say that it will be interesting to watch and see what kind of support SwiftUI provides in the long run for fully custom app designs.

Portability

One obvious area where SwiftUI has some early drawbacks is its portability. Currently, Apple’s documentation clearly states that SwiftUI will only work with iOS13.0+ beta, macOS10.15+ beta, tvOS 13.0+ beta, and watchOS 6.0+.

Flutter, on the other hand, will run on multiple platforms (iOS, Android, macOS, Windows, ChromeOS, Raspberry Pi, and Web), and is compatible with the long tail of iOS and Android devices running a variety of older OS versions. In fact, we were able to get the Flutter version running on Android with a trivial amount of extra work.

Again, it’s very early for SwiftUI, so we’ll have to see what kind of backwards compatibility and platform portability they’ll be able to achieve in the future. Who knows…perhaps one day we’ll be able to run SwiftUI on other platforms. (We can dream, can’t we?)

The Future is Composable

In the end, SwiftUI indicates a huge step forward for app developers. We’re excited to see how it develops, and watch as Apple and Google continue to create better tools for developers to create incredible apps.

Our team at Very Good Ventures is going to continue to explore SwiftUI (and Flutter too!). We’d love to hear from you what you think we should dig into next.

  • A comparison of app performance?
  • Side-by-side “hot reload” comparison?
  • A deep dive on the different tools for SwiftUI and Flutter?

Let us know what we should research next in the comments!

Tell us in the comments what we should dig into next in our comparison of SwiftUI and Flutter.

Thanks for reading!


Very Good Ventures is a technology studio in NYC with years of mobile development experience and is the world’s premier Flutter studio. We built the first-ever Flutter app in 2017 and have been on the bleeding edge ever since. We offer a full range of app development services including consultations, full-stack development, team building, and technical oversight. We are always looking for partners and teammates, so drop us a line!

Flutter NYC

For NYC developers interested in Flutter, Google’s new universal UI framework

Albert Lardizabal

Written by

Principal Engineer @ Very Good Ventures

Flutter NYC

For NYC developers interested in Flutter, Google’s new universal UI framework