Building the SwiftUI Sample App in Flutter

Building the SwiftUI Sample App in Flutter
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.

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.

Check out our version of SwiftUI’s Landmarks project built in Flutter on GitHub!

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 VStacks 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 Lists 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 NavigationButtons 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 Landmarkmodel 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 Landmarkobject. 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 exampleListenable.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 AnimatedListwidget 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!

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 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!

Create a Post Reader App with Flutter

The Complete Flutter Development Bootcamp with Dart

Dart and Flutter: The Complete Developer’s Guide

Learn Flutter & Dart to Build iOS & Android Apps

Flutter & Dart: A Complete Showcase Mobile App™

Suggest:

Flutter TabBar & TabBarView by Sample Code | Flutter Tutorial | Flutter 2023

Flutter Tutorial: Flutter PDF Viewer | Flutter PDF Tutorial | PDF in Flutter

Flutter Tutorial For Beginners In 1 Hour

Flutter Course - Full Tutorial for Beginners

Code a Twitter Clone with Flutter, Appwrite, Riverpod | Full Tutorial for Beginners to Advanced

Flutter - Build Cryptocurrency App From Scratch