iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐥

Architecture of the Flutter App Pilll

に公開

This article is the 16th-day entry for the Individual Development Advent Calendar 2022.

I am developing an app called Pilll for birth control pill management. For more details, see here:
https://bannzai.hatenadiary.jp/entry/2021/05/10/054207

I recently made a cool LP (Landing Page) and am preparing for its release, so please check it out. Also, let me know if there's anything I should improve about it (a bit of self-promotion).
LP: https://pilllapp.studio.site/

What I will cover in this article

I'm going to write a bit about the Flutter architecture I'm often asked about. I'll also promote the library I created and ask for stars (that's the main goal). Additionally, I will briefly look back at the growth of the project in 2022 with some numbers.

Architecture

Everything is on GitHub, so please check the details there. And please give it a star.
https://github.com/bannzai/pilll

I'll explain by looking at the first level of the package directory structure. I've manually removed some unnecessary items, but the surface-level structure looks like this:

$ tree -L 1 lib/
lib/
├── components
├── entity
├── features
├── native
├── provider
└── utils
  • components: Common components like Buttons, Colors, etc.
  • entity: Resources stored in Firestore (DB).
  • features: Further divided into subdirectories for each goal/functionality. Mostly screen-based. Though not currently present, it used to include things like common "buttons" for payment flows.
  • native: Code for bridging with native features (Swift, Kotlin) is placed here.
  • provider: Contains Riverpod providers. Items that are too specific to a feature are placed directly inside features.
  • utils: Other utility functions. For example, Pilll has many date-related processes, so those go here.

As a rule (mostly), singular directory names contain files, while plural directory names contain subdirectories.

The features directory is usually the one that grows the most, so I'll use it as an example. Rules for levels beyond the 1st or 2nd hierarchy are flexible; I create directories in units that are easy to understand. For example, if there are multiple buttons used only on the user page, I might create a directory like features/user/buttons/. Conversely, if there are only one or two, I might just create a file like features/user/button.dart. I don't keep it strictly enforced (partly because it's individual development).

That's it.

About State Management

In many mobile apps, the focus often falls on how to manage data received from APIs or databases. For managing the state that affects the app, I use Riverpod, and specifically in Flutter, I implement it using flutter_hooks and hooks_riverpod as well. The reasons for choosing them are that they can handle many patterns, are easy to write and read, and are type-safe. A particular advantage is that Riverpod works well with Firestore, which allows for data retrieval in Stream format, making it easy to achieve a Single Source of Truth.

The promotion for my self-made library starts here. This is the main topic. Read carefully.

When using Firestore x Riverpod, I expect that patterns like the one below are common. The provider declarations are omitted.

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class TweetsPage extends HookConsumerWidget {
  const TweetsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tweets = ref.watch(tweetsProvider);
    return tweets.when(
      data: (t) => t.isEmpty ? const TweetsEmpty() : TweetsBody(tweets: t),
      error: (error, st) => ErrorPage(error: error),
      loading: () => const Loading(),
    );
  }
}

Data retrieval for tweets in Firestore is performed through a Stream. It displays the main content (TweetsEmpty|TweetsBody), an ErrorPage in case of an error, and a Loading widget during data loading. One benefit of this approach is the ability to concisely and comprehensively assign widgets for cases where data hasn't been retrieved from the Stream yet or when an exception occurs. However, in this case, if another type of data obtained from a Stream is added, the when calls will end up being nested.

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class TweetsPage extends HookConsumerWidget {
  const TweetsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tweets = ref.watch(tweetsProvider);
    final user = ref.watch(userProvider);
    return tweets.when(
      data: (t) {
        if (t.isEmpty) {
	  return const TweetsEmpty();
	} else {
	  return user
	    .when(
	         data:(data) => TweetsBody(tweets: t, user: user),
                 error: (error, st) => ErrorPage(error: error),
                 loading: () => const Loading(),
            );
	}
      }
      error: (error, st) => ErrorPage(error: error),
      loading: () => const Loading(),
    );
  }
}

Actually, there are other ways, such as combining everything into a single Provider to make it easier to use from the Widget, or writing if (tweets is AsyncLoading || user is AsyncLoading) to return Loading() since tweets and user have separate types depending on their state. However, compared to the first code example, this increases boilerplate code and brings concerns about missing checks with is AsyncLoading. It makes the code less straightforward.

I'll introduce a library I created to solve that issue. Named... Ta-da!

_人人人人人人人人人人_
> async_value_group <
 ̄Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^ ̄

async_value_group

Using async_value_group allows you to write code like the following even when you want to use multiple Streams (AsyncValue) from a Provider:

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:async_value_group/async_value_group.dart';

class TweetsPage extends HookConsumerWidget {
  const TweetsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return AsyncValueGroup.group2(
      ref.watch(tweetsProvider),
      ref.watch(userProvider),
    ).when(
      data: (t) => t.t1.isEmpty ? const TweetsEmpty() : TweetsBody(tweets: t.t1, user: t.t2),
      error: (error, st) => ErrorPage(error: error),
      loading: () => const Loading(),
    );
  }
}

You set the AsyncValues related to the Widget in the arguments of AsyncValueGroup.group(n). A type called Tuple(n), defined in async_value_group, is passed as an argument to the closure of when's data. Tuple(n) has properties named t(n) in sequential order, and types are applied to each property in the order they were passed to AsyncValueGroup. The data part is evaluated only when all AsyncValues have been resolved.

What do you think? One drawback of this approach is that you cannot freely determine the property names in Tuple(n), so you can't give them descriptive names like tweets or user. However, in most cases, this is protected by types. Just be careful if you have to use multiple properties of the same type (). That said, using same types is something you would need to be careful about anyway.

Another point to note is that this feature should only be used in situations where grouping AsyncValues is appropriate. For example, if you want to display a UI other than a loading indicator as soon as at least one of the resources is obtained, using AsyncValueGroup would be a mismatch. In that case, writing code like if (tweets is AsyncLoading || !(user is AsyncLoading)) would likely be simpler. Nevertheless, in most cases, I think it's better to proceed only after all information needed for the Widget has been fetched. In Pilll, all processes follow the procedure: Fetch necessary information -> Display main content.

I personally quite like this because it works well with services like Firestore where data can be retrieved as a Stream.

So, the very convenient AsyncValue.group is a big hit in Pilll. I guess you all have no choice but to star it now. Please give it a star. I'll leave the link here once more.

https://github.com/bannzai/async_value_group/

  • Note: Please let me know if there's a better way to write this without using this library.

About the Growth in 2022

Since the main topic is over, I'll write this part briefly (oops), but here are some numbers to give you a general idea of how Pilll is doing now. If you want to compare with last year, please check the year-end review article from last year.

https://bannzai.hatenadiary.jp/entry/2021/12/25/175806

The number of paid subscribers exceeded 1,000 🥳

Over 3,000 App Store ratings with a 4.7 rate ⭐️

That's it. Bragging over.

Next Year

I haven't decided on my outlook for next year yet, but I'd like to continue growing it.

Summary

Give me stars!
⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
https://github.com/bannzai/async_value_group/
⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️

The End \(^o^)/

Discussion