# Say My Frame > Generate Flutter apps from independent modules. Say My Frame generates Flutter apps from independent modules, such as a router, tabs, dependency injection, a state manager, Firebase and screens, wired together and ready to run. # Say My Frame Source: https://doc.saymyframe.com/ Say My Frame (SMF) generates Flutter apps from independent modules. You choose what the app needs, such as a router, tabs at the bottom, sign-in with Google and Apple, notifications, a paywall, a REST client, dependency injection, a state manager, Firebase services, an icon, CI or screens, and `smf create` generates a Flutter project in which these pieces already work together. The routes of the screens are in the router, the tabs show the screens, the services are registered in the container, and the start-up code runs in the right order. Every app has the [flavors](https://doc.saymyframe.com/guides/flavors.md) `dev`, `staging` and `prod`. ```bash dart pub global activate smf_flutter_cli smf create my_app -m home,onboarding,settings,bottom_tabs,material_theme,gen_l10n,get_it,bloc ``` [Video: smf create in a terminal: it asks for the app name and the modules, among them the paywall, the onboarding screen, Google sign-in and Sign in with Apple, the notifications, the REST client, the app icon, the splash screen and GitHub Actions, adds the modules that the chosen ones need, such as go_router, the settings screen, Firebase Authentication and RevenueCat, asks who may use the app without an account, makes the app icon and the splash screen, and generates a Flutter app with an onboarding, a start screen, sign-in with an email, Google and Apple, a paywall, notifications, tabs at the bottom, a theme, two languages, get_it, BLoC, dio and a CI workflow](https://doc.saymyframe.com/demo/0.8/smf_create.mp4) The video shows a run in a terminal that picks these modules by answering the questions of `smf create`, and with them [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), the screens of sign-in, with [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md), [`paywall`](https://doc.saymyframe.com/modules/paywall.md), which brings [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) and [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md), [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md), [`dio`](https://doc.saymyframe.com/modules/dio.md), [`launcher_icons`](https://doc.saymyframe.com/modules/launcher-icons.md), [`native_splash`](https://doc.saymyframe.com/modules/native-splash.md) and [`github_actions`](https://doc.saymyframe.com/modules/github-actions.md). Sign-in needs a Firebase project, which the run leaves for later; [Sign-in](https://doc.saymyframe.com/guides/sign-in.md) has the steps. The paywall needs a RevenueCat project, which you set up by hand; the [steps by hand](https://doc.saymyframe.com/setup.md) show how. What you get is a regular Flutter project. It does not depend on SMF at run time, and nothing in it has to be generated again, so the code is yours from the first commit. It comes with `AGENTS.md`, a guide for the [coding agents](https://doc.saymyframe.com/guides/coding-agents.md) that work on it. ## Why modules A module is one piece of an app, such as the router or the analytics, and modules do not know about each other. A module that shows screens says that it needs *a router*, without knowing that the router is go_router. The analytics module can follow the screens the user sees *when the app has a router*, whichever router it is. SMF calls these shared parts **roles**, and more than one module can provide the same role. That is why any combination works: you can add or leave out a module, or swap one provider of a role for another, and the app still compiles. Continuous integration generates apps from the modules in many combinations and checks each one with `flutter analyze`. ## The modules | Role | Modules that provide it | How many in an app | | --- | --- | --- | | App entry | [`flutter_core`](https://doc.saymyframe.com/modules/flutter-core.md) | always one | | Router | [`go_router`](https://doc.saymyframe.com/modules/go-router.md) | none or one | | Layout | [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md) | none or one | | Settings screen | [`settings`](https://doc.saymyframe.com/modules/settings.md) | none or one | | Onboarding screen | [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) | none or one | | State management | [`bloc`](https://doc.saymyframe.com/modules/bloc.md), [`riverpod`](https://doc.saymyframe.com/modules/riverpod.md) | none or one | | Theme | [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md) | none or one | | App icon | [`launcher_icons`](https://doc.saymyframe.com/modules/launcher-icons.md) | none or one | | Splash screen | [`native_splash`](https://doc.saymyframe.com/modules/native-splash.md) | none or one | | Localization | [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) | none or one | | Dependency injection | [`get_it`](https://doc.saymyframe.com/modules/get-it.md) | none or one | | Events | [`event_bus`](https://doc.saymyframe.com/modules/event-bus.md) | none or one | | Preferences | [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md) | none or one | | Notifications | [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) | none or one | | Push messages | [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) | none or one | | REST API | [`dio`](https://doc.saymyframe.com/modules/dio.md) | none or one | | Purchases | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | none or one | | Values in .env | [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) | none or one | | Crash reporting | [`firebase_crashlytics`](https://doc.saymyframe.com/modules/firebase-crashlytics.md) | any number | | Analytics | [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) | any number | | Authentication | [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | none or one | | CI | [`github_actions`](https://doc.saymyframe.com/modules/github-actions.md) | none or one | Six modules provide no role. Three are features: [`home`](https://doc.saymyframe.com/modules/home.md), a start screen, [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), the screens of sign-in and of the account, and [`paywall`](https://doc.saymyframe.com/modules/paywall.md), the paywall and the screen of the subscription. [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) sets up Firebase for the other Firebase modules, and [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) add the ways to sign in with Google and Apple. ## Status SMF generates apps for Flutter 3.44 or newer and Dart 3.12 or newer. It is tested on macOS, Linux and Windows. ## Where to go next - To generate an app, [install SMF](https://doc.saymyframe.com/getting-started/installation.md), [create your first app](https://doc.saymyframe.com/getting-started/first-app.md) and [take a tour of it](https://doc.saymyframe.com/getting-started/generated-app.md). - To pick modules, read [Choosing modules](https://doc.saymyframe.com/guides/choosing-modules.md) and the [`smf create` reference](https://doc.saymyframe.com/guides/smf-create.md). - To see how it works, read about [the module model](https://doc.saymyframe.com/concepts/module-model.md) and [the generation pipeline](https://doc.saymyframe.com/concepts/pipeline.md). - To write a module of your own, start with [Extending SMF](https://doc.saymyframe.com/extending.md). - To help build SMF, see [Contributing](https://doc.saymyframe.com/contributing.md). # Installation Source: https://doc.saymyframe.com/getting-started/installation SMF is a command line tool, `smf`, published on pub.dev as [`smf_flutter_cli`](https://pub.dev/packages/smf_flutter_cli). ## Requirements - Flutter 3.44 or newer, which comes with Dart 3.12 or newer. The apps that SMF generates require these versions, and `smf create` checks the Flutter SDK before it generates anything. - `flutter` on the `PATH`. SMF uses the `flutter` it finds there, and the `dart` of the same SDK, so the Dart that builds the app is also the one that formats and fixes its code. - A Mac with Xcode, to build the iOS app. SMF generates the Android and iOS projects on any system. For Xcode 27, see [troubleshooting](https://doc.saymyframe.com/guides/troubleshooting.md#ios-builds-with-xcode-27). The Firebase modules need more on the machine: the Firebase CLI, the FlutterFire CLI and a Firebase account. SMF looks for them only when an app has these modules, and offers to set up what is missing; see [Firebase](https://doc.saymyframe.com/guides/firebase.md). SMF is tested on macOS, Linux and Windows. ## Install Activate the package globally with the Dart that comes with your Flutter SDK: ```bash dart pub global activate smf_flutter_cli ``` This installs the `smf` command in the directory of globally activated Dart packages, which is `~/.pub-cache/bin` on macOS and Linux. If that directory is not on your `PATH`, `dart pub global activate` prints a warning. Add the directory to the `PATH` as the [Dart documentation](https://dart.dev/tools/pub/cmd/pub-global#running-a-script-from-your-path) describes. Check the installation: ```bash smf --version smf --help ``` ## Update and remove Activating the package again installs its latest version: ```bash dart pub global activate smf_flutter_cli ``` To remove SMF: ```bash dart pub global deactivate smf_flutter_cli ``` ## Next [Create your first app](https://doc.saymyframe.com/getting-started/first-app.md). # Create your first app Source: https://doc.saymyframe.com/getting-started/first-app `smf create` generates an app in a new directory. In a terminal it asks what it needs to know, and with the answers given as options it asks nothing. ## Answer the questions Run `smf create` in the directory where the app's own directory should go: ```bash smf create ``` This is what a run looks like when you keep the start screen `home`, which is selected already, and pick tabs at the bottom, a settings screen, the onboarding, the localization, the theme, get_it, the event bus, the app icon and the splash screen: ```text πŸ‘‹ Hello! Let's create a Flutter app with Say My Frame. ? App name my_app ? Organization (reverse domain) com.example ? Features: which do you want? home β€” Start screen with a welcome and the next steps ? Infrastructure: which do you want? none ? Layout: which module provides it? bottom_tabs β€” Tabs in a bar at the bottom of the app ? Settings screen: which module provides it? settings β€” Settings screen with the settings of the modules ? Onboarding screen: which module provides it? onboarding β€” Onboarding on the first launch of the app ? Localization: which module provides it? gen_l10n β€” Texts in ARB files with gen-l10n of Flutter ? Theme: which module provides it? material_theme β€” Light and dark Material 3 themes with a palette and a bundled font ? Push messages: which module provides it? None ? Notifications: which module provides it? None ? Dependency injection: which module provides it? get_it β€” Service locator with get_it ? State management: which module provides it? None ? Events: which module provides it? event_bus β€” Events between parts of the app with event_bus ? Authentication: which module provides it? None ? REST API: which module provides it? None ? Purchases: which module provides it? None ? Values in .env: which module provides it? None ? Crash reporting: which module provides it? none ? Analytics: which module provides it? none ? App icon: which module provides it? launcher_icons β€” App icon from assets/branding with flutter_launcher_icons ? Splash screen: which module provides it? native_splash β€” Light and dark splash screen from assets/branding with flutter_native_splash ? CI: which module provides it? None βœ“ Checking the machine (5ms) Adding flutter_core: the only provider of the app entry role, which every app needs. Adding go_router: the only provider of the router role, which home requires. Adding shared_preferences: the only provider of the preferences role, which onboarding requires. βœ“ Rendering the app (0.2s) βœ“ Getting the packages of the app (1.3s) ? Making the app icon from assets/branding (dart tool/update_app_icon.dart), for launcher_icons. Run it now? Yes βœ“ Making the app icon from assets/branding (1.3s) ? Making the splash screen from assets/branding (dart run flutter_native_splash:create), for native_splash. Run it now? Yes βœ“ Making the splash screen from assets/branding (1.3s) βœ“ Cleaning up the imports (1.8s) βœ“ Applying dart fix (0.8s) βœ“ Formatting the code (0.2s) βœ“ Getting the packages of the app in its directory (1.0s) Created my_app in /Users/you/projects/my_app. Run it: cd /Users/you/projects/my_app flutter run ``` A short note with links to the community follows. ### The questions | Question | What the answer does | | --- | --- | | App name | The default is `my_app`. The name becomes the Dart package name of the app in snake_case, so `My App` becomes `my_app`, and it names the app's directory. | | Organization | Reverse domain notation, `com.example` by default. It starts the identifiers of the app: `com.example.my_app` on Android and `com.example.my-app` on iOS, where bundle identifiers take no underscores. | | Features, Infrastructure | These list the modules that provide no role, grouped by their kind. Select any number of them, or none. `home` is selected already, so Enter takes it, and the app starts on it. | | One question per role | Each lists the modules that provide the role, such as the layout, the onboarding screen or dependency injection. A role that an app has at most one of also offers None, and Enter takes its first module. For crash reporting and analytics you can select several modules, or none. The roles come in an [order](https://doc.saymyframe.com/guides/smf-create.md#the-order-of-the-roles) that goes from what the user of the app sees to what gets the app released. | A role may ask one more question once the modules are known. With the feature `sign_in`, or another module that brings the authentication, `smf create` asks who may use the app without an account: nobody, everyone, or everyone as an anonymous user. See [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#the-mode). A role that the modules you picked require offers no None. When only one module provides it, SMF adds that module without asking and tells you why. Here the start screen requires a router, so SMF adds `go_router`. The layout, the settings screen and the onboarding screen require the router too, which is why SMF asks about them first. The onboarding, the theme and the localization require the preferences, which remember what the user chose. Only `shared_preferences` provides them, so SMF adds it without a question here. Push messages require the notifications, so the question of push messages comes before the one of the notifications. Use the arrow keys to move, the space bar to select in a list that takes several answers, and Enter to confirm. Ctrl-C cancels the run at any question and leaves nothing behind. ### What happens next After the questions, SMF renders the app in memory and writes it to a temporary directory. There it gets the packages with `flutter pub get`, runs the setup steps of the modules, cleans up the imports, applies `dart fix` and formats the code. Then it moves the app to its directory and gets the packages again, because Flutter writes the path of the app into some files. If `flutter pub get` or a step that the app cannot do without fails, the app stays in the temporary directory, and the error says where. A step that the app can do without, such as the tool that makes the app icon or the configuration of Firebase, is left for later with its command instead, and a failure of `dart fix` or `dart format` is only a warning. ## Pass everything as options You can give every answer on the command line instead. This command generates the same app without asking anything: ```bash smf create my_app --org com.example -m home,bottom_tabs,settings,onboarding,gen_l10n,material_theme,get_it,event_bus,launcher_icons,native_splash --no-input ``` - `-m` lists the modules, separated by commas, in the order of the answers above. SMF adds what they need, such as the router for `home`. - `--org` sets the organization. Without it, the organization is `com.example`. - `--no-input` turns the questions off. A run that would have to ask stops with an error that names the option to add. Such a run takes only the modules that it was given, so `home` is in the list too. A run without a terminal, as in a script or in CI, asks nothing either. See the [`smf create` reference](https://doc.saymyframe.com/guides/smf-create.md) for every option. ## Run the app ```bash cd my_app flutter run ``` On its first launch, the app shows the [onboarding](https://doc.saymyframe.com/modules/onboarding.md): two pages, with Skip above them and Next below. Skip, or Get started on the last page, ends it, and the app opens on the [start screen](https://doc.saymyframe.com/modules/home.md). That screen greets you, names the app and lists three next steps, the first of which is to replace it with a screen of your own. At the bottom are two tabs, Home and Settings. Under Settings, the user chooses the language, English or Ukrainian, and the theme mode, and the app remembers both. The next launch opens on the start screen right away. `flutter run` builds the flavor `dev`, which installs as My App Dev under the id `com.example.my_app.dev`, next to the other two [flavors](https://doc.saymyframe.com/guides/flavors.md). The icon and the splash screen show the mark of Say My Frame until you [replace them](https://doc.saymyframe.com/guides/app-icon-and-splash.md). [Video: A walk through a generated app on an iPhone: the three pages of the onboarding, the second of which asks to turn on notifications and is passed with Not now, the start screen with its next steps, the settings screen with the entries Theme, Language and Notifications, a tap on Dark that puts the app into the dark theme, and the sheet of the languages, where a tap on Π£ΠΊΡ€Π°Ρ—Π½ΡΡŒΠΊΠ° puts the app into Ukrainian](https://doc.saymyframe.com/demo/0.8/app_tour.mp4) A walk through an app with these screens and with [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md), recorded on an iPhone simulator. So its onboarding has three pages, with a page between the two of this app that asks to turn on notifications, and its settings screen has the row Notifications too. Its modules were chosen in another order, so its settings screen has Theme above Language. An app with no screen to start on, such as an app without a feature, opens on the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen), which names the app and tells you where its first screen goes. With `gen_l10n`, such an app is in English and in Ukrainian too. For iOS builds with Xcode 27 and Flutter 3.44, see [troubleshooting](https://doc.saymyframe.com/guides/troubleshooting.md#ios-builds-with-xcode-27). ## Next - [Take a tour of the app](https://doc.saymyframe.com/getting-started/generated-app.md) to see what each module added. - To give the app sign-in, add `sign_in` and a state manager to `-m`, as in `-m home,sign_in,bloc,bottom_tabs`, and `google_sign_in` and `apple_sign_in` for sign-in with Google and Apple. Such an app signs in with Firebase Authentication, so it needs a Firebase project before it runs; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md). - To give the app notifications, add `local_notifications`, and `firebase_messaging` for push messages; see [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md). - To make requests to your API, add `dio`, and fill in its address in `.env`; see [REST API](https://doc.saymyframe.com/guides/rest.md). - To run the checks on each push and build an APK on request, add `github_actions`; see [CI](https://doc.saymyframe.com/guides/ci.md). - To sell premium access, add `paywall` and a state manager, as in `-m home,paywall,bloc,bottom_tabs`. The app sells the plans of a RevenueCat project, and a debug build buys in the Test Store of RevenueCat once its API key is in `.env`; see [Purchases](https://doc.saymyframe.com/guides/purchases.md). # Tour of a generated app Source: https://doc.saymyframe.com/getting-started/generated-app This tour uses the app from [Create your first app](https://doc.saymyframe.com/getting-started/first-app.md): ```bash smf create my_app --org com.example -m home,bottom_tabs,settings,onboarding,gen_l10n,material_theme,get_it,event_bus,launcher_icons,native_splash --no-input ``` The app has thirteen modules: the ten in `-m`, and three that SMF added. `go_router` is there because `home` needs a router, `shared_preferences` because the onboarding, the theme and the language are remembered, and `flutter_core` because every app has it. ## What you see when it runs On its first launch, the app shows the onboarding: a welcome page and a second page, each a cell of the periodic table with a title and a text below it. Skip is above the pages and Next below them, and on the last page the button is Get started. Once the onboarding is finished, the app shows the home screen, which welcomes the developer of the app and lists three next steps. At the bottom are two tabs, Home and Settings. The settings screen has a large title and two settings in one group: Language, a row that opens a sheet with the languages, and Theme, with a segment for each mode. The app is in English or in Ukrainian, in the language of the device, until the user chooses one of the two under Language. Later launches open on the home screen, in the theme mode and the language that the user chose. ![The first page of the onboarding, with the symbol of the app in a cell.](https://doc.saymyframe.com/demo/0.8/app_1_onboarding_welcome.png) ![The home screen in the light theme and in English, with Good afternoon above the name of the app, above the tabs Home and Settings.](https://doc.saymyframe.com/demo/0.8/app_4_home.png) ![The home screen in the dark theme and in Ukrainian, with Π”ΠΎΠ±Ρ€ΠΈΠΉ дСнь above the name of the app, after the user chose both under Settings.](https://doc.saymyframe.com/demo/0.8/app_9_home_dark_uk.png) ## The files ```text my_app/ β”œβ”€β”€ .gitignore β”œβ”€β”€ .metadata β”œβ”€β”€ AGENTS.md β”œβ”€β”€ CLAUDE.md β”œβ”€β”€ README.md β”œβ”€β”€ analysis_options.yaml β”œβ”€β”€ flutter_launcher_icons.yaml β”œβ”€β”€ flutter_native_splash.yaml β”œβ”€β”€ l10n.yaml β”œβ”€β”€ pubspec.yaml β”œβ”€β”€ android/ Android project of flutter create, with the flavors β”œβ”€β”€ assets/ β”‚ β”œβ”€β”€ branding/ the images of the icon and the splash screen β”‚ └── fonts/geist/ the font of the themes, with its license β”œβ”€β”€ ios/ iOS project of flutter create, with the flavors β”œβ”€β”€ lib/ β”‚ β”œβ”€β”€ main.dart β”‚ β”œβ”€β”€ bootstrap.dart β”‚ β”œβ”€β”€ app.dart β”‚ β”œβ”€β”€ core/ β”‚ β”‚ β”œβ”€β”€ app/status_bar_icons.dart β”‚ β”‚ β”œβ”€β”€ di/ β”‚ β”‚ β”‚ β”œβ”€β”€ service_locator.dart β”‚ β”‚ β”‚ └── dependencies.dart β”‚ β”‚ β”œβ”€β”€ events/ β”‚ β”‚ β”‚ β”œβ”€β”€ communication_service.dart β”‚ β”‚ β”‚ └── event_bus_communication_service.dart β”‚ β”‚ β”œβ”€β”€ l10n/ β”‚ β”‚ β”‚ β”œβ”€β”€ app_locale.dart β”‚ β”‚ β”‚ β”œβ”€β”€ language_setting.dart β”‚ β”‚ β”‚ └── l10n.dart β”‚ β”‚ β”œβ”€β”€ layout/ β”‚ β”‚ β”‚ β”œβ”€β”€ destination.dart β”‚ β”‚ β”‚ └── app_shell.dart β”‚ β”‚ β”œβ”€β”€ onboarding/onboarding_steps.dart β”‚ β”‚ β”œβ”€β”€ preferences/ β”‚ β”‚ β”‚ β”œβ”€β”€ app_preferences.dart β”‚ β”‚ β”‚ └── shared_app_preferences.dart β”‚ β”‚ β”œβ”€β”€ router/ β”‚ β”‚ β”‚ β”œβ”€β”€ app_router.dart β”‚ β”‚ β”‚ β”œβ”€β”€ navigation.dart β”‚ β”‚ β”‚ └── app_router_factory.dart β”‚ β”‚ └── theme/ β”‚ β”‚ β”œβ”€β”€ app_theme.dart β”‚ β”‚ β”œβ”€β”€ theme_mode.dart β”‚ β”‚ └── theme_mode_setting.dart β”‚ β”œβ”€β”€ features/ β”‚ β”‚ β”œβ”€β”€ home/ β”‚ β”‚ β”‚ β”œβ”€β”€ assets/ the image of the home screen β”‚ β”‚ β”‚ └── home_screen.dart β”‚ β”‚ β”œβ”€β”€ onboarding/ β”‚ β”‚ β”‚ β”œβ”€β”€ onboarding_screen.dart β”‚ β”‚ β”‚ β”œβ”€β”€ onboarding_pages.dart β”‚ β”‚ β”‚ └── onboarding_status.dart β”‚ β”‚ └── settings/settings_screen.dart β”‚ └── l10n/ β”‚ β”œβ”€β”€ app_en.arb β”‚ └── app_uk.arb β”œβ”€β”€ test/ β”‚ └── core/app/status_bar_icons_test.dart └── tool/ └── update_app_icon.dart ``` `flutter pub get` adds `pubspec.lock` and `.dart_tool/`, as in any Flutter project. In this app it also generates `lib/l10n/app_localizations.dart` and a file for each language next to it, from the ARB files, and adds `build/`, where Flutter keeps the records of that step. Every file has exactly one author. Some files come from a module, and others come from a role, whichever module provides it. A role describes what the rest of the app can count on, such as a router with typed navigation, and generates that part itself. The module that provides the role fills in the rest. | Files | Written by | | --- | --- | | `main.dart`, `bootstrap.dart`, `app.dart`, `pubspec.yaml`, `analysis_options.yaml`, `README.md`, `.gitignore`, `.metadata`, `android/`, `ios/` | the module `flutter_core`, which provides the app entry | | `AGENTS.md`, `CLAUDE.md`, `core/app/status_bar_icons.dart`, `test/` | the app entry role | | `core/router/app_router.dart`, `core/router/navigation.dart` | the router role | | `core/router/app_router_factory.dart` | the module `go_router`, which provides the router | | `assets/branding/icon.png`, `assets/branding/icon_foreground.png`, `flutter_launcher_icons.yaml`, `tool/update_app_icon.dart` | the module `launcher_icons`, which provides the app icon | | `assets/branding/splash_light.png`, `assets/branding/splash_dark.png`, `flutter_native_splash.yaml` | the module `native_splash`, which provides the splash screen | | `core/layout/destination.dart` | the layout role | | `core/layout/app_shell.dart` | the module `bottom_tabs`, which provides the layout | | `core/onboarding/onboarding_steps.dart` | the onboarding screen role | | `core/preferences/app_preferences.dart` | the preferences role | | `core/preferences/shared_app_preferences.dart` | the module `shared_preferences`, which provides the preferences | | `core/l10n/app_locale.dart`, `core/l10n/language_setting.dart` | the localization role | | `core/l10n/l10n.dart`, `l10n/*.arb`, `l10n.yaml` | the module `gen_l10n`, which provides the localization | | `core/theme/theme_mode.dart`, `core/theme/theme_mode_setting.dart` | the theme role | | `core/theme/app_theme.dart`, and `assets/fonts/geist/` at the root of the app | the module `material_theme`, which provides the theme | | `core/di/service_locator.dart` | the dependency injection role | | `core/di/dependencies.dart` | the module `get_it`, which provides dependency injection | | `core/events/communication_service.dart` | the events role | | `core/events/event_bus_communication_service.dart` | the module `event_bus`, which provides the events | | `features/home/` | the feature `home` | | `features/onboarding/` | the module `onboarding`, a feature that provides the onboarding screen | | `features/settings/settings_screen.dart` | the module `settings`, a feature that provides the settings screen | This split lets modules replace each other. Code that navigates uses `navigation.dart` of the router role and not go_router, code that needs a service uses `service_locator.dart` and not get_it, and code that remembers a setting uses `app_preferences.dart` and not the shared_preferences package. ## Start-up `lib/main.dart` has the same three steps in every app. Modules and roles can wrap the root widget, and here the localization role and the theme role each put a scope around it, through which the root reads the language and the theme mode: ```dart title="lib/main.dart" Future main() async { WidgetsFlutterBinding.ensureInitialized(); await bootstrap(); runApp( AppLocaleScope( notifier: appLocale, child: AppThemeModeScope(notifier: appThemeMode, child: const App()), ), ); } ``` `bootstrap()` runs the start-up code of modules and roles before the first frame. They add their code to one of four phases, which run in this order: code that must come first, platform services such as Firebase, the services of the app, and code that needs those services. In this app, the preferences role opens the preferences in the platform phase, and the dependency injection role registers the services after it: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await initPreferences(); await registerDependencies(); } ``` `initPreferences()` also gives the preferences to the code that keeps a setting there. So the theme mode, the language and whether the onboarding is finished have their saved values before the first frame. With `firebase_crashlytics`, the platform phase would also initialize Firebase and install the crash reporting. ```mermaid sequenceDiagram participant main as main() participant boot as bootstrap() participant app as App main->>main: WidgetsFlutterBinding.ensureInitialized() main->>boot: await bootstrap() Note over boot: early phase Note over boot: platform phase: await initPreferences() Note over boot: DI phase: await registerDependencies() Note over boot: late phase boot-->>main: done main->>app: runApp(wrappers of the modules around App) app->>app: MaterialApp.router(routerConfig: appRouter.config) ``` `lib/app.dart` holds the root widget. With a router it is a `MaterialApp.router` with the router's configuration. Without one, it is a `MaterialApp` that shows the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen), which only an app that no route starts has. The theme role and the localization role give it its other arguments: ```dart title="lib/app.dart" @override Widget build(BuildContext context) => MaterialApp.router( title: 'My App', theme: createLightTheme(context), darkTheme: createDarkTheme(context), themeMode: AppThemeModeScope.of(context), locale: AppLocaleScope.of(context), localizationsDelegates: [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: [...appLocales], routerConfig: appRouter.config, builder: (context, child) => StatusBarIcons(child: child!), ); ``` The `builder` of the root widget wraps the content of every route. The widget there comes from the app entry role, in every app: `StatusBarIcons` of `lib/core/app/status_bar_icons.dart` tells the system whether the status bar needs dark or light icons, by the theme, so the status bar can be read over a screen without an app bar. A screen with an `AppBar` gets the icons that suit its bar. Modules put wrappers of their own there through the [socket](https://doc.saymyframe.com/concepts/sockets.md#the-sockets-of-the-app-entry) `appBuilder`. ## Router and navigation The router role generates two files. `app_router.dart` has the `AppRouter` interface and the instance `appRouter`, which `createAppRouter()` creates on first use. `navigation.dart` has the typed navigation: a location class for every route, such as `HomeHomeLocation` for `/home`, and `context.nav`, so a screen navigates with `context.nav.home.home().go()`. `go_router` implements `createAppRouter()` in `app_router_factory.dart` with a `GoRouter` that has every route of every feature, the redirect of `/` to the start screen and, with a layout, the tabs. The routes of each feature live under its id, so the route `/` of `home` is `/home`. See [Navigation](https://doc.saymyframe.com/guides/navigation.md). The onboarding declares a guard, and in an app with guards `app_router.dart` also has `routeGuards`. While the onboarding is not finished, the router shows `/onboarding` in place of every other location. See [Guards](https://doc.saymyframe.com/guides/navigation.md#guards). ## Layout The layout role generates `destination.dart` with `Destination`, which holds an icon and a function that returns the label, and `appDestinations`, the destinations of the app: ```dart title="lib/core/layout/destination.dart" const List appDestinations = [ Destination(label: _homeHomeLabel, icon: Icons.home), Destination(label: _settingsSettingsLabel, icon: Icons.settings), ]; String _homeHomeLabel(BuildContext context) => context.l10n.homeLabel; String _settingsSettingsLabel(BuildContext context) => context.l10n.settingsTitle; ``` `bottom_tabs` generates `AppShell`, a `Scaffold` with the screen of the selected tab and a bar with a tab for each destination, which the file draws itself in the colors of the theme. The router gives it `appDestinations`, in the order of the features, and keeps the stack of each tab while another one is selected. A label is a text of the feature of its tab, so the tabs follow the language of the app. ## Preferences and settings The preferences role generates `app_preferences.dart` with the `AppPreferences` interface, and `shared_preferences` implements it on the shared_preferences package. Code that keeps a setting gives the role a restorer, a function that reads the setting when the app starts. This app has three: ```dart title="lib/core/preferences/app_preferences.dart" final List _restorers = [ restoreOnboarding, restoreAppLocale, restoreAppThemeMode, ]; ``` `settings` generates the settings screen, which shows the entries that the roles and the modules of the app give it, in one group below its title. Here the localization role gives the entry Language and the theme role the entry Theme, in the order of the modules that provide the two roles. See [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md). ## Texts and languages Each module and role gives its texts to the localization role, in English and in the languages that it has them in. `gen_l10n` keeps them in ARB files, one for each language, from which Flutter generates the code that reads them. The texts of this app are in English and in Ukrainian: the label of the tab Home and the texts of the home screen, the texts of the onboarding, and the title of the settings screen and the texts of its entries. `app_locale.dart` of the role has the languages of the app, `appLocales`, and the language that the user chose, `appLocale`. Code reads a text as `context.l10n.`. See [Languages](https://doc.saymyframe.com/guides/languages.md). ## Theme `material_theme` generates `app_theme.dart` with the light and the dark theme of the app: their colors, their text styles and the look of their components. It is the file to change for another look. The themes are in the font Geist, whose files the module puts into `assets/fonts/geist/` and declares in `pubspec.yaml`, so the app loads no font from the network. The theme role generates `theme_mode.dart`, which keeps the mode that the user selected, and the row Theme of the settings screen. See [Theme](https://doc.saymyframe.com/guides/theme.md). ## Dependency injection The dependency injection role generates `service_locator.dart` with the `ServiceLocator` interface and the function `resolve()`. `get_it` generates `dependencies.dart`, whose `registerDependencies()` registers the services of all modules in get_it: ```dart title="lib/core/di/dependencies.dart" Future registerDependencies() async { final getIt = GetIt.instance; getIt.registerLazySingleton( () => di0.createCommunicationService(), ); getIt.registerLazySingleton( () => di1.createAppPreferences(), ); } ``` The events role and the preferences role registered their services here because the app has a container. Without one, the app would get the event service from `createCommunicationService()`. See [Services and state](https://doc.saymyframe.com/guides/services.md). ## Events The events role generates `communication_service.dart` with `AppEvent`, the base class of events, and the `CommunicationService` interface. Its `fire(event)` sends an event, and `on()` streams the events of a type. `event_bus` implements the interface on the `EventBus` of the [event_bus](https://pub.dev/packages/event_bus) package. ## The features Features keep their files in `lib/features//`: - `home` adds `home_screen.dart`, a welcome to the developer of the app that names the app and lists the next steps, and the image that the screen shows, in `assets/` next to it. Replace the content of the screen with the first screen of your app. The module declares one route, `/home`, which is a destination labelled Home and a screen that the app can start on. See [`home`](https://doc.saymyframe.com/modules/home.md). - `onboarding` adds the screen of the onboarding at `/onboarding`, its pages and its status. Replace the pages with your own in `onboarding_pages.dart`. The module provides the onboarding screen role, whose template writes `lib/core/onboarding/onboarding_steps.dart` with the steps that other modules add to the onboarding, such as a page that asks for the permission to show notifications. In this app the list is empty. See [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md). - `settings` adds the settings screen at `/settings`, which is a destination too. ## The rest of the project - `pubspec.yaml` has the dependencies of all modules: `event_bus`, `get_it`, `go_router`, `intl` and `shared_preferences` here, next to Flutter's own. `shared_preferences` also keeps `shared_preferences_android` at 2.5.2 or later; see [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md). Its `flutter` section declares the image of the home screen, and the font of the themes with its license. The app needs Flutter 3.44 or newer and Dart 3.12 or newer. - `analysis_options.yaml` has the lints of a new Flutter app, `flutter_lints`, and leaves `build/` out of the analysis. On macOS, Flutter copies the Swift packages of plugins there, with their examples, and `flutter analyze` would report those otherwise. - `android/` and `ios/` are the projects of `flutter create` of Flutter 3.44, with the app's identifiers, `com.example.my_app` on Android and `com.example.my-app` on iOS, and the [flavors](https://doc.saymyframe.com/guides/flavors.md) `dev`, `staging` and `prod`, which add `.dev` and `.staging` to them. `flutter run` builds `dev`. - `launcher_icons` and `native_splash` add the four images of `assets/branding/`, `flutter_launcher_icons.yaml`, `flutter_native_splash.yaml` and `tool/update_app_icon.dart`, and their tools make the icon and the launch screen in the native projects. See [App icon and splash screen](https://doc.saymyframe.com/guides/app-icon-and-splash.md). The minimum iOS version is 15.0. The iOS app signs with `ios/Runner/Runner.entitlements`, which is empty in this app. - `README.md` has the name of the app and the line "Generated with Say My Frame", which links to this site. The line lets a search on GitHub find the apps that Say My Frame generated, and you can remove it. Modules and roles add sections to the README. Here `gen_l10n` tells where the texts are, under "Texts", and the localization role how to add a language, under "Languages". The README of an app with steps that only you can do, such as uploading a key to the Firebase console, opens with the section "Finish the setup": the steps in order, with a link to their [guides](https://doc.saymyframe.com/setup.md). This app has none. - `test/` has a widget test of `StatusBarIcons`, which every app has. An app that no route starts also has the fallback start screen and a test of it. This app starts on `/home`, so it has neither; see [`flutter_core`](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen). ## The guide for coding agents `AGENTS.md` tells coding agents what the code of the app does not show, and `CLAUDE.md` holds one line, `@AGENTS.md`, for the agents that read that file instead. The app entry role generates both in every app, whichever module provides it. The guide has a section for each part of the app that has notes for agents. In this app those are the app entry, the dependency injection, the events, the home screen, the layout, the localization, the onboarding, the onboarding screen, the preferences, the router, the settings screen and the theme. The section of the router, for one, tells an agent to navigate with `context.nav` and names the three places that a route is in. See [Working with a coding agent](https://doc.saymyframe.com/guides/coding-agents.md). ## It is your code now SMF generates the app once, and the result is a plain Flutter project. It has no SMF package in its dependencies, and no command updates it later, so change any file as you would in a project you wrote yourself. To add a screen later, see [Routes of your own](https://doc.saymyframe.com/guides/navigation.md#routes-of-your-own). ## Next - [Choosing modules](https://doc.saymyframe.com/guides/choosing-modules.md) shows what else a generated app can have, such as the screens of [sign-in](https://doc.saymyframe.com/guides/sign-in.md). - [The module model](https://doc.saymyframe.com/concepts/module-model.md) explains how the modules fit together without knowing each other. # Finish the setup Source: https://doc.saymyframe.com/setup Some of the setup of an app happens in your Apple Developer account, in App Store Connect, in Google Play Console, in the Firebase console and in the RevenueCat dashboard, where no command of SMF can reach: a key that only you can download, a switch in a console, the products that the app sells, the fingerprints of your release keys. `smf create` does everything else. At the end it says how many such steps are left and prints a link to this page, and the README of the app lists them in its section "Finish the setup". Each step has its own page with a click-by-click guide. The link of your app lists its steps in the order to do them, and each guide leads on to the next one. Do the steps once the commands that `smf create` left for later have run, such as `dart tool/configure_firebase.dart dev`. Mark each step as done as you go, here or in its guide: this browser remembers the marks. Your app has the [flavors](https://doc.saymyframe.com/guides/flavors.md) `dev`, `staging` and `prod`, each with an id of its own, and a service knows each id as an app of its own. So repeat a step for each flavor that needs it. Each guide says what repeats. A flavor that never reaches a store or a real user may need none of it. ## Sign the iOS app - [In Xcode, sign the iOS app with your paid Apple Developer team](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md): the step `app_entry.ios_app_id`, for [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md), [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md). ## Sign-in - [Turn on Sign in with Apple in Firebase Authentication](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md): the step `firebase_auth.apple_provider`, for [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md). - [Give Firebase your Sign in with Apple key, so that deleting an account works](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md): the step `firebase_auth.apple_revocation`, for [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md). - [Before releasing on Google Play, give Firebase the SHA of your release keys](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md): the step `firebase_auth.google_release_sha`, for [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md). ## Push messages - [Give Firebase your Apple push key (APNs key)](https://doc.saymyframe.com/setup/firebase-messaging-apns-key.md): the step `firebase_messaging.apns_key`, for [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md). ## Google Analytics - [Turn on Google Analytics in the Firebase project, unless it is on already](https://doc.saymyframe.com/setup/firebase-analytics-google-analytics.md): the step `firebase_analytics.google_analytics`, for [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md). ## Purchases - [Set up payments in App Store Connect and Google Play Console](https://doc.saymyframe.com/setup/purchases-store-agreements.md): the step `purchases.store_agreements`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). - [Create the products of your plans in App Store Connect and Google Play Console](https://doc.saymyframe.com/setup/purchases-store-products.md): the step `purchases.store_products`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). - [Set up the entitlement premium and the default offering in RevenueCat](https://doc.saymyframe.com/setup/revenuecat-entitlement-and-offering.md): the step `revenuecat.entitlement_and_offering`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). - [Copy the API keys of your RevenueCat apps into .env](https://doc.saymyframe.com/setup/revenuecat-api-keys.md): the step `revenuecat.api_keys`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). - [Give RevenueCat your In-App Purchase key from App Store Connect](https://doc.saymyframe.com/setup/revenuecat-app-store-key.md): the step `revenuecat.app_store_key`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). - [Give RevenueCat access to Google Play with a service account](https://doc.saymyframe.com/setup/revenuecat-play-service-account.md): the step `revenuecat.play_service_account`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). - [Publish your terms of use and privacy policy and put their links into .env](https://doc.saymyframe.com/setup/paywall-legal-pages.md): the step `paywall.legal_pages`, for [`paywall`](https://doc.saymyframe.com/modules/paywall.md). # In Xcode, sign the iOS app with your paid Apple Developer team Source: https://doc.saymyframe.com/setup/app-entry-ios-app-id The step `app_entry.ios_app_id`, for [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md), [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md). Push messages and Sign in with Apple are capabilities of the iOS app. Apple grants them to an App ID, the bundle id of the app registered in a team, and only a paid Apple Developer team can have such an App ID. A free personal team cannot sign the app with them, and Xcode stops with an error about the entitlement. The easiest way to get the App ID is to let Xcode sign the app once with your paid team: Xcode registers the bundle id and turns on the capabilities that the app asks for. Each [flavor](https://doc.saymyframe.com/guides/flavors.md) has a bundle id of its own, such as `com.example.my-app.dev` for `dev` and `com.example.my-app` for `prod`, and each needs its App ID. Xcode registers the one of the scheme that you build, so build the scheme of each flavor that you put on a device or release. The section "Flavors" of the README of the app lists the bundle ids. :::note A bundle id is unique across all Apple developers, and ids under `com.example` are usually taken. Generate the app with your own organization, such as `smf create my_app --org com.yourcompany`, so that the bundle id is yours. The screenshots show the example bundle id `com.example.my-app` and the example Team ID `SAYMYFRAME`. The orange frames mark what to click or check, in the order of their numbers. ::: **1. Sign the app in Xcode.** Open `ios/Runner.xcworkspace` of the app in Xcode. Select **Runner** in the project navigator, then the target **Runner** (1), then the tab **Signing & Capabilities** (2). Keep **Automatically manage signing** checked and choose your paid team under **Team** (3). If the team is missing, add your Apple Account in **Xcode > Settings > Accounts**. ![Signing and Capabilities of the target Runner in Xcode, with the target marked 1, the tab marked 2 and the team Say My Frame marked 3, and the capabilities Background Modes, Push Notifications and Sign In with Apple below the signing](https://doc.saymyframe.com/assets/images/xcode-signing-a467cc5bfcf6b9b201d5bf4e7a1b6afc.png) Xcode registers the App ID and shows no error once the signing works. The capabilities of the app, such as **Push Notifications** and **Sign in with Apple**, are listed below the signing. **2. Check the App ID.** In [your Apple Developer account](https://developer.apple.com/account), under **Certificates, IDs & Profiles**, click **Identifiers** (1). ![Program resources of the account, with Identifiers under Certificates, IDs and Profiles marked 1](https://doc.saymyframe.com/assets/images/account-identifiers-92d462060bfddc5feeb910f15351e45c.png) The bundle id of the app is in the list. An App ID that Xcode registered has a name that starts with `XC`. Click it (2). ![The Identifiers page, with the App ID My App of the identifier com.example.my-app marked 2](https://doc.saymyframe.com/assets/images/app-ids-list-e3ebddaca32fda216aa1bbad8060d11a.png) The capabilities that the app uses are checked: **Push Notifications** (1) for push messages and **Sign In with Apple** (2) for Sign in with Apple. ![Edit your App ID Configuration, with the checked Push Notifications marked 1 and the checked Sign In with Apple marked 2](https://doc.saymyframe.com/assets/images/app-id-capabilities-7d476ea850d0c1ea4ad5efdee69f567c.png) If one is not checked, check it and click **Save**, then sign the app in Xcode again. ## Without Xcode You can also register the App ID yourself and then choose the team in Xcode. On the **Identifiers** page, click the **+** next to the title. Choose **App IDs** (1) and click **Continue** (2), then choose **App** and click **Continue** again. ![Register a new identifier, with App IDs selected and marked 1, and Continue marked 2](https://doc.saymyframe.com/assets/images/new-identifier-app-ids-cb002ae916482e46936d8ab8b88e90ea.png) Enter a description (1), such as `My App`. Keep **Explicit** and enter the bundle id of the app (2), which Xcode shows under **Bundle Identifier** on the tab **Signing & Capabilities**. Then check the capabilities that the app uses in the list below the form, click **Continue** (3) and **Register**. ![Register an App ID, with the description My App marked 1, the explicit bundle id com.example.my-app marked 2 and Continue marked 3](https://doc.saymyframe.com/assets/images/register-app-id-4f6080905e2db19325c712ce826290a0.png) # Turn on Sign in with Apple in Firebase Authentication Source: https://doc.saymyframe.com/setup/firebase-auth-apple-provider The step `firebase_auth.apple_provider`, for [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md). The app lets users sign in with Apple through Firebase Authentication. No command can turn Apple on there, so you do it in the Firebase console, once for each Firebase project that your [flavors](https://doc.saymyframe.com/guides/flavors.md) sign in with Apple through. Until then, a sign-in with Apple fails with the reason `notConfigured`, and the message for the developer says what to enable. The iOS app also needs **Sign In with Apple** on its App ID, which signing the app in Xcode with a paid team gives it; see [the step about the App ID](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md). :::tip The screenshots show the example Firebase project `my-app-12345`. The orange frames mark what to click, in the order of their numbers. ::: **1. Open Authentication.** In the [Firebase console](https://console.firebase.google.com/), open your project and click **Authentication** in the menu on the left (1). If it is not among the shortcuts there, it is under **Security**. Open the tab **Sign-in method** (2). If the page offers **Get started** instead, click it first: Authentication was never set up in this project. ![The menu of the Firebase console with Authentication marked 1, and the tab Sign-in method marked 2](https://doc.saymyframe.com/assets/images/auth-sign-in-method-tab-ad3756b67f7f30bfc7045dfe5272ee9a.png) ![Authentication in a project where it was never set up, with the button Get started marked 1](https://doc.saymyframe.com/assets/images/auth-get-started-d7a8945334b1350f2ff23b78f14bf4cf.png) **2. Add Apple.** Click **Add new provider** (3). ![The list of sign-in providers, with the button Add new provider marked 3](https://doc.saymyframe.com/assets/images/auth-add-new-provider-a22ed32afd7a2b8b2bb1f29d2ed5e957.png) Under **Additional providers**, click **Apple** (4). ![Select a sign-in provider, with Apple among the additional providers marked 4](https://doc.saymyframe.com/assets/images/auth-pick-apple-8eae3646437f5c9c16a0d90cbf88dd6c.png) **3. Enable it.** Turn on **Enable** (1) and click **Save** (2). An iOS app needs nothing else here: leave **Services ID** empty for now. The step about deleting accounts fills it in. ![The settings of the Apple provider, with the switch Enable marked 1 and the button Save marked 2](https://doc.saymyframe.com/assets/images/apple-enable-25cf32b29ccab7b84098078ab6d3fbe4.png) **Check.** Apple is in the list of providers with the status **Enabled**. Sign in with Apple in the app on an iPhone or a simulator with an Apple Account. On a simulator, sign in to the Apple Account in the Settings app of the simulator first. # Give Firebase your Sign in with Apple key, so that deleting an account works Source: https://doc.saymyframe.com/setup/firebase-auth-apple-revocation The step `firebase_auth.apple_revocation`, for [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md). When a user who signs in with Apple deletes the account, the app revokes the tokens that Apple gave it, as the App Store asks of every app with Sign in with Apple (App Store Review Guideline 5.1.1(v)). Firebase revokes them with a key for Sign in with Apple and a Services ID of your team. Until you give Firebase both, deleting such an account fails with the reason `notConfigured`, and the account stays. Firebase then answers `Code flow is not enabled for Apple`. You make a key and a Services ID in your Apple Developer account, then enter both in the settings of the Apple provider in Firebase. If your [flavors](https://doc.saymyframe.com/guides/flavors.md) have Firebase projects of their own, enter them in each project that signs in with Apple. Turn on the Apple provider first; see [the step about it](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md). :::tip The screenshots use example values: the Team ID `SAYMYFRAME`, the Key ID `SMFSIWAKEY`, the bundle id `com.example.my-app`, the Services ID `com.example.my-app.signin` and the Firebase project `my-app-12345`. Your Team ID is under **Membership details** in your Apple Developer account. The orange frames mark what to click or fill in, in the order of their numbers. ::: ## 1. A key for Sign in with Apple In [your Apple Developer account](https://developer.apple.com/account), open **Certificates, IDs & Profiles**, then **Keys**, and click the **+** next to the title. Name the key (1), such as `My App Sign in with Apple`, check **Sign in with Apple** (2) and click **Configure** (3) in its row. ![Register a New Key, with the name My App Sign in with Apple marked 1, the checked Sign in with Apple marked 2 and its Configure button marked 3](https://doc.saymyframe.com/assets/images/new-key-siwa-a88d93dd91a45e93a46d16cb00f226fb.png) Choose the App ID of the app as the **Primary App ID** (1) and click **Save** (2). ![Configure Key, with the primary App ID My App, SAYMYFRAME.com.example.my-app, marked 1 and Save marked 2](https://doc.saymyframe.com/assets/images/configure-siwa-e7b32a5fbd66dfac118f61fe2f772f40.png) Click **Continue**, then **Register**. On the page of the key, copy the **Key ID** and click **Download** for the `.p8` file. :::warning Apple lets you download the file **only once**. Keep it in a password manager. The private key in it is a secret: you paste it into the Firebase console yourself, and it never goes into the app or its repository. ::: ## 2. A Services ID Open **Identifiers** and click the **+** next to the title. Choose **Services IDs** (1) and click **Continue** (2). ![Register a new identifier, with Services IDs selected and marked 1, and Continue marked 2](https://doc.saymyframe.com/assets/images/new-identifier-services-ids-d07c32dfb47b44a77bbf766da58adb44.png) Enter a description (1), such as `My App sign-in`, and an identifier (2). The bundle id of the app with `.signin` at the end is a good choice; it cannot be the bundle id itself. Click **Continue** (3), then **Register**. ![Register a Services ID, with the description My App sign-in marked 1, the identifier com.example.my-app.signin marked 2 and Continue marked 3](https://doc.saymyframe.com/assets/images/register-services-id-2579298aeab224c4bd379af86408dada.png) Switch the filter at the top right of the list from **App IDs** to **Services IDs** (1) and click the new Services ID (2). ![The Identifiers page with the filter Services IDs marked 1, and the Services ID My App sign-in marked 2](https://doc.saymyframe.com/assets/images/services-ids-list-7c430bd96f73382fa622065b7d62e024.png) Check **Sign In with Apple** (1) and click **Configure** (2). ![Edit your Services ID Configuration, with the checked Sign In with Apple marked 1 and its Configure button marked 2](https://doc.saymyframe.com/assets/images/services-id-edit-cdbe04858c1a7ece0ace25ac7e78df58.png) Choose the App ID of the app as the **Primary App ID** (1), then click the **+** next to **Website URLs** (2). ![Web Authentication Configuration, with the primary App ID marked 1 and the plus button of the website URLs marked 2](https://doc.saymyframe.com/assets/images/services-id-web-auth-11c362dcccffe97075b3f21d1a4fd627.png) Enter the domain (1) and the return URL (2) of your Firebase project, with the id of your project in place of `my-app-12345`: - **Domains and Subdomains:** `my-app-12345.firebaseapp.com` - **Return URLs:** `https://my-app-12345.firebaseapp.com/__/auth/handler` The settings of the Apple provider in Firebase show this return URL too, with a button that copies it. ![Register Website URLs, with the domain of the Firebase project marked 1, its return URL marked 2 and Next marked 3](https://doc.saymyframe.com/assets/images/services-id-urls-7c4667199f4dd8009be481e724359c38.png) Click **Next** (3), then **Done**, then **Continue**, and **Save**. ## 3. Both in Firebase In the [Firebase console](https://console.firebase.google.com/), open **Authentication**, the tab **Sign-in method**, and click **Apple** in the list of providers. Open **OAuth code flow configuration**, then fill in: 1. **Services ID:** the identifier from part 2, such as `com.example.my-app.signin`. 2. **Apple team ID:** your Team ID. 3. **Key ID:** the Key ID from part 1. 4. **Private key:** open the `.p8` file in a text editor and paste all of it, from `-----BEGIN PRIVATE KEY-----` to `-----END PRIVATE KEY-----`. ![The settings of the Apple provider, with the Services ID, the Apple team ID, the Key ID and the empty field of the private key marked 1 to 4](https://doc.saymyframe.com/assets/images/apple-code-flow-fields-17b304c08fca9174c01ede238ecd1ad0.png) Then click **Save** (5). The return URL that part 2 gives Apple is the one under the fields, which the button next to it copies. ![The bottom of the settings of the Apple provider, with the callback URL of the project and the button Save marked 5](https://doc.saymyframe.com/assets/images/apple-code-flow-save-cbfb48f00361e0b0dc6a28990f4ac706.png) **Check.** Sign in with Apple in the app, then delete the account on the screen of the account. The app deletes the account and returns to the sign-in, and the user is gone from the tab **Users** of Authentication. # Before releasing on Google Play, give Firebase the SHA of your release keys Source: https://doc.saymyframe.com/setup/firebase-auth-google-release-sha The step `firebase_auth.google_release_sha`, for [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md). Google recognizes the Android app by the SHA-1 and SHA-256 of the key that signs it. The script `dart tool/enable_firebase_sign_in.dart` registers those of the debug key of your machine, so sign-in with Google works in debug builds. Each [flavor](https://doc.saymyframe.com/guides/flavors.md) is an Android app of its own, so repeat this for each flavor that such a key signs. A release build is signed with other keys, and until Firebase knows them, sign-in with Google fails in the release, for example in a test track of Google Play. You do this once, before the first release on Google Play, and again if you change the keys. :::tip The screenshots show the example package name `com.example.my_app` and the example Firebase project `my-app-12345`. The orange frames mark what to click, in the order of their numbers. ::: **1. Find the SHA of the release keys.** With Play App Signing, which Google Play uses for every new app, two keys matter: - **The app signing key**, with which Google Play signs what it delivers to users. - **The upload key**, with which you sign what you upload to Google Play. Both are in the [Play Console](https://play.google.com/console): open the app, then **Test and release > App integrity**, then **App signing**. Copy the **SHA-1** and the **SHA-256** of both certificates. Before the app is in the Play Console, read the upload key from its keystore: ```bash keytool -list -v -keystore upload-keystore.jks -alias upload ``` **2. Add them in Firebase.** In the [Firebase console](https://console.firebase.google.com/), open your project. In the menu on the left, point at **Settings** and click **General**. Under **Your apps**, select the Android app. Under **SHA certificate fingerprints**, the debug fingerprints that the script registered are listed already. Click **Add fingerprint** (1). ![Your apps, with the Android app my_app, its SHA certificate fingerprints and Add fingerprint marked 1](https://doc.saymyframe.com/assets/images/android-sha-0295d36b27f9f62b10427ca2262388cf.png) Paste one of the fingerprints (2) and click **Save** (3). Firebase tells SHA-1 and SHA-256 apart by their length. Repeat for each of the four. ![The field Certificate fingerprint with a SHA-256 marked 2 and the button Save marked 3](https://doc.saymyframe.com/assets/images/android-add-sha-ad8b2a33d540628bb7f6eec73809c480.png) The Firebase CLI does the same, with the id of the Android app from `firebase.json` of the app: ```bash firebase apps:android:sha:create ``` **Check.** Install the release from a test track of Google Play and sign in with Google. # Give Firebase your Apple push key (APNs key) Source: https://doc.saymyframe.com/setup/firebase-messaging-apns-key The step `firebase_messaging.apns_key`, for [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md). Firebase sends push messages to iPhones through the Apple Push Notification service (APNs). For that it needs a key from your Apple Developer account. Without the key the app still gets its address for push messages, but Firebase cannot send anything to it. You need a paid Apple Developer account and access to your Firebase project. You make the key once for your team, and it works for all of its apps. The Firebase console has the upload under each Apple app of a project, and each [flavor](https://doc.saymyframe.com/guides/flavors.md) is an app of its own, in one project or in several. So check the iOS app of each flavor that you send to, and repeat the upload with the same key where it has none. :::tip The screenshots use example values: the Team ID `SAYMYFRAME`, the Key ID `SMFAPNSKEY`, the bundle id `com.example.my-app` and the Firebase project `my-app-12345`. You will see your own. The orange frames mark what to click, in the order of their numbers. ::: **1. Find your Team ID.** Open [your Apple Developer account](https://developer.apple.com/account) and scroll to **Membership details**. Copy the **Team ID**: ten letters and digits. ![Membership details of an Apple Developer account, with the Team ID SAYMYFRAME framed](https://doc.saymyframe.com/assets/images/team-id-17919a1429cf0d0b47090ee600c2a346.png) **2. Create the key.** In the account, under **Certificates, IDs & Profiles**, click **Keys** (1). ![Program resources of the account, with Keys under Certificates, IDs and Profiles marked 1](https://doc.saymyframe.com/assets/images/account-keys-c0a1eec126c2c7b43e7a12ae1902377c.png) Click the **+** next to the title (2). ![The Keys page, with the plus button next to the title marked 2](https://doc.saymyframe.com/assets/images/keys-list-9930773b1597b33ef01ba6acb6ed0278.png) Give the key a name (1), such as `My App APNs`, and check **Apple Push Notifications service (APNs)** (2). Then click **Configure** (3) in the same row. ![Register a New Key, with the name My App APNs marked 1, the checked APNs service marked 2 and its Configure button marked 3](https://doc.saymyframe.com/assets/images/new-key-apns-ac4a4bc20a81c5a26dacd9dacdc6f2aa.png) Set **Environment** to **Sandbox & Production** (1) and **Key Restriction** to **Team Scoped (All Topics)** (2), then click **Save** (3). One key then serves debug builds and App Store builds alike. Apple does not let you change these two settings later. ![Configure Key, with the environment Sandbox and Production marked 1, the restriction Team Scoped marked 2 and Save marked 3](https://doc.saymyframe.com/assets/images/configure-apns-10afc1d4d5be1133cad1b20f3ff7ac76.png) Click **Continue**, then **Register**. **3. Download the key.** On the page of the key, click **Download** (1). You get a file named `AuthKey_.p8`. Copy the **Key ID** (2) from the same page. ![View Key Details, with the Download button marked 1 and the Key ID SMFAPNSKEY marked 2](https://doc.saymyframe.com/assets/images/apns-key-details-b7bcde33fcb75d6f15522044a83a7aa1.png) :::warning Apple lets you download the file **only once**. Keep it in a password manager. The file is a secret: never put it into the app or its repository. If you lose it, revoke the key and create a new one. ::: **4. Open Cloud Messaging in Firebase.** In the [Firebase console](https://console.firebase.google.com/), open your project. In the menu on the left, point at **Settings** (1) and click **General** (2). On the page **Project settings**, open the tab **Cloud Messaging**. ![The menu of the Firebase console, with Settings and its item General marked 1 and 2](https://doc.saymyframe.com/assets/images/project-settings-menu-d9498eaae0d38e2fb59029b536200ab1.png) Scroll to **Apple app configuration** and select your iOS app on the left. Under **APNs Authentication Key**, click **Upload** (1) in the row **No development APNs auth key**. ![Apple app configuration, with the app my_app and the Upload button of the development key marked 1](https://doc.saymyframe.com/assets/images/apns-upload-button-b946d5a1074b636e982f452f41d19910.png) **5. Upload the key.** Click **Browse** (1) and choose the `.p8` file, or drag the file onto the dashed area. Enter the **Key ID** (2) and your **Team ID** (3), and click **Upload** (4). ![The dialog Upload development APNs auth key, with Browse, the Key ID SMFAPNSKEY, the Team ID SAYMYFRAME and Upload marked 1 to 4](https://doc.saymyframe.com/assets/images/apns-upload-dialog-9d029363421a5831d8fe91547ce28e95.png) Do the same in the row **No production APNs auth key**, with the same file and the same ids. **Check.** Both rows now show the key with its Key ID and Team ID. ![The APNs Authentication Key table, with the development and the production key of the Key ID SMFAPNSKEY](https://doc.saymyframe.com/assets/images/apns-key-uploaded-9556f101a8aeb8d4cf7738788abbae3e.png) To see that it works, run the app on an iPhone, copy the address that it prints in debug mode, and send it a test message from **Messaging** in the Firebase console. [A test message](https://doc.saymyframe.com/guides/firebase.md#a-test-message) tells how. The key reaches only the apps of its team. So the iOS app also needs an App ID of the same team with **Push Notifications**, which signing the app in Xcode gives it; see [the step about the App ID](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md). # Turn on Google Analytics in the Firebase project, unless it is on already Source: https://doc.saymyframe.com/setup/firebase-analytics-google-analytics The step `firebase_analytics.google_analytics`, for [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md). Firebase Analytics keeps what the app records in Google Analytics. A Firebase project that the FlutterFire CLI created has no Google Analytics, and a project created in the console may have been created without it. The app logs its events either way, but they appear nowhere until Google Analytics is on. Skip this step if the **Analytics** pages of your Firebase project show data or a dashboard rather than a button to enable it. The link to Google Analytics belongs to the project. If your [flavors](https://doc.saymyframe.com/guides/flavors.md) have Firebase projects of their own, repeat this in each project that needs it. :::tip The screenshots show the example Firebase project `My App`. The orange frames mark what to click, in the order of their numbers. ::: **1. Open Integrations.** In the [Firebase console](https://console.firebase.google.com/), open your project. In the menu on the left, point at **Settings** and click **Integrations**, which opens the tab **Integrations** (1) of the project settings. On the card **Google Analytics**, click **Enable** (2). A card that says **Enabled** and **Manage** means it is on already. ![The tab Integrations marked 1, with the card Google Analytics and its link Enable marked 2](https://doc.saymyframe.com/assets/images/analytics-enable-58d7cf8cf6f66b583d84e51e9b8ce4d0.png) **2. Choose an account.** Choose a Google Analytics account in the list (1), or create one there, and click **Enable Google Analytics** (2). Firebase creates a property of Google Analytics in that account and links it to the project. ![Configure Google Analytics, with the list of accounts marked 1 and the button Enable Google Analytics marked 2](https://doc.saymyframe.com/assets/images/analytics-configure-95a00baf31ef63259a3997c2512c727d.png) The app needs no new configuration for this: the Android and iOS apps of the project send their events to the new property. **Check.** Run the app and open a few screens. Events arrive in **Analytics > Realtime** within a few minutes. To see them at once, turn on the [DebugView](https://firebase.google.com/docs/analytics/debugview) of the device. # Set up payments in App Store Connect and Google Play Console Source: https://doc.saymyframe.com/setup/purchases-store-agreements The step `purchases.store_agreements`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). Neither store lets an app sell anything before you have agreed to its terms for paid apps and told it how you get paid and taxed. App Store Connect lets you create no in-app purchase until the Paid Apps Agreement is signed, and a purchase in the sandbox of Apple works only once the agreement is active. Google Play Console sells only through a payments profile linked to your developer account. You do this once for your developer account, and it holds for all of its apps. The Test Store of RevenueCat needs none of it, so a debug build can sell before this step is done. :::tip The screenshots use example values, such as the bank account `Example Bank (1234)`. The orange frames mark what to click, in the order of their numbers. ::: ## App Store Connect **1. Sign the Paid Apps Agreement.** In [App Store Connect](https://appstoreconnect.apple.com/), click **Business** at the top of the page. On the tab **Agreements**, find the row **Paid Apps Agreement**, click **View and Agree to Terms** (1), and then **Agree**. Only the Account Holder of the team can sign it. **2. Add the tax forms.** On the same tab, click **+** next to **Tax Forms** (2), fill in each form that Apple asks for, and click **Submit**. The Account Holder, an Admin or a Finance user can do this. **3. Add a bank account.** Click **+** next to **Bank Accounts** (3) and enter the account that gets the proceeds. Apple asks for the agreement and the tax forms first. When an Admin or a Finance user adds the account, the Account Holder approves it. ![The tab Agreements of Business in App Store Connect, with View and Agree to Terms of the Paid Apps Agreement marked 1, the plus next to Tax Forms marked 2 and the plus next to Bank Accounts marked 3](https://doc.saymyframe.com/assets/images/business-agreements-28740adf2d6c57bc90879514dd3d58c9.png) ## Google Play Console **4. Create a payments profile.** In [Google Play Console](https://play.google.com/console), open **Manage account** (1) in the bar on the left. Under **Play apps settings**, click **Payments profile** (2), and then **Create payments profile**. ![The page Manage account of Play Console, with Manage account in the bar on the left marked 1 and Payments profile under Play apps settings marked 2](https://doc.saymyframe.com/assets/images/payments-profile-4cdb374c93d4c518e2952d122a34730c.png) Enter your legal name and address (no PO box), a primary contact, and the public information of your business: a website, a product category, a support email and the name that shows on the card statements of your users. Click **Submit**. Play Console links the profile to your developer account. **5. Add the tax information.** On the payments profile, in the card **Settings**, click **Manage settings**. Open the tax information of your country, click **Edit**, add the form that Google asks for, such as a U.S. tax form, and save it. **6. Add a bank account.** On the payments profile, in the card **How you get paid**, click **Manage payment methods**, add a payment method and enter the account holder name and the details of the account. The account is in the country of the payments profile. In some countries Google sends a small deposit to the account, which you confirm in Play Console a few days later. **Check.** In App Store Connect, the row **Paid Apps** on the tab **Agreements** has the status **Active**. In Play Console, **Manage account > Payments profile** shows your profile with its bank account under **How you get paid**. # Create the products of your plans in App Store Connect and Google Play Console Source: https://doc.saymyframe.com/setup/purchases-store-products The step `purchases.store_products`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). The plans of the app are products in the stores, and a store keeps the products of each id apart. These steps are for the flavor `prod`, which has the id of the app. A [flavor](https://doc.saymyframe.com/guides/flavors.md) that sells in a store under its own id needs its own app and products there, so repeat them for it if it needs them. Every plan gives the same premium access, so create one product for each plan that you sell, in both stores, such as: | Plan | App Store | Google Play | Product ID | | --- | --- | --- | --- | | Monthly, with a free week | An auto-renewable subscription of 1 month, with an introductory offer | A subscription with a monthly base plan and a free trial offer | `premium_monthly` | | Yearly | An auto-renewable subscription of 1 year | A subscription with a yearly base plan | `premium_yearly` | | Lifetime | A non-consumable in-app purchase | A one-time product | `premium_lifetime` | The same Product ID in both stores keeps the next steps simple. A Product ID can never be used again, in either store, even after you delete its product. On Google Play it starts with a lowercase letter or a digit, has at most 40 characters, and may have underscores and periods. The paywall names these periods: every week, every 1, 2, 3 or 6 months, and every year. It names a free trial or a lower price at first of 3 days, 1 or 2 weeks, 1, 2, 3 or 6 months, or 1 year. These are the periods and trials of the App Store. Google Play offers more, such as every 4 weeks, and the paywall shows the title of such a product instead of the name of its period. Do [the step about payments](https://doc.saymyframe.com/setup/purchases-store-agreements.md) first: App Store Connect lets you create no in-app purchase until the Paid Apps Agreement is signed. :::tip The screenshots use the app `My App`. The orange frames mark what to click, in the order of their numbers. ::: ## App Store Connect **1. Create a subscription group.** In [App Store Connect](https://appstoreconnect.apple.com/), open **Apps** and your app. In the sidebar, under **Monetization**, click **Subscriptions** (1). In **Subscription Groups**, click **Create** (2), or **+** next to the heading once the app has a group. ![The page Subscriptions of an app in App Store Connect, with Subscriptions in the sidebar marked 1 and Create under Subscription Groups marked 2](https://doc.saymyframe.com/assets/images/subscriptions-create-d3c03159949a784090a787ce26be1fa2.png) Enter a reference name (1), such as `Premium`, and click **Create** (2). ![The dialog Create Subscription Group, with the reference name Premium marked 1 and Create marked 2](https://doc.saymyframe.com/assets/images/subscription-group-a2317b75ee7f090613bf7a58dfd77325.png) A user can take one introductory offer in a group, and moves between the plans of a group rather than having two at once, so put the subscriptions of the premium access into this one group. Under **Display Name and Description** of the group, click **Add** and enter the name that the App Store shows for it. **2. Create a subscription.** On the page of the group, click **Create** (1), or **+** next to **Subscriptions** once the group has one. ![The page of the subscription group Premium in App Store Connect, with Create under Subscriptions marked 1](https://doc.saymyframe.com/assets/images/subscription-group-page-7306d07ad864366cc506aaee3178b1e3.png) Enter a **Reference Name** (1), such as `Premium Monthly`, the **Product ID** (2), such as `premium_monthly`, and the **Subscription Duration** (3), such as 1 month, and click **Create** (4). Apple offers 1 week, 1, 2, 3 and 6 months, and 1 year. You cannot change the duration once the subscription is submitted. ![The dialog Create Subscription, with the reference name Premium Monthly marked 1, the Product ID premium_monthly marked 2, the duration 1 month marked 3 and Create marked 4](https://doc.saymyframe.com/assets/images/create-subscription-3dee0103cc8507a8e8c8268289961379.png) On the page of the subscription, under **Availability**, click **Set Up Availability** (1) and choose the countries or regions where you sell. Under **Subscription Prices**, click **Add Subscription Price** (2). ![The sections Availability and Subscription Prices of a subscription, with Set Up Availability marked 1 and Add Subscription Price marked 2](https://doc.saymyframe.com/assets/images/subscription-prices-38f712a8e163d2553583297d36a4affb.png) Choose a country or region and its price (1), such as United States and $4.99, and click **Next** (2). App Store Connect computes the prices of the other countries and regions from it. Change any of them on the next page, click **Next**, then **Confirm**. ![The dialog Subscription Pricing, with the country United States and the price $4.99 marked 1 and Next marked 2](https://doc.saymyframe.com/assets/images/subscription-pricing-ec40fe178defe362bc20718fabcdef43.png) Then fill in: - **Display Name and Description**: click **Add** and enter what the App Store shows. - **Review Information**: a screenshot of the paywall and notes for App Review. Click **Save**. Repeat for the yearly plan. **3. Add a free trial.** On the page of the monthly subscription, click **+** next to **Subscription Prices** (1), then **Create Introductory Offer** (2). App Store Connect shows the **+** once the subscription has a price. ![The section Subscription Prices of a subscription, with + next to the heading marked 1 and Create Introductory Offer in its menu marked 2](https://doc.saymyframe.com/assets/images/intro-offer-menu-4b5b26fdb3e73c1fedf8057c4ee6076b.png) Choose the countries or regions and click **Next**. Choose the start date, choose **No End Date** under **End Date**, and click **Next**. Choose the type **Free** (1) and its duration under **Free for** (2), such as 1 week. Click **Next**, then **Confirm**. **Pay as you go** and **Pay up front** give a lower price at first instead. An introductory offer cannot be edited later, only deleted and created again. ![The step Type of Introductory Offer, with the types Pay as you go, Pay up front and Free marked 1, where Free is chosen, and the duration Free for 1 week marked 2](https://doc.saymyframe.com/assets/images/intro-offer-type-b7856ec4223c62e7051b691d82df6163.png) **4. Create the lifetime purchase.** In the sidebar, under **Monetization**, click **In-App Purchases**, then **+** next to the heading. Choose the type **Non-Consumable** (1), enter a reference name (2) and the Product ID (3), such as `premium_lifetime`, and click **Create** (4). ![The dialog Create an In-App Purchase, with the type Non-Consumable marked 1, the reference name Premium Lifetime marked 2, the Product ID premium_lifetime marked 3 and Create marked 4](https://doc.saymyframe.com/assets/images/iap-non-consumable-2cded5646993f64d6151578495b3b215.png) On the page of the purchase, set a price in the section **Price Schedule**. In the section **Display Name and Description**, add a display name and a description. Add a screenshot under **Review Information**, and click **Save**. **5. Send them with the app.** The first subscription and the first in-app purchase of an app go to App Review with a new version of the app. On the page of each product, click **Add for Review**, and submit them with the version. ## Google Play Console **6. Upload a build.** Play Console lets you create products only once a version of the app with the Google Play Billing Library is on a track. The app has the library through RevenueCat, and the library declares the permission `com.android.vending.BILLING` itself, so the manifest needs no change. Build an app bundle, signed with your upload key, since Google Play takes no bundle that is signed with the debug key; see [Sign the app](https://docs.flutter.dev/deployment/android#sign-the-app) in the documentation of Flutter: ```bash flutter build appbundle --flavor prod --dart-define-from-file=.env ``` In [Google Play Console](https://play.google.com/console), open the app, then **Test and release > Testing > Internal testing**. Click **Create new release** (1) and upload `build/app/outputs/bundle/prodRelease/app-prod-release.aab` to it. ![The page Internal testing of an app in Play Console, with Create new release marked 1](https://doc.saymyframe.com/assets/images/internal-testing-de7f5ec56dc026d15d239cad560f8901.png) **7. Create a subscription.** Open **Monetize with Play > Products > Subscriptions** and click **Create subscription** (1). ![The page Subscriptions of an app in Play Console, with Create subscription marked 1](https://doc.saymyframe.com/assets/images/subscriptions-56e6ff1ae590d0a6e655ff2e7aebf523.png) Enter the **Product ID** (1), such as `premium_monthly`, and a **Name** (2), and click **Create** (3). ![The dialog Create subscription, with the Product ID premium_monthly marked 1, the name Premium Monthly marked 2 and Create marked 3](https://doc.saymyframe.com/assets/images/create-subscription-680bd4ec46336be29f8d98b963665d9e.png) On the page of the subscription, under **Base plans and offers**, click **Add base plan**. Enter a **Base plan ID** (1), such as `monthly`, with lowercase letters, digits and hyphens. Choose the type **Auto-renewing** (2) and the **Billing period** (3), such as **Monthly**. ![The page Add base plan in Play Console, with the base plan ID monthly marked 1, the type Auto-renewing marked 2 and the billing period Monthly marked 3](https://doc.saymyframe.com/assets/images/base-plan-569925ed92d16407f107a6387e8539af.png) Under **Price and availability**, click **Set prices**, check the countries and regions where you sell (the box in the header of the table checks all of them), and click **Set price**. Enter the price and its currency, such as 4.99 USD, and click **Update**. Click **Save**, then **Activate**. Repeat for the yearly plan: a subscription `premium_yearly` with a base plan `yearly` whose billing period is **Yearly**. **8. Add a free trial.** In the monthly subscription, under **Base plans and offers**, click **Add offer**, choose the base plan and click **Add offer**. Enter an **Offer ID**, such as `free-week`, and under **Eligibility criteria** choose **New customer acquisition**. Under **Phases**, click **Add phase**, choose the type **Free trial** and its duration (1), such as 1 week, and click **Apply**. Click **Save**, then **Activate**. ![The dialog Add phase of an offer in Play Console, with the type Free trial and the duration 1 week marked 1](https://doc.saymyframe.com/assets/images/offer-phase-91118f919fb8341992cc73b775310842.png) **9. Create the lifetime product.** Open **Monetize with Play > Products > One-time products** and click **Create one-time product**. On **Product details**, enter the **Product ID** (1), such as `premium_lifetime`, a **Name** and a **Description**, and click **Next**. ![The first page of Create one-time product, Product details, with the Product ID premium_lifetime marked 1](https://doc.saymyframe.com/assets/images/one-time-product-efbb0bb40eff9e67dcdb46ab3ef3fc2d.png) On **Availability and pricing**, add a purchase option with an ID and the purchase type **Buy**, set its prices, and click **Activate**. A one-time product that is bought once and kept for good is a non-consumable, and [the step in RevenueCat](https://doc.saymyframe.com/setup/revenuecat-entitlement-and-offering.md) marks it so. **Check.** App Store Connect lists the subscriptions in their group and the non-consumable purchase, each with a price. Play Console lists the subscriptions with active base plans, the offer of the free week, and the one-time product as active. To buy them on a device before a release, add testers: in App Store Connect under **Users and Access > Sandbox**, and in Play Console under **Manage account > Play apps settings > License testing**. ![The page Manage account of Play Console, with Manage account in the bar on the left marked 1 and License testing under Play apps settings marked 2](https://doc.saymyframe.com/assets/images/license-testing-d892326be6714d9d01add01a8b6aab19.png) A license tester installs the app from the internal testing track and pays with a test card. In a debug build, leave `REVENUECAT_TEST_KEY` empty, so that the app sells through the store rather than the Test Store of RevenueCat. # Set up the entitlement premium and the default offering in RevenueCat Source: https://doc.saymyframe.com/setup/revenuecat-entitlement-and-offering The step `revenuecat.entitlement_and_offering`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). The app asks RevenueCat for two things. Its premium access is the entitlement `premium`, and its plans are the packages of the default offering of the project, which the SDK calls the current offering. Until both are there, the paywall says that the plans are not available, and a debug build names what RevenueCat lacks, such as "RevenueCat has no current offering". You make the entitlement and the offering once for the project. Each store gets its products into them, the Test Store of RevenueCat too. :::tip A new RevenueCat project has a Test Store with products, so you can do this step before the products of the App Store and Google Play exist, and buy a plan in a debug build. Add the products of the stores to the entitlement and to the packages once they exist. The screenshots use the project `My App`, and the orange frames mark what to click, in the order of their numbers. ::: **1. Create a project.** In the [RevenueCat dashboard](https://app.revenuecat.com/), create a project for the app, or open the one that you have. A project without a Test Store gets one on the page **Apps**, in the section **Test configuration**. **2. Add the products.** Open **Product catalog**, then **Products**, and click **New product**, then **Create from scratch**, for each product that RevenueCat does not list yet. Choose the app of the store, fill in the form and click **Create Product**: | Store | What the form takes | | --- | --- | | App Store | The Product ID of App Store Connect in **Identifier**, as it is, such as `premium_monthly`, and the **Product type**: **Subscription** for a plan that renews, **Non-consumable** for a plan paid once. | | Play Store, a subscription | The **Product type** **Subscription**, the ID of the subscription in **Subscription**, such as `premium_monthly`, and the ID of its base plan in **Base plan Id**, such as `monthly`. | | Play Store, a one-time product | The **Product type** **Non-consumable** and its Product ID in **Google product identifier**, such as `premium_lifetime`. Otherwise RevenueCat consumes the purchase, and Google Play lets the user buy it again. | | Test Store | Any identifier, with a name, a price and a duration. These cannot be edited once the product is saved. | ![The form of a new product of the Play Store app, with the product type Non-consumable marked 1 and the Google product identifier premium_lifetime marked 2](https://doc.saymyframe.com/assets/images/product-non-consumable-7da6a3146f778af8d230b06480a70571.png) Once RevenueCat has the credentials of a store (see the steps about [the App Store key](https://doc.saymyframe.com/setup/revenuecat-app-store-key.md) and [the service account of Google Play](https://doc.saymyframe.com/setup/revenuecat-play-service-account.md)), **Import Products** at the top of the form takes the products from the store instead. The Test Store sells subscriptions without a free trial, so a plan there shows no trial on the paywall. **3. Create the entitlement `premium`.** In **Product catalog**, open **Entitlements** and click **New entitlement**. Enter the identifier `premium`, in lowercase, exactly so, and a description such as `Premium access`. Open the entitlement, whose page shows the identifier `premium` (1). Under **Associated products**, click **Attach** (2), select every product of every plan, of every store, and save. ![The page of the entitlement premium, with the identifier premium marked 1 and Attach under Associated products marked 2](https://doc.saymyframe.com/assets/images/entitlement-1c41c4f3d558fbe7c615da4de119f1be.png) Every product of the default offering has to be attached. A purchase of a product that is not gives the user no premium access: the paywall then fails with "Purchases are unavailable right now", and the debug hint names the product to attach. **4. Create the offering.** In **Product catalog**, open **Offerings** and click **New offering**, then **Create from scratch**. Enter an identifier, such as `default`, which you cannot change later, and a description, and click **Save**. **5. Add a package for each plan.** Open the offering, click **Edit**, and then **New Package** (1). In the new package, choose the **Identifier** of the duration of the plan, such as monthly, annual or lifetime, or a custom one, enter a **Description** (2), and choose under **Product** (3) the product of each app for that plan. RevenueCat takes one product of each app. Click **Save** (4). The paywall shows the plans in the order of the packages, and it selects the first yearly plan. ![The editor of an offering, with New Package marked 1, the description of a package marked 2, its product marked 3 and Save marked 4](https://doc.saymyframe.com/assets/images/offering-package-5b51ba555bedb37fdf3cf5625bf93c69.png) **6. Make it the default offering.** On **Offerings**, click **Β·Β·Β·** in the column **Actions** of the offering, then **Make Default**. The default offering has a check mark next to its identifier. The app sells the packages of this offering alone. **Check.** With the API key of the Test Store in `REVENUECAT_TEST_KEY` (see [the step about the API keys](https://doc.saymyframe.com/setup/revenuecat-api-keys.md)), run a debug build and open the paywall, such as from the row Subscription of the settings screen. It shows a card for each package. Buy one: the Test Store shows its own dialog, where **Test valid purchase** completes the purchase, and the router closes the paywall. # Copy the API keys of your RevenueCat apps into .env Source: https://doc.saymyframe.com/setup/revenuecat-api-keys The step `revenuecat.api_keys`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). The app configures RevenueCat with the public API key of a RevenueCat app of the project: the App Store app on iOS, the Play Store app on Android, and the Test Store in a debug build. While the key that a build takes is empty, the app runs without purchases and never calls RevenueCat, and a debug build prints which key to fill in. These keys are public. Each is compiled into the app, where anyone can read it. A secret API key of RevenueCat, which starts with `sk_`, never goes into the app, and the app refuses one. A RevenueCat app stands for one id in a store, and each [flavor](https://doc.saymyframe.com/guides/flavors.md) has an id of its own. The examples below are for `prod`. A flavor that sells in a store under its own id needs its own apps in RevenueCat and its own products in the stores, so repeat these steps for it if it needs them. `.env` is one file, so change its keys by hand when you build another flavor, and let [CI](https://doc.saymyframe.com/guides/ci.md) write them for its job. :::tip The examples use the bundle id `com.example.my-app` and the package name `com.example.my_app` of an app that `smf create my_app` generated. Yours start with the organization that you gave `--org`. The screenshots use the project `My App`. The orange frames mark what to click, in the order of their numbers. ::: **1. Add the apps of the stores.** In the [RevenueCat dashboard](https://app.revenuecat.com/), open the project and click **Apps** in the sidebar (1). Click **New app configuration** (2), or **New app** once the project has an app. ![The page Apps of a RevenueCat project, with Apps in the sidebar marked 1 and the card New app configuration marked 2](https://doc.saymyframe.com/assets/images/apps-new-1201d2d32bcace9a5abd2f5d105a98b3.png) Choose **App Store** (1) for the iOS app, and then, for the Android app, **Google Play Store** (2). ![The stores of a new app configuration, with App Store marked 1 and Google Play Store marked 2](https://doc.saymyframe.com/assets/images/new-app-stores-19c576b4c75c656f300d350605d6921c.png) - **App Store**: an app name and the **App Bundle ID** (1) of the iOS app, such as `com.example.my-app`. Xcode shows it under **Bundle Identifier** on the tab **Signing & Capabilities** of the target **Runner**. ![The form New App Store app, with the App Bundle ID com.example.my-app marked 1](https://doc.saymyframe.com/assets/images/app-store-app-b6f94e4477b53f318f3479e1d894a5a4.png) - **Google Play Store**: an app name and the **Google Play package name** (1) of the Android app, such as `com.example.my_app`, the `applicationId` in `android/app/build.gradle.kts`. ![The form New Play Store configuration, with the Google Play package name com.example.my_app marked 1](https://doc.saymyframe.com/assets/images/play-store-app-5195c0f0420b10e407420b8b9e8abbbc.png) Click **Save changes** at the bottom of each form. RevenueCat creates the public API key of each app with it. The forms also have a section for the credentials of the store, which the next two steps fill in, and you can add them now or later. **2. Copy the keys.** Click **API keys** in the sidebar (1). Under **SDK API keys**, click the copy icon of each app: the key of the App Store app (2) starts with `appl_`, and the key of the Play Store app (3) with `goog_`. The Test Store has a row of its own there, with a key that starts with `test_`, and the page **Apps** shows that key too. ![The page API keys, with API keys in the sidebar marked 1 and the copy icons of the keys of the App Store app and of the Play Store app marked 2 and 3](https://doc.saymyframe.com/assets/images/api-keys-7ed8c0a8a292ea1a447634aa6698764a.png) **3. Put them into .env.** In `.env` at the root of the app: ```bash title=".env" REVENUECAT_APPLE_KEY=appl_... REVENUECAT_GOOGLE_KEY=goog_... REVENUECAT_TEST_KEY=test_... ``` `.env` stays out of git. On another machine, copy `.env.example` to `.env` and fill it in again. **4. Start the app again.** The `flutter` tool reads `.env` when a command starts, so stop `flutter run` and start it again with the values: ```bash flutter run --dart-define-from-file=.env ``` Run and Debug of VS Code, and the run configuration of the app in Android Studio, pass the argument for you. The app chooses the key by the build: | Build | Key | | --- | --- | | A debug build, with `REVENUECAT_TEST_KEY` filled in | The Test Store | | A debug build without it, and every profile or release build | `REVENUECAT_APPLE_KEY` on iOS, `REVENUECAT_GOOGLE_KEY` on Android | A release build never takes the key of the Test Store, since RevenueCat stops such a build on purpose. To buy through the sandbox of a store in a debug build, leave `REVENUECAT_TEST_KEY` empty. **Check.** A debug build no longer prints that a key "has no value in this build", and the paywall shows the plans of the default offering. # Give RevenueCat your In-App Purchase key from App Store Connect Source: https://doc.saymyframe.com/setup/revenuecat-app-store-key The step `revenuecat.app_store_key`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). RevenueCat checks each purchase on iOS with Apple, and for that it needs an In-App Purchase key from App Store Connect. Without the key, RevenueCat does not record the transactions of the App Store, and the user who paid gets no premium access. You make the key once for your team, and it serves all of its apps. Add the App Store app to the RevenueCat project first; see [the step about the API keys](https://doc.saymyframe.com/setup/revenuecat-api-keys.md). :::tip RevenueCat no longer needs the App-Specific Shared Secret of App Store Connect for this: the In-App Purchase key replaces it. The screenshots use example values: the Key ID `SMFSUBSKEY` and an Issuer ID from the documentation of Apple. The orange frames mark what to click, in the order of their numbers. ::: **1. Generate the key.** In [App Store Connect](https://appstoreconnect.apple.com/), open **Users and Access** and the tab **Integrations**. In the sidebar, under **Keys**, click **In-App Purchase** (1). Click **Generate In-App Purchase Key**, or **+** next to **Active** (2) when the team has a key already. The Account Holder or an Admin can do this. Copy the **Issuer ID** (3), which the same page shows above the keys. ![The In-App Purchase keys of App Store Connect, with In-App Purchase in the sidebar marked 1, the plus next to Active marked 2 and Copy next to the Issuer ID marked 3](https://doc.saymyframe.com/assets/images/iap-keys-26ac07567384b3ed5a4af839e170725e.png) Enter a name (1), such as `RevenueCat`, and click **Generate** (2). ![The dialog Generate In-App Purchase Key, with the name RevenueCat marked 1 and Generate marked 2](https://doc.saymyframe.com/assets/images/iap-key-generate-813b288e828eb3aaaa6ed0d0e12752cf.png) If App Store Connect shows no Issuer ID, create any key under **App Store Connect API** on the same tab **Integrations**, and the Issuer ID appears. **2. Download it.** In the list **Active**, download the new key from its row. You get a `.p8` file whose name has the Key ID, such as `SubscriptionKey_SMFSUBSKEY.p8`. :::warning Apple lets you download the file **only once**. Keep it in a password manager. The private key in it is a secret: you upload it to RevenueCat yourself, and it never goes into `.env`, the app or its repository. ::: **3. Upload it to RevenueCat.** In the [RevenueCat dashboard](https://app.revenuecat.com/), click **Apps** in the sidebar and open the App Store app. In the section **In-app purchase key configuration**, click **Add new key** if the section offers it. Drop the `.p8` file on **P8 key file from App Store Connect** (1) without renaming it, since RevenueCat reads the Key ID from its name and fills in **Key ID** itself. Paste the **Issuer ID** (2) and click **Save changes** (3). ![The section In-app purchase key configuration of an App Store app in RevenueCat, with the field of the p8 file marked 1, the Issuer ID marked 2 and Save changes marked 3](https://doc.saymyframe.com/assets/images/iap-key-upload-68a0ae07f23a85d3609885859fb7bc66.png) **Check.** RevenueCat shows **Valid credentials** for the key. To see a purchase go through, buy a plan with a sandbox account. Create one in App Store Connect under **Users and Access > Sandbox**, with an email address that is no Apple Account yet. Run a debug build on an iPhone with `REVENUECAT_TEST_KEY` empty, and buy a plan: iOS asks for the sandbox account at the first purchase, and keeps it under **Settings > Developer** afterwards. The purchase shows in RevenueCat under the customers of the project. The sandbox needs the Paid Apps Agreement to be active; see [the step about payments](https://doc.saymyframe.com/setup/purchases-store-agreements.md). # Give RevenueCat access to Google Play with a service account Source: https://doc.saymyframe.com/setup/revenuecat-play-service-account The step `revenuecat.play_service_account`, for [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md). RevenueCat checks each purchase on Android with Google Play, through a service account of Google Cloud that has access to your Google Play Console account. Until RevenueCat has valid credentials, it cannot validate the purchases of Google Play, and the user who paid gets no premium access. You need a Google Cloud project, which may be the one of the Firebase project of the app, and the rights to invite users to your Play Console account. Add the Play Store app to the RevenueCat project first; see [the step about the API keys](https://doc.saymyframe.com/setup/revenuecat-api-keys.md). :::tip RevenueCat offers a script for Google Cloud Shell that does steps 1 to 3 for you. It is in [Creating Play Service Credentials](https://www.revenuecat.com/docs/service-credentials/creating-play-service-credentials) of the documentation of RevenueCat, next to these steps. The screenshots use example values: the Google Cloud project `my-app-12345` and its service account `revenuecat@my-app-12345.iam.gserviceaccount.com`. The orange frames mark what to click, in the order of their numbers. ::: **1. Turn on the APIs.** In the [Google Cloud console](https://console.cloud.google.com/), select the project. Under **APIs & Services**, enable the **Google Play Android Developer API** and the **Google Play Developer Reporting API**. **2. Create the service account.** Open **IAM & Admin**, click **Service Accounts** in the sidebar (1), and then **Create service account** (2). ![The service accounts of the Google Cloud project my-app-12345, with Service Accounts in the sidebar marked 1 and Create service account marked 2](https://doc.saymyframe.com/assets/images/service-accounts-93dc1b4a53bc77d2eb910da0963c1f1c.png) Enter a name, such as `revenuecat`, and click **Create and continue**. Give it the roles **Pub/Sub Editor** and **Monitoring Viewer**, and click **Done**. RevenueCat uses the first for the real-time notifications of Google Play. **3. Create its key.** In the row of the service account, open the menu under **Actions** and click **Manage keys**. Click **Add key**, then **Create new key**, choose **JSON** (1) and click **Create** (2). The browser downloads the JSON key. ![The dialog Create private key, with the key type JSON marked 1 and Create marked 2](https://doc.saymyframe.com/assets/images/create-key-json-0e6beb19ca0f3d34148ec86838eff173.png) :::warning The JSON key lets anyone act as the service account. Keep it in a password manager, and never put it into `.env`, the app or its repository. ::: **4. Invite it to Play Console.** In [Google Play Console](https://play.google.com/console), open **Manage account** in the bar on the left, then **Users and permissions**, and click **Invite new users**. Enter the email address of the service account (1), which is `client_email` in the JSON key. ![The page Invite user of Play Console, with the email address of the service account marked 1](https://doc.saymyframe.com/assets/images/invite-user-28b3408bc8071b44de0ed6adc2b56ca0.png) On the tab **App permissions**, add the app. On the tab **Account permissions**, check: - **View app information and download bulk reports (read-only)** (1) - **View financial data, orders, and cancellation survey responses** (2) - **Manage orders and subscriptions** (3) - **Manage store presence** (4) Play Console also checks the permissions that these need, such as **View app quality information (read-only)**. ![The four permissions on the tab Account permissions of Play Console, each checked and marked 1 to 4 in the order of the list](https://doc.saymyframe.com/assets/images/account-permissions-dae95f97fe8bf3948aec06f4291a8c70.png) Click **Invite user**. **5. Upload the key to RevenueCat.** In the [RevenueCat dashboard](https://app.revenuecat.com/), click **Apps** in the sidebar and open the Play Store app. In the section **Service account credentials**, drop the JSON key on **Service Account Credentials JSON** (1) and click **Save changes** (2). ![The section Service account credentials of a Play Store app in RevenueCat, with the field of the JSON key marked 1 and Save changes marked 2](https://doc.saymyframe.com/assets/images/play-credentials-2511f6ce44eef3f00011e696e8e54d2e.png) **Check.** RevenueCat shows the credentials as valid. Google may take up to 36 hours to accept new credentials, so they may show as invalid on the first day. Open the status of the credentials and click **Check credentials** to look again. RevenueCat suggests editing the description of any product of the app in Play Console, which may make Google accept them sooner. To see a purchase go through, add your Google account under **Manage account > Play apps settings > License testing** of Play Console, install the app from the internal testing track, and buy a plan with the test card that Google Play offers a license tester. The purchase shows in RevenueCat under the customers of the project. # Publish your terms of use and privacy policy and put their links into .env Source: https://doc.saymyframe.com/setup/paywall-legal-pages The step `paywall.legal_pages`, for [`paywall`](https://doc.saymyframe.com/modules/paywall.md). The App Store asks an app that sells subscriptions to link to its terms of use and its privacy policy, both in the app and in its App Store metadata. Google Play asks every app for a privacy policy, linked in Play Console and in the app. The paywall shows the links Terms of Use and Privacy Policy from two values of `.env`: `PAYWALL_TERMS_URL` and `PAYWALL_PRIVACY_URL`. While a value is empty, or is no web address, the paywall leaves its link out, and a debug build names the key in its note for the developer. The terms of use on iOS then lead to the standard license agreement of Apple. :::tip The screenshots use the app `My App` and the address `https://example.com/privacy`. The orange frames mark what to click, in the order of their numbers. ::: **1. Publish the pages.** Put both pages at public web addresses, such as on the website of the app. Google Play takes no PDF for the privacy policy. - The privacy policy says who you are and how to reach you, what data the app collects and shares and why, how it keeps the data safe, and how long it keeps it and how a user has it deleted. The modules of the app decide what data it sends: RevenueCat, for example, gets the id of the user and what the user bought. - The terms of use are your own, or the [standard license agreement of Apple](https://www.apple.com/legal/internet-services/itunes/dev/stdeula/) if it fits your app. **2. Put the addresses into .env.** In `.env` at the root of the app: ```bash title=".env" PAYWALL_TERMS_URL=https://example.com/terms PAYWALL_PRIVACY_URL=https://example.com/privacy ``` An address with `https` or `http` and a host counts. An address with an anchor goes into double quotes, since `#` after a plain value starts a comment: `PAYWALL_TERMS_URL="https://example.com/legal#terms"`. Stop `flutter run` and start it again with `--dart-define-from-file=.env`, since the `flutter` tool reads `.env` when a command starts. **3. Give App Store Connect the privacy policy.** In [App Store Connect](https://appstoreconnect.apple.com/), open **Apps** and your app, and in the sidebar, under **Trust & Safety**, **App Privacy**. Click **Edit** (1) next to **Privacy Policy**, enter the address, and click **Save**. ![The page App Privacy of an app in App Store Connect, with Edit next to Privacy Policy marked 1](https://doc.saymyframe.com/assets/images/app-privacy-policy-b1565fe8ce40bb3d785956818393ab21.png) The App Store shows the change with the next version of the app. **4. Give App Store Connect the terms of use.** - With the standard license agreement of Apple, add a link to it, or to your page of the terms, to the description of the app in App Store Connect. App Review asks for that link in the description of an app with subscriptions. - With terms of your own, open **App Information** (1) in the sidebar, click **Edit** (2) next to **License Agreement**, choose to apply a custom license agreement, paste its text, choose the countries or regions, click **Done** and **Save**. The App Store then shows a link to it on the page of the app. ![The page App Information of an app in App Store Connect, with App Information in the sidebar marked 1 and Edit next to License Agreement marked 2](https://doc.saymyframe.com/assets/images/license-agreement-a85e8f8e0ce4ff894eee094c45606cf9.png) **5. Give Google Play the privacy policy.** In [Google Play Console](https://play.google.com/console), open the app, then **Monitor and improve > Policy and programs > App content**. Find **Privacy policy** on the tab **Need attention** and click **Start**, or, once it has an address, on the tab **Actioned** and click **Manage** (1). Enter the address and save. ![The tab Actioned of App content in Play Console, with Manage in the row Privacy policy marked 1](https://doc.saymyframe.com/assets/images/privacy-policy-5c1d0701bbf6037372431c2a8439dd8c.png) **Check.** In a debug build, the paywall shows the links **Terms of Use** and **Privacy Policy**, its note for the developer names no key of `.env`, and each link opens its page in the browser. # Choosing modules Source: https://doc.saymyframe.com/guides/choosing-modules An app is made of the modules you ask for and the modules they need. You name modules with `-m` or pick them in the questions of `smf create`, and SMF adds the rest. ## Roles and the modules that provide them Most modules provide a role, a part of the app that other modules count on without knowing which module provides it. An app has at most one provider of most roles, while crash reporting and analytics can have several. | Role | `-m` | What the module does | In an app | | --- | --- | --- | --- | | App entry | `flutter_core` | The Flutter project: `main()`, start-up, root widget, native projects | always, added by SMF | | Router | `go_router` | Routes of the features, typed navigation | none or one | | Layout | `bottom_tabs` | Tabs at the bottom for the features' destinations, in the colors of the theme | none or one | | Settings screen | `settings` | A screen with the settings of the modules in one group, a row for each | none or one | | Onboarding screen | `onboarding` | The onboarding that a new user goes through on the first launch of the app, with the steps that other modules add | none or one | | State management | `bloc` | BLoC with `flutter_bloc` | none or one | | | `riverpod` | Riverpod with `flutter_riverpod` | | | Theme | `material_theme` | A light and a dark Material 3 theme with a palette and a bundled font, and the theme mode that the user selects | none or one | | App icon | `launcher_icons` | An icon for iOS and Android, made from two images in the app that you replace | none or one | | Splash screen | `native_splash` | The screen that the system shows while the app starts, for the light and the dark mode, made from two images in the app that you replace | none or one | | Localization | `gen_l10n` | The texts of the app in ARB files, in the language of the device or in the one that the user chose | none or one | | Dependency injection | `get_it` | Service locator with get_it | none or one | | Events | `event_bus` | A service that delivers events between parts of the app | none or one | | Preferences | `shared_preferences` | The settings of the app (not secrets), remembered between its launches | none or one | | Notifications | `local_notifications` | Notifications now and at about a time to come, the permission to show them, and the taps on them | none or one | | Push messages | `firebase_messaging` | Push messages with Firebase Cloud Messaging: the address of the device for a backend, the messages and the taps | none or one | | REST API | `dio` | A REST client with the address in `.env`, failures of a closed set, repeats, a cancel for each call and the token of the user | none or one | | Purchases | `revenuecat` | Premium access with RevenueCat: the plans of the current offer, a purchase, a restore, and the access of the user before the first frame | none or one | | Values in .env | `dart_define` | The values that you fill in after generating the app, such as public API keys, given to the app with `--dart-define-from-file` | none or one | | Crash reporting | `firebase_crashlytics` | Reports errors to Firebase Crashlytics | any number | | Analytics | `firebase_analytics` | Records events and screen views in Firebase Analytics | any number | | Authentication | `firebase_auth` | Signs users in with Firebase Authentication, with an email address and a password, as anonymous users, or with Google and Apple | none or one | | CI | `github_actions` | The format check, `flutter analyze` and `flutter test` on each push, and a release APK for an environment on request | none or one | Six modules provide no role: | Kind | `-m` | What the module does | | --- | --- | --- | | Feature | `home` | A start screen at `/home`, which welcomes the developer of the app and lists the next steps | | Feature | `sign_in` | The screens of sign-in, sign-up and password reset for an email address and a password, with a button for each other way to sign in, and the screen of the account | | Feature | `paywall` | The paywall, which sells premium access with the plans of the current offer, and the screen of the subscription, with a row of the settings screen and a step of the onboarding | | Infrastructure | `firebase_core` | Sets up Firebase, for the other Firebase modules | | Infrastructure | `google_sign_in` | Sign-in with Google on Android and iOS, a way to sign in for the authentication | | Infrastructure | `apple_sign_in` | Sign in with Apple on iOS, a way to sign in for the authentication | Each module has a [page of its own](https://doc.saymyframe.com/modules.md). ## What SMF adds for you - `flutter_core` goes into every app. - A module brings the modules it depends on: `firebase_crashlytics`, `firebase_analytics`, `firebase_messaging` and `firebase_auth` bring `firebase_core`. - A module that requires a role brings its provider when only one module provides it. Features need a router, and so do the layout and the onboarding, so `home`, `settings`, `onboarding` or `bottom_tabs` brings `go_router`. A module that needs dependency injection brings `get_it`. `material_theme`, `gen_l10n`, `onboarding` and `local_notifications` each remember something between the launches of the app, so each brings `shared_preferences`. `firebase_messaging` brings `local_notifications`, through which a message shows in the foreground. `sign_in` brings `firebase_auth`, which keeps the accounts, and `settings`, where the entry of the account is. `google_sign_in` and `apple_sign_in` require sign-in too, so each brings `firebase_auth`. `revenuecat` reads its API keys from `.env`, so it brings `dart_define`, and `paywall` requires the purchases, so it brings `revenuecat` and `dart_define`. `dio` reads the address of the API from `.env`, so it brings `dart_define` too. When several modules provide a required role, a run in a terminal asks which one to use. A run without a terminal stops and asks you to add one of them to `-m`. Before it generates the app, SMF prints each module it added and why. ## How the modules combine ### Every app has three flavors Whatever its modules, an app has the flavors `dev`, `staging` and `prod`, which install next to each other, and `flutter run` builds `dev`. A module with a setup in a service, such as Firebase or RevenueCat, repeats that setup for each flavor that needs it. See [Flavors](https://doc.saymyframe.com/guides/flavors.md). ### Screens need a router A feature declares its routes for whatever router the app has. An app without a router shows the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen), which names the app and tells you where its first screen goes, and so does an app with a router but no screen to start on. `smf create` warns of the latter, with the code `router.no_start`. Only such apps have the screen. ### The layout shows the destinations of the features A feature can mark a route as a destination of the main navigation, as `home` does. With `bottom_tabs`, every destination becomes a tab, in the order the features were chosen. With one destination the tab bar is hidden, and without any the app has no main navigation. The bar holds at most five tabs. A feature whose destination does not fit is left out with a warning, and with `--strict` the run stops instead. Without a layout, the app has no main navigation to lead to its destinations. `smf create` then warns of each destination other than the one that the app starts on, by its path and its module: ```text [WARN] [role:router]: No module provides the layout role, so the app has no main navigation to lead to the destination /settings (settings). Choose a provider of the role, or open it from a screen of yours with context.nav. ``` The app is generated all the same. With `--strict`, the warning `router.no_main_navigation` stops the run instead; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). ### The settings screen is a feature too `settings` provides the settings screen role, and it is a feature with a route of its own, so it needs a router and its screen is a destination. With `bottom_tabs`, Settings becomes a tab next to the tabs of the other features. Without a layout, nothing that SMF generates opens the screen, and your own code opens it; see [`settings`](https://doc.saymyframe.com/modules/settings.md#opening-the-screen). A module or a role with a setting gives the settings screen role a row, and the screen shows all of them, whichever module provides the screen. The theme mode of `material_theme` and the language of `gen_l10n` each have one, the notifications have one for the permission, `sign_in` has the row of the account, `paywall` the row of the subscription, and the purchases one that restores them. In an app without a settings screen, the mode and the language work without their rows. In an app with `settings` and no setting, the screen shows a note for you where the rows go. ### Preferences remember what the user chose A module that keeps something the user chose saves it through the preferences role, which `shared_preferences` provides. The theme mode of `material_theme` and the language of `gen_l10n` are kept this way, and with `settings` the screen has a row for each. The preferences are for settings and not for secrets: nothing in them is encrypted, so a token, a password or a key never goes there. See [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md). ### Texts follow the language of the app A module gives its texts to the localization role, in English and in the other languages that it has them in. With `gen_l10n`, the app keeps them in ARB files and shows them in the language of the device, and you add your own texts and languages there. The built-in modules have their texts in English and in Ukrainian, and so has the fallback start screen of an app that no route starts, so an app with `gen_l10n` is in both languages unless `--locales` says otherwise. Without a module that provides the localization, the modules show their texts in English. See [Languages](https://doc.saymyframe.com/guides/languages.md). ### The onboarding keeps the user until it is finished `onboarding` is a feature with a guard of the routes. On the first launch, the app shows the onboarding in place of every other screen, whichever features it has, and it remembers in the preferences that the onboarding is finished. It provides the onboarding screen role, so other modules add steps to it, such as the page of the notifications that asks for the permission and the page of the paywall that offers premium access. See [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md). ### Notifications ask for the permission where the app can `local_notifications` shows notifications through `appNotifications`, and `firebase_messaging` receives push messages through `appPush`, showing a message in the foreground as a notification. The app asks for the permission to show notifications on a page of the onboarding, in an app with one, and from a row of the settings screen, in an app with one. An app with neither asks nowhere until its code does. See [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md). ### Sign-in is screens, a session and a mode `sign_in` is the screens: the sign-in, the sign-up, the password reset and the screen of the account. `firebase_auth` provides the auth role under them: `appSession`, which knows who uses the app before the first frame, on Firebase Authentication. `sign_in` requires that role, so it brings `firebase_auth`, and `firebase_core` with it. ![The sign-in of sign_in with the line Choose how to sign in to your account., the buttons Continue with Google and Continue with Apple, then or, the fields Email and Password, the button Sign in, and Create account below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png) ![The screen of the account of sign_in: the address of the account, the button Sign out, and Delete account in red.](https://doc.saymyframe.com/demo/0.8/app_account.png) `smf create` asks who may use the app without an account, or takes `--auth-mode`: nobody (`required`, the default), everyone (`guest`), or everyone as an anonymous user (`anonymous`). In `required` the app shows the sign-in until the user is signed in. In the other two it asks for an account only on the screens that need one. An app with `sign_in` needs three more things: | It needs | Why | What to add | | --- | --- | --- | | A state manager | The screens keep their state with it, in a variant for each. Two modules provide one, so `smf create` asks, or stops without a terminal. | `bloc` or `riverpod` | | A settings screen | The entry of the account is there. `smf create` adds `settings` by itself. | nothing | | A way to the settings screen | A main navigation shows the settings screen among its destinations. Without one, no screen leads to it, and a screen of yours opens it or the account. | `bottom_tabs` | An app can also have `firebase_auth` without `sign_in`: the session and the mode, with screens of your own. See [Sign-in](https://doc.saymyframe.com/guides/sign-in.md). `google_sign_in` and `apple_sign_in` add the ways to sign in with Google and Apple, which the screens of `sign_in` show as buttons. On iOS, App Store Review Guideline 4.8 asks an app with a login service of a third party, such as Google sign-in, to offer an equivalent way to sign in too, one that asks for no more than the name and the email address of the user and lets the user keep the address private. Sign in with Apple is such a way, and `smf create` warns of an app without one; see [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). ### The paywall sells what the purchases keep `paywall` is the screens: the paywall and the screen of the subscription. `revenuecat` provides the purchases role under them: `appPurchases`, which knows before the first frame whether the user has premium access, and sells the plans of a RevenueCat offering. `paywall` requires that role, so it brings `revenuecat`, which brings `dart_define` for its API keys in `.env`. Right after `smf create`, the keys are empty and the app runs without purchases. A debug build sells once the key of the Test Store of RevenueCat is in `.env`, and a release needs steps by hand in App Store Connect, Google Play Console and RevenueCat, which the README of the app lists. The screens keep their state with the state manager of the app, so an app with `paywall` has `bloc` or `riverpod`. An app can also have `revenuecat` without `paywall`, with screens of your own. See [Purchases](https://doc.saymyframe.com/guides/purchases.md). ### The REST client adds what the app has `dio` provides the REST role: `appRest`, with its address in `.env`. No module of the CLI makes a request itself, so the client is there for your code. In an app with sign-in, it adds the token of the user to the requests to that address, whichever module provides the sign-in. See [REST API](https://doc.saymyframe.com/guides/rest.md). ### CI runs what the app has `github_actions` provides the CI role, which runs the checks on each push and builds a release APK for one flavor on request. In an app with values in `.env`, a build writes its own `.env` from the variables of the environment of its flavor. See [CI](https://doc.saymyframe.com/guides/ci.md). ### The icon and the splash screen are yours to replace `launcher_icons` and `native_splash` provide the app icon and the splash screen from images in `assets/branding/`, which show the mark of Say My Frame until you replace them. A run in a terminal that answers their questions with Enter gets both. A run with `--no-input`, or a `-m` without them, keeps the logo of Flutter and a white launch screen. See [App icon and splash screen](https://doc.saymyframe.com/guides/app-icon-and-splash.md). ### Guards come in the order of a first launch A guard of the routes has a stage, so the app asks its guards in the order of a first launch whatever the order of the modules: the onboarding comes before a guard that asks who the user is. See [Guards of routes](https://doc.saymyframe.com/concepts/guards.md#the-order-of-the-guards). ### State management is per feature `bloc` and `riverpod` add their package, and `riverpod` also puts its `ProviderScope` around the app. A feature that keeps state brings its Cubits or providers in a variant for each state manager. `sign_in` and `paywall` do, so an app with either has `bloc` or `riverpod`. `home` and `onboarding` keep what moves on their screens in the screens themselves, so they work with either of them or with none. ### Services work with or without a container The events, analytics and crash reporting roles each generate a service interface and a function that returns the app's service. With `get_it`, the roles register their services in the container, and features take them from there. Without a container, the app calls the function. See [Services and state](https://doc.saymyframe.com/guides/services.md). ### Analytics follows the router With a router, `firebase_analytics` logs a screen view for each screen the user sees. Without a router, it records only the events that the app logs itself. ### Reporting modules add up With more than one module for crash reporting or analytics, the app's `CrashReporter` or `AnalyticsService` forwards every call to each of them on its own, so a module that fails affects no other. See [Services and state](https://doc.saymyframe.com/guides/services.md#the-services). ## Some useful sets | Command | What you get | | --- | --- | | `smf create my_app` | Every question, in a terminal. | | `smf create my_app --no-input` | Only what every app needs: a Flutter app with a fallback start screen. | | `smf create my_app -m home,bottom_tabs` | A start screen, the router and tabs for the screens that features add. | | `smf create my_app -m home,settings,bottom_tabs,shared_preferences` | A start screen and a settings screen as two tabs, and preferences for the settings that the app remembers. | | `smf create my_app -m material_theme,gen_l10n,home,settings,bottom_tabs` | The same two tabs, with a light and a dark theme and the texts of the app in ARB files, in English and in Ukrainian. The settings screen has a row for the theme mode and one for the language, and the app remembers both. | | `smf create my_app -m home,bottom_tabs,settings,onboarding,gen_l10n,material_theme` | All of that, and an onboarding on the first launch. | | `smf create my_app -m home,bottom_tabs,settings,onboarding,local_notifications` | Notifications, with a page of the onboarding and a row of the settings screen that ask for the permission. | | `smf create my_app -m home,bottom_tabs,get_it,event_bus,bloc` | A start screen with tabs, a service container, events between parts of the app, and BLoC. | | `smf create my_app -m home,bottom_tabs,get_it,firebase_crashlytics,firebase_analytics` | Crash reports and analytics in Firebase, with screen views. | | `smf create my_app -m home,sign_in,bloc,bottom_tabs` | Sign-in in front of a start screen with tabs: nobody uses the app without an account. The account is under the tab Settings, and the app signs in with Firebase Authentication. | | `smf create my_app -m home,sign_in,riverpod,bottom_tabs --auth-mode guest` | The same screens with Riverpod, in an app that everyone may use. The sign-in opens when a user without an account taps the account under Settings. | | `smf create my_app -m home,onboarding,sign_in,bloc,bottom_tabs,gen_l10n,material_theme` | An onboarding on the first launch, then the sign-in, with a light and a dark theme, in English and in Ukrainian. The settings screen has the rows Account, Language and Theme. | | `smf create my_app -m home,sign_in,bloc,bottom_tabs,google_sign_in,apple_sign_in` | The sign-in with the buttons Continue with Google and, on iOS, Continue with Apple above the form. | | `smf create my_app -m home,bottom_tabs,firebase_messaging` | Push messages with Firebase Cloud Messaging, and the notifications through which a message shows in the foreground. | | `smf create my_app -m home,bottom_tabs,settings,onboarding,paywall,bloc` | A paywall that sells premium access with RevenueCat, the row Subscription and the row Restore purchases on the settings screen, and the page of the paywall in the onboarding. The API keys of RevenueCat and the addresses of the terms of use and the privacy policy go into `.env`. | | `smf create my_app -m home,bottom_tabs,dio` | A start screen with tabs, and a REST client for the code that you add, with its address in `.env`. | | `smf create my_app -m home,bottom_tabs,launcher_icons,native_splash,github_actions` | A start screen with tabs, an icon and a splash screen to replace with your own, and CI on GitHub Actions. | | `smf create my_app -m home,bottom_tabs,firebase_auth --auth-mode anonymous` | The session without the screens: a start screen with tabs, and an anonymous user that the app signs in when it starts. The screens that sign a user in are yours to write. | To see what a set of modules gives before anything is generated, add `--explain`. It prints the modules, the roles, the dependencies and what the machine is missing, and then stops. See the [`smf create` reference](https://doc.saymyframe.com/guides/smf-create.md#explain). ## Conflicts Asking for two providers of a role that an app has at most one of, such as `-m bloc,riverpod`, stops `smf create` with a usage error that names both. Keep one of them. # The `smf create` command Source: https://doc.saymyframe.com/guides/smf-create ```bash smf create [options] ``` `smf create` generates a Flutter app from modules in a new directory. Besides `smf help`, it is the only command of `smf`. `smf --version` prints the version, and `smf create --help` lists the options. ## Options | Option | What it does | | --- | --- | | `-m`, `--modules=` | The modules to add, separated by commas, such as `-m home,bottom_tabs`. The modules they need are added too. Without it, a run in a terminal asks for the modules. | | `--org=` | The organization in reverse domain notation. It starts the identifiers of the app. Without it, a run in a terminal asks; otherwise it is `com.example`. | | `-o`, `--output=` | The directory in which the app's own directory is created. The default is the current directory. | | `--on-conflict=` | What to do when the app's directory exists and is not empty; see [below](#an-existing-directory). The default is `prompt`. | | `--strict` | Stop instead of leaving out a module that cannot work, and on a warning about what the app is made of; see [lenient and strict](#lenient-and-strict). | | `--explain` | Print what would be generated and whether the machine is ready, then stop without changing anything; see [below](#explain). | | `--skip-external-setup` | Never install tools, log in or configure external services; print what to run instead. | | `--[no-]input` | Whether the run may ask questions in the terminal. With `--no-input`, everything comes from the options. | | `--start=` | The full path of the screen the app starts on, such as `/home`. It can name any route without required parameters that is outside the flow of a [guard](https://doc.saymyframe.com/guides/navigation.md#guards) and asks for no condition, and a run without a terminal needs it when several screens can start the app. An option of the router role. | | `--auth-mode=` | Who may use the app without an account: nobody (`required`, the default), everyone (`guest`), or everyone as an anonymous user (`anonymous`); see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#the-mode). An option of the auth role. | | `--locales=` | The languages of the app among those of the texts of its modules, such as `en,uk`. The first is the one the app uses when the device asks for none of them. The default is all of them, English first; see [Languages](https://doc.saymyframe.com/guides/languages.md#choosing-the-languages). An option of the localization role. | | `--verbose` | Report more of what happens. It can come before or after `create`. | | `-h`, `--help` | Print the usage of the command. | ## The name and the identifiers The app name becomes the Dart package name of the app in snake_case, so `My App`, `myApp` and `my-app` all become `my_app`. The package name is also the name of the app's directory under `--output`. The package name must start with a Latin letter and contain only letters, digits and underscores. It cannot be a keyword of Dart, Java or Kotlin, or the name of a package every Flutter app depends on, such as `flutter` or `collection`. Every part of the organization starts with a letter and has only letters, digits, hyphens and underscores, and no part is a keyword of Java or Kotlin. The identifiers of the app join the organization and the package name: | | `smf create my_app --org com.example` | | --- | --- | | Android application id and namespace | `com.example.my_app` | | iOS bundle id | `com.example.my-app` (bundle ids take hyphens, not underscores) | These are the ids of the flavor `prod`. The flavors `dev` and `staging` add `.dev` and `.staging`, so all three install next to each other; see [Flavors](https://doc.saymyframe.com/guides/flavors.md). ## Questions `smf create` asks questions only when it runs in a terminal, without `--no-input` and without `--explain`. It asks for: 1. the app name, unless it is given; 2. what to do with an existing directory, unless `--on-conflict` says; 3. the organization, unless `--org` gives it; 4. the modules, unless `-m` gives them: first the modules without a role by kind, such as the features, with `home` selected already, then a provider for each role, where Enter takes the first one (see [Create your first app](https://doc.saymyframe.com/getting-started/first-app.md#the-questions) and [the order of the roles](#the-order-of-the-roles)); 5. the provider of a role that the chosen modules require and that several modules provide, as the state manager for the screens of `sign_in`. Such a question names the module that requires the role and offers no None; 6. whether to set up what a check of the machine found missing, such as the Firebase CLI, unless the run skips external setup (see [the machine and external setup](#the-machine-and-external-setup)); 7. what the roles of the app leave open: the start screen, when several screens can start the app and `--start` does not say, and who may use the app without an account, in an app with a module that provides sign-in, unless `--auth-mode` says; 8. whether to run a step of a module after generation now, such as the tool that makes the app icon, or `dart tool/configure_firebase.dart dev` and after it the step that enables the sign-in methods in Firebase. Without a terminal, or with `--no-input`, the run asks nothing. Where it would have to ask, it stops with a usage error that says what to add: the app name, `--on-conflict`, a provider in `-m`, or `--start`. This is the error of `-m home,sign_in` without a state manager: ```text Several modules provide the state management role, which sign_in requires: bloc, riverpod. Add one of them to -m. ``` It does not stop for `--auth-mode`: without it, the app is in the mode `required`. Without `-m`, the app gets only what every app needs: a run without a terminal never takes a module that it was not given, so it does not take `home` either. ### The order of the roles The question of each role comes after the questions of the roles that require it, so that a role that an earlier answer needs offers no None. A role that an earlier answer requires and that only one module provides gets no question at all: `smf create` adds that module and says why. The questions come in this order, and a run asks those that the answers before leave open: 1. Features, and Infrastructure: the modules without a role. 2. Layout, Settings screen and Onboarding screen. Each requires the router, so the router has no question once one of them is chosen. 3. Router, when no earlier answer requires it. 4. Localization and Theme. 5. Push messages, and then Notifications, which push messages require. 6. Preferences, Dependency injection, State management and Events. 7. Authentication, and then REST API, which uses it. 8. Purchases, and then Values in .env, which the modules of the two roles before it read. 9. Crash reporting and Analytics, each of which takes several modules. 10. App icon, Splash screen and CI. So the questions go from what the user of the app sees to what gets the app released. Enter takes the first module of a question that takes one answer. So a run in a terminal that answers every question with Enter gets a provider for each of those roles, among them the app icon and the splash screen. The notifications role adds a step to the onboarding and an entry to the settings screen, so both screens are decided by the time of its question. In an app with every module, the onboarding, the theme, the localization and the notifications require the preferences, so `shared_preferences` comes without a question: ```text Adding shared_preferences: the only provider of the preferences role, which onboarding requires. ``` ## An existing directory When the app's directory exists and is not empty, `--on-conflict` decides: | Value | What happens | | --- | --- | | `prompt` | A run in a terminal asks what to do. The default answer keeps the directory and creates the app next to it; the others replace the directory or cancel the run. Without a terminal, the run stops with a usage error. | | `replace` | SMF generates the app first. Then it sets the old directory aside, moves the app into its place and deletes the old directory. If moving the app fails, the old directory goes back. | | `copy` | The app goes into a new directory next to it: `my_app copy`, or `my_app copy 2` if that exists too. | | `cancel` | Nothing is generated, and `smf create` exits with code 1. | SMF decides this before it does anything else, such as installing a tool. ## Lenient and strict By default, `smf create` is lenient. When a module cannot work in the app, such as a feature whose tab does not fit into the tab bar, it leaves that module out with a warning, plans the app again without it, and generates the rest. At the end it warns again about the modules the app is without. A run can also warn about what the app is made of while every module stays in it, such as an app whose routes mark none as a start screen. A lenient run prints such a warning and goes on, with the role that reported it: ```text [WARN] [role:router]: No route is marked as a start candidate, so the app starts on its fallback screen. Choose a start route with --start. ``` With `--strict`, a problem of a module stops the run with exit code 1 before anything is generated, and so does a warning about what the app is made of. A warning of the checks of the module model stops the run before the machine is checked, and a warning of a choice of a role, such as the start screen, stops it before the app is rendered. Use `--strict` in scripts and CI, where an app without a module you asked for, or an app that does not come out as you asked, is a failure. This is a strict run of an app with `settings` alone, which has no screen to start on and no main navigation that leads to the settings screen: ```text Generation stopped because of 2 warnings about the app. Without --strict, the run goes on after them. warning [role:router] router.no_start: No route is marked as a start candidate, so the app starts on its fallback screen. Choose a start route with --start. warning [role:router] router.no_main_navigation: No module provides the layout role, so the app has no main navigation to lead to the destination /settings (settings). Choose a provider of the role, or open it from a screen of yours with context.nav. ``` A warning about the machine, such as a tool that a step after generation needs, never stops a run, strict or not. Each warning about the app has a code: the id of the role that reports it, a dot, and a name. The built-in roles report these: | Code | What the app is made of | | --- | --- | | `router.no_start` | The app has routes, but no route can start it, and `--start` names none. It starts on the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen). | | `router.no_main_navigation` | The app has destinations besides the one that it starts on, but no layout, so no main navigation leads to them. | | `router.ambiguous_routes` | Two routes of a module both match some locations, which go to the route declared first. | | `localization.untranslated` | Texts of a module have no translation into a language of the app, which shows them in English there. | | `localization.unsupported_language` | A text of a module has a translation into a language that no app can be in, so the app leaves that language out. | | `localization.unnamed_language` | The setting of the language shows a language of the app by its code, since the role has no name for it. | | `auth.open_account_routes` | Routes ask for an account, but no guard of the app stands for it, so every user gets to them; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#an-app-without-the-screens). | | `auth.no_equivalent_sign_in` | On iOS, the app offers a sign-in of a third party, such as Google, and no way to sign in that the App Store takes as its equivalent, as its guideline 4.8 asks; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). | | `pipeline.unused_option` | An option of a role that the app does not have, which nothing reads. | `smf create` has a hidden option for apps that warn on purpose, as some apps of SMF's own CI do: with `--strict`, `--allow-warning=` lets the run go on after a warning with that code, which it still prints. Give it once for each code. A value that is not the form of a code is a usage error. Some problems stop the run in either mode. A problem that no single module causes, such as a usage error, is one of them. So is the problem of a module that no app can be made without, such as `flutter_core`, the only provider of the app entry. `smf create` does not leave such a module out, and stops with its problem and how to fix it, such as a Flutter SDK that is too old. ## Explain `--explain` runs everything that decides the app, which means the selection of modules, the checks of the module model and the checks of the machine, and prints the result. It never asks, installs or logs in, and it generates no file. Where a real run would ask which module provides a role, it takes the first one and names the others. It makes no choices either, so it shows the warnings of the checks of the module model and not those of the choices, and with `--strict` it stops only on the first. ```bash smf create my_app --org com.example -m home,bottom_tabs,get_it,event_bus --explain ``` ```text App my_app of com.example Android application id: com.example.my_app iOS bundle id: com.example.my-app Directory: /Users/you/projects/my_app Modules home: requested bottom_tabs: requested get_it: requested event_bus: requested flutter_core: the only provider of the app entry role, which every app needs go_router: the only provider of the router role, which home requires Roles Layout: bottom_tabs Dependency injection: get_it Events: event_bus App entry: flutter_core Router: go_router Dependencies get_it ^9.3.0 (get_it) event_bus ^2.0.1 (event_bus) flutter from the flutter SDK (flutter_core) go_router ^17.5.0 (go_router) Dev dependencies flutter_test from the flutter SDK (flutter_core) flutter_lints ^6.0.0 (flutter_core) Machine βœ“ Flutter SDK ``` Depending on the app, the report has more sections. "Left out (lenient mode)" lists the modules that the app would be without, and why. "Order of contributions" shows, for code that several modules put into the same place, the order they come in and the reason for it. "After generation" lists the commands that would run in the new app, such as `dart tool/configure_firebase.dart dev` of the Firebase modules, each step that continues another under it, and the notice of a step that has one. This is that section for an app with `sign_in`: ```text After generation dart tool/configure_firebase.dart dev (firebase_core) then dart tool/enable_firebase_sign_in.dart (firebase_auth) If the app signs in with Google, it also gives Google the app's name and the Firebase CLI account's email for its consent screen, registers the SHA-1 and SHA-256 of this machine's Android debug key (creating the key if there is none, as the first debug build would), downloads the app's Firebase files again and writes the iOS URL scheme into ios/Runner/Info.plist. A run asks before it runs this step, and leaves it for later when it cannot ask. ``` "By hand" lists the [steps by hand](#steps-by-hand) of an app that has any, after "After generation": the link to their guide, then each step with its id, its title and, in parentheses, who lists it. These are the lines of an app with `apple_sign_in`: ```text By hand https://doc.saymyframe.com/setup?steps=app_entry.ios_app_id,firebase_auth.apple_provider,firebase_auth.apple_revocation app_entry.ios_app_id: In Xcode, sign the iOS app with your paid Apple Developer team (apple_sign_in) firebase_auth.apple_provider: Turn on Sign in with Apple in Firebase Authentication (firebase_auth) firebase_auth.apple_revocation: Give Firebase your Sign in with Apple key, so that deleting an account works (firebase_auth) ``` "Machine" gets a line for each check a module needs, with instructions for what is missing. These are the lines of the same app on a machine without the Firebase CLI: ```text Machine βœ“ Flutter SDK βœ— Firebase CLI (for firebase_core): missing Install it with "npm install -g firebase-tools", or see https://firebase.google.com/docs/cli. An interactive run offers to set it up. βœ— Firebase login (for firebase_core): missing Install the Firebase CLI, then log in with "firebase login", or on a remote machine, such as over SSH, with "firebase login --no-localhost". βœ“ FlutterFire CLI 1.4.1 or a later 1.x (for firebase_core) βœ“ Xcode project tools of flutterfire (for firebase_core) βœ“ Setup of the Xcode project on a Mac (for firebase_core) βœ— Firebase CLI 15.34.0 or later (for firebase_auth): missing Install it with "npm install -g firebase-tools", or see https://firebase.google.com/docs/cli. ``` ## The machine and external setup Before it generates anything, `smf create` checks the machine: the Flutter SDK for every app, and whatever the modules need, such as the Firebase CLI for the Firebase modules. The Flutter SDK must satisfy the SDK constraints of the app, which means Flutter 3.44 or newer, or the run stops, as [troubleshooting](https://doc.saymyframe.com/guides/troubleshooting.md#the-flutter-sdk-is-missing-or-too-old) shows. SMF checks the machine for a module after the modules it depends on, wherever you named them, so a check can count on a tool that an earlier one installed. When something is missing, the checks of the built-in modules only warn and print instructions. In a terminal, SMF offers to set up what it can. Each question says what the check found, such as a tool that is missing or an older version of it, and how to set it up by hand, then asks whether to set it up now. With `--skip-external-setup`, it never installs anything, logs in or sets up an external service, and prints the instructions instead. Some modules run a command in the new app, such as `dart tool/configure_firebase.dart dev`. A module marks such a step as skippable when the app is complete without it, as `firebase_core` does. A skippable step may not run, because the run has no terminal, skips external setup or lacks a tool the step needs. It may also fail, or you may leave it for later. In each case `smf create` still creates the app and prints the command to run in it later, with the reason. Nothing went wrong when a step is left for later, so the run does not warn of it. That is a step that you chose to run later, a step that a run without a terminal or with `--skip-external-setup` holds back, and a step that continues one of these. The run lists such steps after the line that the app is created, in the order in which they run. In an app with [steps by hand](#steps-by-hand), the line about them follows the list, and the lines on running the app come last. When the command needs a tool that the machine lacks, the reason names that tool too, as on a machine without the Firebase CLI: ```text Created my_app in /Users/you/projects/my_app. One step is left for later. Run it in the app: Configuring Firebase with flutterfire (the run skips external setup, and Firebase CLI and Firebase login are missing): dart tool/configure_firebase.dart dev Then run the app: cd /Users/you/projects/my_app flutter run ``` The run warns of a step when its command fails, or when it would have run the step and a tool that the step needs is missing, as after you decline to install the Firebase CLI in a terminal. The warning comes before the line that the app is created: ```text [WARN] Configuring Firebase with flutterfire is not done, because Firebase CLI and Firebase login are missing. Run it in the app: dart tool/configure_firebase.dart dev ``` A step may come with a notice: something to know before it runs that its description does not tell, such as a side effect of the tool that it runs. A run in a terminal asks before it runs such a step, with the notice in the question, and a run that cannot ask leaves the step for later. The notice follows the command of a step that is left for later, and `--explain` shows it under the command. The step of `firebase_auth` that enables the sign-in methods in the Firebase project is such a step, and it continues the configuration of Firebase. When that command is left for later, the step waits with it. The list then has both, and the step refers to the command that it continues by its number: ```text 2 steps are left for later. Run them in the app, in this order: 1. Configuring Firebase with flutterfire (the run skips external setup, and Firebase CLI and Firebase login are missing): dart tool/configure_firebase.dart dev 2. Enabling the sign-in methods of the app in its Firebase project (it runs after step 1): dart tool/enable_firebase_sign_in.dart If the app signs in with Google, it also gives Google the app's name and the Firebase CLI account's email for its consent screen, registers the SHA-1 and SHA-256 of this machine's Android debug key (creating the key if there is none, as the first debug build would), downloads the app's Firebase files again and writes the iOS URL scheme into ios/Runner/Info.plist. ``` A step that the app cannot do without either runs or stops the run. ## Steps by hand Some of the setup of an app is out of reach of any command, such as uploading the APNs key of push messages to Firebase, or signing the iOS app with a paid Apple Developer team. The modules of the app list such steps, and the run ends with them, after the steps that are left for later. This is the end of a run for an app with `firebase_analytics` that skips external setup: ```text Created my_app in /Users/you/projects/my_app. One step is left for later. Run it in the app: Configuring Firebase with flutterfire (the run skips external setup, and Firebase CLI and Firebase login are missing): dart tool/configure_firebase.dart dev Finish the setup by hand in one step: https://doc.saymyframe.com/setup?steps=firebase_analytics.google_analytics Then run the app: cd /Users/you/projects/my_app flutter run ``` A service knows each [flavor](https://doc.saymyframe.com/guides/flavors.md#what-repeats-for-each-flavor) of the app as an app of its own, so such a step repeats for each flavor that needs it. The link opens [Finish the setup](https://doc.saymyframe.com/setup.md) with the steps of the app in the order to do them, each with a link to its guide, click by click. Do the steps once the commands that are left for later have run. The run asks nothing about these steps, so a run without a terminal, with `--no-input` or with `--skip-external-setup` prints the same lines. The README of the app lists the same steps, with the same link, in its first section, "Finish the setup". Without the link of a run, the page lists every step of the built-in modules. ## Exit codes | Code | Meaning | | --- | --- | | `0` | The app was created, or `smf` printed help, the version or the report of `--explain`. | | `1` | Generation failed, and the messages say why: an error of a module or a warning about the app with `--strict`, an error of a module that every app needs, a machine without what the app needs, such as a Flutter SDK that is missing or too old, a failed command, or `--on-conflict cancel`. If the app was generated already, it stays in a temporary directory that the message names. | | `64` | The command line was wrong or incomplete: an unknown option or module, a missing app name, a value of `--allow-warning` that is not a code, or a question that a run without a terminal cannot ask. | | `70` | An unexpected error, which is a bug of `smf` or of a module. Run again with `--verbose` for the full log, and please [report it](https://github.com/saymyframe/smf_flutter_cli/issues). | | `130` | The run was cancelled with Ctrl-C, by the end of the input, with Cancel in the question about an existing directory, or, on macOS and Linux, with `SIGTERM`. Nothing of the app is left behind. | ## In scripts and CI A run for a script names everything and asks nothing: ```bash smf create my_app \ --org com.example \ -m home,bottom_tabs,get_it,bloc \ --no-input \ --skip-external-setup \ --strict \ --on-conflict replace ``` SMF's own CI generates its apps the same way, without a terminal and with `--strict`. It checks each app with `flutter analyze` and runs tests in it, such as the start-up of Firebase, and it starts apps on an Android emulator and an iOS simulator. Every night it does so on every stable release of Flutter that the apps allow. # Flavors Source: https://doc.saymyframe.com/guides/flavors Every app that `smf create` generates has three native flavors, `dev`, `staging` and `prod`. You get them without an option or a module. They are plain Android and Xcode settings, so the app has no package for them. Each flavor has an id of its own, so all three install next to each other on one device: | Flavor | Android application id | iOS bundle id | Name on the device | | --- | --- | --- | --- | | `dev` | `com.example.my_app.dev` | `com.example.my-app.dev` | My App Dev | | `staging` | `com.example.my_app.staging` | `com.example.my-app.staging` | My App Staging | | `prod` | `com.example.my_app` | `com.example.my-app` | My App | The ids start with the organization and the name of the app. `smf create --explain` prints the ids of `prod`, and the section "Flavors" of the README of the app lists all of them. ## Run and build a flavor ```bash flutter run # dev flutter run --flavor staging flutter build apk --flavor prod flutter build appbundle --flavor prod flutter build ipa --flavor prod ``` A `flutter` command without `--flavor` builds `dev`, because `pubspec.yaml` says `default-flavor: dev`. That holds in release mode too: `flutter build appbundle` is a release of `dev`, under its id. So a build for a store always names `--flavor prod`. On Android, a release build is signed with the debug key until `android/app/build.gradle.kts` has a signing config of yours, and a store refuses such a build. [Sign the app](https://docs.flutter.dev/deployment/android#sign-the-app) tells how. The name of the flavor is part of the name of each APK and app bundle, as in `build/app/outputs/flutter-apk/app-prod-release.apk` and `build/app/outputs/bundle/prodRelease/app-prod-release.aab`. An app with the module [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) also passes `--dart-define-from-file=.env` to each of these commands; see [Values in .env](https://doc.saymyframe.com/guides/env.md). The values of `.env` are not tied to a flavor. ## Read the flavor in code The app has one entry, `lib/main.dart`, for all flavors, so add no `main_.dart`. Code reads the flavor from `appFlavor` of Flutter: ```dart import 'package:flutter/services.dart'; final showDebugMenu = appFlavor != 'prod'; ``` `appFlavor` is a constant of the build. `flutter test` runs as `dev`, the default flavor. ## Run configurations An app with a provider of [the values in .env](https://doc.saymyframe.com/guides/env.md), such as `dart_define`, has a run configuration for each flavor, named after the app and the flavor, such as `my_app staging`. Each passes the flavor and the arguments that the values need: | IDE | Where they are | What runs them | | --- | --- | --- | | VS Code | `.vscode/launch.json` | Run and Debug (F5) starts the one that you select in the Run and Debug view. The Run and Debug links above `main()` and above a test, and the Testing view, always use the one of `dev`, the only one that is a template of those launches (`templateFor`). | | Android Studio | `.run/.run.xml` | Each is a run configuration of its own. A test that you run from Android Studio gets none of these arguments, so run tests from a terminal with them. | An app without such a provider has no run configurations. There, an IDE runs `dev`, and you pass `--flavor` as an argument for another flavor. ## Xcode Each flavor has a shared scheme, `ios/Runner.xcodeproj/xcshareddata/xcschemes/.xcscheme`, and the build configurations `Debug-`, `Profile-` and `Release-`. In Xcode, select the scheme of a flavor. It builds that flavor, with its id, its name and its `appFlavor`, whatever the last `flutter` command did. The scheme `Runner` stays in the project, on the plain `Debug`, `Profile` and `Release` configurations, and those have the id and the name of `prod`. It takes `appFlavor` from `ios/Flutter/Generated.xcconfig`, which holds what the last `flutter` command wrote there and has no flavor after a fresh `flutter pub get`. In an app with Firebase, a run of the scheme `Runner` can then stop at start-up, because the app cannot tell which options to use. `flutter build ios --config-only --flavor ` gives that file a flavor. ## What repeats for each flavor A service that knows your app by its id, such as a store or a push provider, knows each flavor as an app of its own. The setup of such a service repeats for each flavor that needs it. SMF does not hide this, because the services work that way with or without SMF. A flavor that never reaches a store or a real user may need none of it. | What | How often | | --- | --- | | [Firebase](https://doc.saymyframe.com/guides/firebase.md#one-project-for-each-flavor) | Each flavor runs `dart tool/configure_firebase.dart` once. Flavors may share a project or have one each. | | The steps by hand in a Firebase project | Once for each project, or once for each app of a project, as [the guide of each step](https://doc.saymyframe.com/setup.md) says. | | The App ID of the iOS app | Once for each bundle id that you sign and that needs a capability. | | Products in App Store Connect and Google Play Console | For each id that sells. A store knows `com.example.my_app.staging` as another app. | | [Values of CI](https://doc.saymyframe.com/guides/ci.md#values-for-each-environment) | One GitHub environment for each flavor that you build there. | The icon and the splash screen are the same for all flavors; see [App icon and splash screen](https://doc.saymyframe.com/guides/app-icon-and-splash.md). ## Add or remove a flavor After generation, the flavors are text in the files of your app. SMF does not touch them again. These steps add a flavor `qa`. The name has no hyphen, since Flutter splits the name of a build configuration at it. **1. Android.** Add it to `productFlavors` in `android/app/build.gradle.kts`, with an id suffix and a name on the device: ```kotlin create("qa") { dimension = "default" applicationIdSuffix = ".qa" manifestPlaceholders["appName"] = "My App QA" } ``` **2. iOS.** In `ios/Runner.xcodeproj/project.pbxproj`, each of the three configuration lists gets `Debug-qa`, `Profile-qa` and `Release-qa`, copies of those of another flavor. In Xcode, that is **Duplicate** under the configurations of the project. In the Runner target, give the three copies the bundle id in `PRODUCT_BUNDLE_IDENTIFIER` and the name on the device in `APP_DISPLAY_NAME`. Then copy `xcschemes/staging.xcscheme` to `xcschemes/qa.xcscheme` and replace `-staging` with `-qa` in it. The schemes of the app already have the pre-action that Flutter needs, so a copy keeps it. **3. Run configurations.** If the app has them, add one to `.vscode/launch.json`, and copy `.run/staging.run.xml` to `.run/qa.run.xml`. **4. Firebase.** If the app has `firebase_core`, copy `lib/firebase_options_staging.dart` to `lib/firebase_options_qa.dart`, add the flavor to the `switch` in `lib/firebase_options_of_flavor.dart` and to `_flavors` at the top of `tool/configure_firebase.dart`. Then configure it as for [any flavor](https://doc.saymyframe.com/guides/firebase.md#one-project-for-each-flavor). **5. CI.** If the app has `github_actions`, add the flavor to `options` under `workflow_dispatch` in `.github/workflows/ci.yml`. Then check it: ```bash flutter build apk --debug --flavor qa flutter build ios --config-only --flavor qa ``` To remove a flavor, undo the same places. `default-flavor` in `pubspec.yaml` has to name a flavor that stays, and the plain configurations in the Xcode project stay as they are. A setting that you add to the Runner target by hand goes into each of its twelve build configurations, the three plain ones and the nine of the flavors. ## A module of your own The flavors are constants of the app entry role, `AppEntryRole.flavors`, each an `AppFlavor`, so a module reads their names and ids from there rather than writing them out. [What a provider of the app entry keeps to](https://doc.saymyframe.com/extending/role-provider.md#the-app-entry) describes the rest. # Navigation Source: https://doc.saymyframe.com/guides/navigation In an app with a router, every screen that a feature declares has a route, and the router role generates a typed way to reach it: `context.nav`. Screens navigate through it instead of through go_router, so their code works with any router. ## Paths and names A feature declares its routes relative to its own namespace, the path `/`. The feature `home` declares the route `/`, so its full path is `/home`. Its full name, `home.home`, joins the id of the feature and the name of the route. The examples on this page use a feature `catalog` that declares two routes: a list at `/` and, below it, the details of an item at `item/:id`, which takes the path parameter `id`, an `int`, and the optional query parameter `color`, a `String`. Their full paths are `/catalog` and `/catalog/item/:id`, and their full names `catalog.list` and `catalog.item`. ## `context.nav` `context.nav` has a getter for each feature and a method for each of its routes, with the parameters of the route: ```dart context.nav.catalog.list() context.nav.catalog.item(id: 5, color: 'red') ``` Each returns a `NavLink`, which navigates in one of three ways: | Method | What it does | | --- | --- | | `go()` | Shows the location with the chain of its parents below it as the stack: `go()` to an item shows the list below it, so Back returns to the list. | | `push()` | Shows the location on top of the current stack. Its `Future` completes with the value the page returns when it closes. | | `replace()` | Replaces the page on top of the stack with the location. | ```dart TextButton( onPressed: () async { final color = await context.nav.catalog.item(id: 5).push(); // The item page closed, returning a color or null. }, child: const Text('Item 5'), ) ``` Behind the methods is a location class for every route, generated into `lib/core/router/navigation.dart`: ```dart title="lib/core/router/navigation.dart" /// The location of `catalog.item`: `/catalog/item/:id`. final class CatalogItemLocation extends AppLocation { /// Creates the location with the values of the route. const CatalogItemLocation({required this.id, this.color}); /// The value of the path parameter `id`. final int id; /// The value of the query parameter `color`. final String? color; @override String get routeName => 'catalog.item'; @override String get path => _withQuery('/catalog/item/$id', {'color': color}); @override AppLocation get parent => const CatalogListLocation(); } ``` `context.nav` works with any context of the app, even one above the router, because the generated router navigates itself rather than looking up the router of the context. ## Parameters A route takes values from its location. Path parameters, such as `:id`, are always required, and query parameters, such as `?color=red`, can be required or optional. A value is a `String`, an `int`, a `double` or a `bool`. The screen of the route takes each as a named parameter of its constructor, nullable when it is optional: ```dart const ItemScreen({required this.id, this.color, super.key}); ``` With go_router, the router parses an `int` or a `double` from the location with `tryParse`, and a `bool` is `true` or `false` exactly. When a required value is missing or has the wrong type, as in `/catalog/item/abc`, the location shows the error screen of go_router instead of the page. An optional value that is missing or has the wrong type reaches the screen as `null`. ## The start screen A feature can mark a route as one that the app can start on, as `home` does with `/home`. The app opens on it, and the path `/` redirects there. When several routes can start the app, such as `/home` and `/catalog`, `smf create` asks which one: ```text ? Which screen does the app start on? (↑↓ to move, enter to choose) ❯ /home (home) /catalog (catalog) ``` A run without a terminal takes the full path from `--start`, such as `--start /catalog`, and stops with a usage error without it. `--start` can also name a route that no feature marks, as long as the route has no required parameters, is outside the flow of a [guard](#guards) and asks for no condition. In a terminal it answers the question in advance. When no route can start the app, `/` shows the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen), which names the app and tells you where its first screen goes. If the app has routes but no feature marks one, `smf create` warns and suggests `--start`. The warning has the code `router.no_start`, and `--strict` stops on it; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). ## Tabs and other main navigation With a layout, such as [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), the routes that features mark as destinations form the main navigation of the app: a tab for each, in the order of the features. The app opens on the tab of its start screen. The settings screen of [`settings`](https://doc.saymyframe.com/modules/settings.md) is a destination too, so with it the app has a Settings tab. - Every tab keeps its own stack while another tab is selected. The routes below a destination stay in its tab. - The other top-level routes are outside the main navigation. They show over the tabs, and going to one leaves the tabs behind. - `go()` to a location in a tab selects that tab and makes the chain of the location its stack. `go()` to a location outside the main navigation replaces the whole stack with its chain. - `push()` from a page in a tab shows the location on top of the selected tab's stack, whichever tab the location belongs to, and the selected tab stays. - The app shows the main navigation only once. So on a page shown over it, `push()` and `replace()` of a location in the main navigation throw a `StateError` that says to use `go()` instead, and the stack stays as it is. On a page with no main navigation below it, `push()` brings the main navigation back on top with the location. ## Guards A feature can keep the user from the rest of the app until a condition holds. [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) does: on the first launch, the app shows the onboarding until the user finishes it. [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) does in an app that nobody uses without an account: the app shows the sign-in until the user is signed in. Such a feature declares a guard: the condition, and one of its own routes to show while the condition does not hold, the target of the guard. The target and the routes below it are the flow of the guard. A guard over the whole app is a gate. While a gate does not allow, the app shows the target in place of every location outside the flow, whoever asks for it: the start of the app, the platform, or `go()`, `push()` and `replace()` of the routes of any feature. Such a `push()` completes with `null` at once. Once the gate allows, the app leaves the flow by itself. It shows the location that was asked for in the meantime, or the screen that the user was on, or the screen that it starts on. The routes of a flow show only while its guard does not allow. Once the onboarding is finished, `go()` to `/onboarding`, or a link to it, shows the screen that the app starts on. So no code navigates into the flow of a gate. A screen of the flow only changes what the guard reads, as Skip and Get started of the onboarding do, and the app shows the flow and leaves it. With several gates, the app asks them in the order of a first launch, whatever the order of the modules: the onboarding comes before the sign-in. ### A guard for some routes A guard can also keep the user from some routes only: the routes that need what it stands for, such as an account. The rest of the app shows whatever that guard says. The guard `sign_in.hasAccount` of `sign_in` is one: it keeps a user without an account from the screen of the account, and its target is the sign-in. | While such a guard does not allow | What the app does | | --- | --- | | `go()`, `push()` or `replace()` of one of its routes | It opens the target of the guard over the page that the user is on, and the request waits. | | The user goes back from the target. | The user is on the page they were on. A `push()` that waited completes with `null`. | | The guard starts allowing. | It closes the pages of the flow and does what was asked. `push()` shows the route over the page that the user was on and completes with the value of its page, `go()` shows it in place of the stack, and `replace()` in place of that page. | | A link to one of its routes opens the app. | The target opens over the screen that the app starts on. | When the guard stops allowing, the app closes the pages of its routes, with the pages over them. The user is then on the page below them, or on the screen that the app starts on when no page is below. Until such a guard allows, the routes of its flow show like any route: | How a page of the flow is asked for | What the app shows | | --- | --- | | A screen opens it with `push()`, as a button that leads a guest to the sign-in does. | The page over that screen, so back leads back. | | A screen goes to it with `go()`. | The page in place of the stack, with no way back. | | A link asks for it. | The page over the screen that the app starts on, so back leads into the app. | Two cases are known limits, both for a link that opens the app behind a gate that does not allow, as on a first launch with an onboarding. A link to a route that such a guard keeps the user from opens no target. If the guard still does not allow once the gate does, the link is lost, and the user is on the screen that the app starts on. A link to a page of the flow of such a guard is lost behind a gate with another flow too. ### After a guard changed A screen neither closes itself nor navigates after it changed what a guard reads: the app has done both by then. That goes for a screen of a flow that made its guard allow, and for a screen that a guard keeps the user from once the screen made that guard stop, as a screen with a sign-out button does. A `pop()` after the change closes the page that is on top by then, which is the page that the user asked for or the page below the one that the app closed. ### In the files of the app In an app with guards, `lib/core/router/app_router.dart` has more than the router: | | | | --- | --- | | `routeGuards` | The guards of the app, in the order the app asks them. The gates come first, and the first one that does not allow decides. The guards for some routes come after them, each with the names of those routes in its `routes`. | | `redirectOf(routeName)` | The location that the guards show when the app is asked for a route, or `null` when they let the user see it. | | `flowIsOver(routeName)` | Whether the route is in a flow that is over. | | `guardChanges` | Notifies its listeners when a guard starts or stops allowing. | An app without guards has none of them. In an app with guards, a guard of your own is one more `RouteGuard` in `routeGuards`. A gate goes at the place among the gates where its screen comes on a first launch: a guard of the first launch goes before one that asks who the user is. A guard for some routes goes after the gates. The section "Router" of the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app says what each needs. [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md#a-guard) shows how a feature module declares a guard. `--start` cannot name a route in the flow of a guard, and `smf create` stops with a usage error that names the guard. It refuses a route that asks for a condition too. [Guards of routes](https://doc.saymyframe.com/concepts/guards.md) describes what a router does with the guards, in which order the app asks them and where the user comes back to. [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md) describes the guards for some routes. ## Following the screens Modules can follow the screen the user sees through the router, whichever router it is. [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) logs a screen view for each screen, with the full name of its route, such as `home.home`. Switching tabs counts as seeing another screen. Pages that the app shows with a navigator directly, such as with `Navigator.push`, and dialogs are not screens of the router. ## Routes of your own SMF generates the navigation from the routes of the modules when it creates the app. A screen that you add later needs its route in three places, which agree on the full name of the route and on its path. ### A screen below an existing one For a screen `AboutScreen` below the home screen, at `/home/about`, the three places are: 1. The screen, a widget in the directory of its feature, here `lib/features/home/about_screen.dart`. Its `const` constructor takes each value of the route as a named parameter, and this route has none. 2. The location, in `lib/core/router/navigation.dart`. `AppLocation` is a sealed class, so the location class goes into that file, and the class of the routes of the feature gets a method for it: ```dart title="lib/core/router/navigation.dart" /// The location of `home.about`: `/home/about`. final class HomeAboutLocation extends AppLocation { /// Creates the location. const HomeAboutLocation(); @override String get routeName => 'home.about'; @override String get path => '/home/about'; @override AppLocation get parent => const HomeHomeLocation(); } // ... /// The routes of the module `home`. final class HomeRoutes { // ... /// The route `home.about`: `/home/about`. NavLink about() => NavLink(_context, const HomeAboutLocation()); } ``` 3. The route itself, where the module that provides the router keeps the routes. With go_router, that is a `GoRoute` in `lib/core/router/app_router_factory.dart`, named by the full name of the route, here below the route of the home screen. The file imports the file of the screen with a prefix, `about` in this example: ```dart title="lib/core/router/app_router_factory.dart" GoRoute( path: '/home', name: 'home.home', builder: (context, state) => const screen0.HomeScreen(), routes: [ GoRoute( path: 'about', name: 'home.about', builder: (context, state) => const about.AboutScreen(), ), ], ), ``` Then navigate to the screen as to the screens of the modules, with `context.nav.home.about().go()`. ### A screen of a new feature A feature of your own, such as a catalog at `/catalog`, has its screen in a directory of its own, `lib/features/catalog/`. Its route is a top-level one, so its location class has no `parent`. In `lib/core/router/navigation.dart`, the feature also gets a class of its routes, and `AppNav` a getter that returns it: ```dart title="lib/core/router/navigation.dart" /// The location of `catalog.catalog`: `/catalog`. final class CatalogCatalogLocation extends AppLocation { /// Creates the location. const CatalogCatalogLocation(); @override String get routeName => 'catalog.catalog'; @override String get path => '/catalog'; } // ... final class AppNav { // ... /// The routes of the feature `catalog`. CatalogRoutes get catalog => CatalogRoutes._(_context); } // ... /// The routes of the feature `catalog`. final class CatalogRoutes { const CatalogRoutes._(this._context); final BuildContext _context; /// The route `catalog.catalog`: `/catalog`. NavLink catalog() => NavLink(_context, const CatalogCatalogLocation()); } ``` Code then navigates with `context.nav.catalog.catalog().go()`. Where the `GoRoute` of the screen goes decides how the app shows it. As a route of the list `routes` of the router, after `_mainNavigationRoute`, the route of the main navigation, the screen shows over the main navigation. To give it a tab instead, add a `Destination` to `appDestinations`, with a function for its label, and a branch for it at the same index of the `branches` that `_mainNavigation()` creates: ```dart title="lib/core/layout/destination.dart" const List appDestinations = [ Destination(label: _homeHomeLabel, icon: Icons.home), Destination(label: _catalogCatalogLabel, icon: Icons.list), ]; String _homeHomeLabel(BuildContext context) => 'Home'; String _catalogCatalogLabel(BuildContext context) => 'Catalog'; ``` The label is a function, so that the list stays `const` and the tab follows the language of the app. In an app with [languages](https://doc.saymyframe.com/guides/languages.md), return a text of the app from it, such as `context.l10n.catalogLabel`. In the branch, the file of the screen is imported with the prefix `catalog`: ```dart title="lib/core/router/app_router_factory.dart" StatefulShellBranch( initialLocation: '/catalog', observers: _observers(), routes: [ GoRoute( path: '/catalog', name: 'catalog.catalog', builder: (context, state) => const catalog.CatalogScreen(), ), ], ), ``` The branches are in the order of the destinations. The router calls `_mainNavigation()` again each time the main navigation leaves its pages, so what a branch has of its own, such as a key of its navigator, is created inside that function. The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app has the same steps in its section on the router, so an agent adds a route this way too. ### Navigate through `context.nav` Navigate through `context.nav` and not through go_router itself. The navigation of the app asks the guards before a `go()`, a `push()` or a `replace()`, keeps the request that waits for a guard, and refuses to put a location of the main navigation on a page shown over it. The modules that follow the screens know a screen by the name of its route. # Services and state Source: https://doc.saymyframe.com/guides/services A generated app can have services for events, analytics and crash reporting, each from a role. The code of the app gets them from a DI container when the app has one, and from plain functions when it does not. Either way, the screens reach them only through their state. The preferences, which remember the settings of the app, come from a role too. The code of the app gets them when the app starts, or from the container, and [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md) describes how. Sign-in comes from a role as well, but not as a service of the container. The code of the app reaches it through `appSession`, a top-level variable; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md). The notifications and the push messages work the same way, through `appNotifications` and `appPush`; see [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md). ## The services | Role | Service | File | Module | | --- | --- | --- | --- | | Events | `CommunicationService` | `lib/core/events/communication_service.dart` | [`event_bus`](https://doc.saymyframe.com/modules/event-bus.md) | | Analytics | `AnalyticsService` | `lib/core/analytics/analytics_service.dart` | [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) | | Crash reporting | `CrashReporter` | `lib/core/crash_reporting/crash_reporter.dart` | [`firebase_crashlytics`](https://doc.saymyframe.com/modules/firebase-crashlytics.md) | Each role generates the interface of its service and a function that returns the app's service: `createCommunicationService()`, `createAnalyticsService()` and `createCrashReporter()`. The function returns the same instance every time. An app can have several modules for analytics or crash reporting, and its service then forwards every call to each of them on its own. A module whose service throws or fails keeps no other from the call, and its failure reaches neither the code that called nor the handlers of uncaught errors. In debug mode, the service of the app prints the failure. Each analytics module gets its own copy of the parameters of a call. The app leaves out a service that fails to be created or to start, and works with the others. The code of the app uses the interface and never the module behind it, so you can replace a module without touching that code. ## With a DI container With [`get_it`](https://doc.saymyframe.com/modules/get-it.md), each service role registers its service in the container as a lazy singleton, the preferences role too, and other modules register services of their own. `registerDependencies()` does this in `bootstrap()`, before the first frame. The generated code follows one rule, and the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app gives it to agents for the code that they add: only the composition file of a feature takes services from the container. The composition file, `lib/features//_composition.dart`, creates what the screens of the feature need, such as a Cubit, with `resolve()` of `lib/core/di/service_locator.dart`. Everything else gets its services as parameters, and the screens talk only to their state. With BLoC, the composition file creates the Cubit: ```dart title="lib/features/counter/counter_composition.dart" import 'package:flutter_bloc/flutter_bloc.dart'; import '../../core/di/service_locator.dart'; import 'counter_store.dart'; /// Creates the cubit of the counter screen with the services it needs. CounterCubit createCounterCubit() => CounterCubit(resolve()); ``` and the screen provides it with `BlocProvider(create: (_) => createCounterCubit(), ...)` and reads it with `context.read()`. With Riverpod, the composition file bridges the container to a provider: ```dart title="lib/features/counter/counter_composition.dart" import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/di/service_locator.dart'; import 'counter_store.dart'; /// The store of the counter, from the service locator of the app. final counterStoreProvider = Provider( (_) => resolve(), ); ``` and the notifiers of the feature read it with `ref`. [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md) builds this feature from start to end. A value known only at run time, such as the id of the item that a screen shows, is a parameter of the function in the composition file, as in `DetailsCubit createDetailsCubit(int id)`. Elsewhere, a factory class creates objects with such values: it takes its services in its constructor, creates the objects in a method such as `call(int id)`, and is registered like any other service, so the code that needs it gets it as a parameter. In tests, `resetDependencies()` of `lib/core/di/dependencies.dart` disposes of the services that the container created, in the reverse order of their registration, and removes them all, so that `registerDependencies()` can register them again. ## Without a container Without a DI container, call the function of the service where you need it, such as in the code that creates a Cubit: ```dart final analytics = createAnalyticsService(); ``` It returns the same service every time, so every part of the app shares it. Don't create another one from the module's own implementation, such as `createEventBusCommunicationService()`, because the listeners of one event service do not get the events fired into another. This is for the code that you write in the app. In the code that modules generate, only the DI container calls these functions, and the contract harness checks that. A feature resolves its services in its composition file instead, which is why a feature with services requires the DI role. ## Events The events role lets parts of the app that do not know each other exchange events. An event is a class that extends `AppEvent`: ```dart final class ItemAdded extends AppEvent { const ItemAdded(this.id); final int id; } ``` `fire` sends an event, and `on()` is the stream of the events of a type: ```dart events.fire(const ItemAdded(5)); final subscription = events.on().listen((event) { // An item was added somewhere in the app. }); ``` An event goes once to every listener of its type that is listening when the event is fired, and the events arrive in the order they were fired. Whether it also goes to the listeners of a type that it extends or implements depends on the module, and it never goes to a listener of any other type. The stream of `on()` has only the events fired after it is listened to, so an event fired between the call of `on()` and `listen` is not in it. A cancelled subscription gets no more events. With `event_bus`, an event also goes to the listeners of the types it extends or implements, so `on()` gets every event, and listeners get an event after the code that fires it has completed. ## Analytics `AnalyticsService` logs events and describes the user: `logEvent`, `logSignIn`, `logSignUp`, `setUserId`, `setUserProperty` and `setAnalyticsCollectionEnabled`. In an app with a router, screen views need no code: `firebase_analytics` logs one for each screen the user sees. See [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md#screen-views). ## Crash reporting `bootstrap()` calls `installCrashReporting()` of the role once the reporting services are ready. It reports as fatal the errors of the main isolate that the app does not handle, through two handlers. `FlutterError.onError` gets the errors that Flutter catches, such as in a build or a layout, and still presents them as Flutter does by default. `PlatformDispatcher.instance.onError` gets every other uncaught error, such as one in a `Future` or a `Timer`, and in debug mode it also leaves the error unhandled, so the engine still prints it. Report other errors with `recordError`, add context to the next report with `log`, and set the user with `setUserId`. The reporter does not print what it reports, so an error that the app reports is not printed either. The handlers cover the main isolate. `compute()` and `Isolate.run()` throw the error of their isolate to the code that awaits them, so it reaches the handlers unless that code catches it. For an isolate that the app spawns itself, report its errors in its error listener, such as the `onError` port of `Isolate.spawn`. ## State The state management role holds the state of screens. [`bloc`](https://doc.saymyframe.com/modules/bloc.md) adds `flutter_bloc`, and [`riverpod`](https://doc.saymyframe.com/modules/riverpod.md) adds `flutter_riverpod` and wraps the app in a `ProviderScope`. A feature that keeps state brings its Cubits or providers in a variant for each state manager, so the same feature works with either. With either state manager, the widgets of a screen talk only to their state, a Cubit through `context.read` or a provider through `ref`, and the state talks to the services. Widgets never reach into the DI container. The screens of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) are written this way with both. A screen provides or watches its state and passes plain values and callbacks to a view, a widget that imports no package of a state manager. State that several screens read, such as who uses the app, is provided around the root of the app with `bloc`, and is a provider of its own with `riverpod`. # Preferences and settings Source: https://doc.saymyframe.com/guides/preferences With a module that provides the preferences role, such as [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md), a generated app remembers its settings between its launches. An app with [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md), [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md), [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) or [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) always has such a module, since it remembers the theme mode, the language, whether the onboarding is finished, and whether the app asked for the permission to show notifications. With [`settings`](https://doc.saymyframe.com/modules/settings.md), the app has a screen that shows its settings. This page shows how the code you write uses both, and [How settings work](https://doc.saymyframe.com/concepts/settings.md) explains the roles behind them. :::warning The preferences are for settings, such as the theme mode or whether the user has dismissed a hint, and not for secrets. Nothing in them is encrypted, and a backup of the device carries them. Never store a token, a password, an API key or an encryption key there. A secret belongs in the secure storage of the platform, the Keychain on iOS and the Keystore on Android. ::: ## The preferences of the app The preferences role generates `lib/core/preferences/app_preferences.dart`, whichever module provides it: | | | | --- | --- | | `AppPreferences` | The interface of the preferences: `getString`, `getBool`, `getInt`, `getDouble` and `getStringList`, a `set…` for each of them, and `remove`. | | `initPreferences()` | Opens the preferences and gives them to the restorers, described below. `bootstrap()` awaits it in its platform phase, before the services of the app and before the first frame. | | `createAppPreferences()` | Returns the preferences that `initPreferences()` opened. | A read is synchronous, from memory, and never throws. It returns `null` when its key has no value of the type it asks for, so `getString` of a key with a `bool` is `null`. Whether a number saved as an `int` is read as a `double`, or the other way round, depends on the module. With `shared_preferences` it is not, so read a setting as the type you saved it as. Once the future of a write completes, reads return what it saved, in this run of the app and after its next launch. A key has one value: a write replaces what the key had, a value of another type too. `remove` puts a setting back to its default, and the reads of its key return `null` again. If the preferences cannot be opened, `initPreferences()` fails, and `bootstrap()` with it. ## Remember a setting Code that remembers a setting has three parts: the state that the widgets listen to, a function that changes the state and saves it, and a restorer, which reads what is saved when the app starts. This one remembers that the user has dismissed a hint of the home screen: ```dart title="lib/features/home/hint.dart" import 'package:flutter/foundation.dart'; import '../../core/preferences/app_preferences.dart'; /// The key of the setting in the preferences of the app. const _key = 'home.hint_dismissed'; /// Whether the user dismissed the hint of the home screen. final ValueNotifier hintDismissed = ValueNotifier(false); AppPreferences? _preferences; /// Dismisses the hint, or shows it again, and saves the choice. Future chooseHint({required bool dismissed}) async { hintDismissed.value = dismissed; await _preferences?.setBool(_key, dismissed); } /// Takes the choice that is saved, or keeps the current one, and keeps /// [preferences] for the choice to come. void restoreHint(AppPreferences preferences) { _preferences = preferences; hintDismissed.value = preferences.getBool(_key) ?? hintDismissed.value; } ``` A restorer is a function that takes the `AppPreferences`. Add it to the list of restorers in the file of the role, with the import of its file: ```dart title="lib/core/preferences/app_preferences.dart" final List _restorers = [ restoreHint, ]; ``` `initPreferences()` calls each restorer with the preferences once they are open, so the setting has its saved value before the first frame. The widgets listen to `hintDismissed` and call `chooseHint()`, and never touch the preferences themselves. The roles and the modules of the app keep their settings the same way: `smf create` puts their restorers into the same list, such as `restoreAppThemeMode` of the theme and `restoreOnboarding` of the onboarding. A restorer is synchronous, keeps the current value when nothing is saved under its key, as `?? hintDismissed.value` does above, and may run more than once. [How settings work](https://doc.saymyframe.com/concepts/settings.md#preferences) has its rules in full. In the code of the app, only `bootstrap()` calls `initPreferences()`, and nothing but the DI container calls `createAppPreferences()`. Code gets the preferences as the argument of its restorer, and the guide for coding agents of the app tells agents to do the same. A test is another matter: it calls `createAppPreferences()` to read and write a key, and `initPreferences()` to open the preferences again, as [the test below](#in-tests) does. ## Keys Name a key `.`, such as `home.hint_dismissed`, where the owner is the feature or the concern whose code keeps the setting. The modules name theirs after their ids, so the keys of different owners do not collide. Nothing checks the form: two owners that save under one key overwrite each other's setting. ## With a DI container With a module of dependency injection, such as [`get_it`](https://doc.saymyframe.com/modules/get-it.md), the preferences role also registers the preferences in the container as a lazy singleton. A service takes them as a dependency of its factory, and the composition file of a feature takes them with `resolve()` and hands them to the state of the feature, such as a Cubit. See [Services and state](https://doc.saymyframe.com/guides/services.md#with-a-di-container). ## The settings screen With `settings`, the app has `SettingsScreen` at `/settings`. Below its title, it shows the settings that the roles and the modules of the app have, such as the theme mode and the language, in one group on a card. With a layout, such as [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), the screen is a destination of the main navigation. Without one, open it from your own code: ```dart context.nav.settings.settings().push() ``` An entry for a setting of your own is a widget that reads and changes the setting through its state, as the other entries do: ```dart title="lib/features/home/hint_setting.dart" import 'package:flutter/material.dart'; import 'hint.dart'; /// The row of the settings screen that hides the hint of the home screen, /// or shows it again. class HintSetting extends StatelessWidget { /// Creates the row. const HintSetting({super.key}); @override Widget build(BuildContext context) => ValueListenableBuilder( valueListenable: hintDismissed, builder: (context, dismissed, _) => SwitchListTile( secondary: const Icon(Icons.lightbulb_outline), title: const Text('Hide the hint of the home screen'), value: dismissed, onChanged: (value) => chooseHint(dismissed: value), ), ); } ``` The screen is in `lib/features/settings/settings_screen.dart`. Import the file of the entry there with a prefix that no other import of the screen has, as the screen imports the entries of the modules, since two entries may have the same class name. The screen creates its entries as constants, so the entry has a `const` constructor. ### In an app without settings While no module of the app has a setting, the screen shows a note for you in place of the group; see [`settings`](https://doc.saymyframe.com/modules/settings.md#an-app-without-settings). The first entry takes the place of the note. Replace the `SliverFillRemaining` with the note by the entry on a `Card`: ```dart title="lib/features/settings/settings_screen.dart" import '../home/hint_setting.dart' as hint; // ... child: CustomScrollView( slivers: [ SliverPadding( padding: const EdgeInsets.fromLTRB(16, 20, 16, 0), sliver: SliverToBoxAdapter(child: title), ), const SliverPadding( padding: EdgeInsets.fromLTRB(16, 20, 16, 32), sliver: SliverToBoxAdapter( child: Card( clipBehavior: Clip.antiAlias, child: hint.HintSetting(), ), ), ), ], ), ``` Then delete the class `_NoSettings` and the constant `_file` from the file, which nothing uses after that. ### In an app with settings In an app with a module that brings a setting, such as [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md), the screen has the group. Add the entry to its children, here after the entry of the theme mode: ```dart title="lib/features/settings/settings_screen.dart" import '../home/hint_setting.dart' as hint; // ... const _Group( children: [entry0.ThemeModeSetting(), hint.HintSetting()], ), ``` The group draws a line between its entries. ## In tests A test shows that a setting is saved by reading its key after a choice. It shows that a setting is remembered by writing the key through `AppPreferences`, running `initPreferences()` again, as the next launch does, and reading the state: ```dart title="test/features/home/hint_test.dart" import 'package:flutter_test/flutter_test.dart'; import 'package:my_app/bootstrap.dart'; import 'package:my_app/core/preferences/app_preferences.dart'; import 'package:my_app/features/home/hint.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; void main() { test('the choice is saved, and the next start reads it', () async { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); await bootstrap(); expect(hintDismissed.value, isFalse); // Saved: the key has the choice once the write completes. await chooseHint(dismissed: true); expect(createAppPreferences().getBool('home.hint_dismissed'), isTrue); // Remembered: write the key, open the preferences again as the next // launch does, and read the state. await createAppPreferences().setBool('home.hint_dismissed', false); await initPreferences(); expect(hintDismissed.value, isFalse); }); } ``` Running `initPreferences()` again right after a choice proves nothing, since memory has the value already. Nor does it stand for the next launch once a key was removed: the restorer finds nothing saved and keeps the value that the state has, where a new launch starts with the default. The first statement of the test puts the preferences of `shared_preferences` into memory. Without it, opening the preferences throws. Its two names come from the package `shared_preferences_platform_interface`, which the test needs as a dev dependency; see [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md#in-tests). A DI container that created the preferences before keeps the object of the earlier open. So a test of code that takes them from the container also runs `resetDependencies()` and `registerDependencies()` once `initPreferences()` ran again. # Theme Source: https://doc.saymyframe.com/guides/theme An app with a module that provides the theme role, such as [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md), has a light and a dark theme, and a theme mode that the user selects: light, dark, or the one of the device. The app remembers the mode between its launches, so an app with the role always has [preferences](https://doc.saymyframe.com/guides/preferences.md) too. | File | From | What to change there | | --- | --- | --- | | `lib/core/theme/app_theme.dart` | the module that provides the role | The look: the two themes of the app. | | `lib/core/theme/theme_mode.dart` | the theme role | Nothing. Code selects and reads the mode through it. | | `lib/core/theme/theme_mode_setting.dart` | the theme role, in an app with a settings screen | The entry of the settings screen that selects the mode. | ## The look `lib/core/theme/app_theme.dart` has two functions: ```dart ThemeData createLightTheme(BuildContext context) ThemeData createDarkTheme(BuildContext context) ``` Change the look of the app there. With `material_theme`, the file has the colors of both themes, their text styles, the look of their components and the family of their font, whose files are in `assets/fonts/` of the app; see [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md#change-the-look). The root of the app calls both functions each time it builds, so a change of that file shows on a hot reload: ```dart title="lib/app.dart" @override Widget build(BuildContext context) => MaterialApp.router( title: 'My App', theme: createLightTheme(context), darkTheme: createDarkTheme(context), themeMode: AppThemeModeScope.of(context), routerConfig: appRouter.config, builder: (context, child) => StatusBarIcons(child: child!), ); ``` Keep both functions and their parameter, and leave the `theme`, the `darkTheme` and the `themeMode` of the root `MaterialApp` as they are. The context that the functions get is the one of the root widget, above the `MaterialApp`, so it has neither the theme nor the localizations of the app. In the screens, take colors and text styles from `Theme.of(context)` and not from constants, so that every screen follows the mode. The screens of the built-in modules do, and so does the bar of [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md): the [onboarding](https://doc.saymyframe.com/modules/onboarding.md), the [start screen](https://doc.saymyframe.com/modules/home.md), the [settings screen](https://doc.saymyframe.com/modules/settings.md), the screens of the [sign-in](https://doc.saymyframe.com/modules/sign-in.md) and the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen) follow the mode and a look of your own. The fields, the buttons and the cards of the sign-in are those of the theme, so a change of the `inputDecorationTheme` of the app changes its fields. Two things keep their colors in both themes: the card of the start screen of `home`, and the buttons of the other ways to sign in on the screens of `sign_in`, which stay white with a black label and icon, as the brand guidelines of the identity providers allow. The icons of the status bar follow the mode too: `StatusBarIcons` of `lib/core/app/status_bar_icons.dart`, which the `builder` of the root puts around every screen, asks the system for dark ones on a light theme and for light ones on a dark theme. ## The mode `lib/core/theme/theme_mode.dart` is the same with every module that provides the look: | | | | --- | --- | | `appThemeMode` | The controller of the mode, the only one of the app. Its `value` is the `ThemeMode` of the app: `ThemeMode.system`, which follows the device, until the user selects another. `choose(mode)` makes `mode` the mode of the app at once and saves it. | | `AppThemeModeScope` | The widget around the root of the app. `AppThemeModeScope.of(context)` returns the mode, and the widget of that context rebuilds when the mode changes. | | `restoreAppThemeMode` | The [restorer](https://doc.saymyframe.com/guides/preferences.md#remember-a-setting) of the mode, which the app calls before its first frame. | `main()` puts the scope around the root widget, which is how the root follows the mode: ```dart title="lib/main.dart" runApp(AppThemeModeScope(notifier: appThemeMode, child: const App())); ``` The mode is saved in the preferences under the key `theme.mode`, as the name of the `ThemeMode`: `system`, `light` or `dark`. When the app starts, the restorer takes the mode that is saved. It keeps the current mode when nothing is saved, or when what is saved is not the name of a mode. Change the mode only with `choose`, and write nothing under that key yourself. The future of `choose` completes once the mode is saved. If the preferences fail to save it, the future completes with their error. The app is in the selected mode by then and stays in it while it runs, but its next launch has the mode that was saved before. The same choice again saves it. [How settings work](https://doc.saymyframe.com/concepts/settings.md#the-theme-mode-a-setting-of-a-role) follows the mode through the roles of the app. ## The entry on the settings screen In an app with a [settings screen](https://doc.saymyframe.com/guides/preferences.md#the-settings-screen), `lib/core/theme/theme_mode_setting.dart` has `ThemeModeSetting`, the entry in which the user selects the mode. Below its title, Theme, it has three segments, System, Light and Dark, each with its icon above its name. ![The entry Theme on the settings screen, with the segment Light selected and the app in the light theme, above the rows Language and Notifications.](https://doc.saymyframe.com/demo/0.8/app_5_settings.png) ![The same entry after a tap on Dark: the segment Dark is selected, and the app is in the dark theme.](https://doc.saymyframe.com/demo/0.8/app_6_settings_dark.png) The segment of the mode of the app is the selected one, and a tap on another selects its mode at once: ```dart title="lib/core/theme/theme_mode_setting.dart" selected: {AppThemeModeScope.of(context)}, onSelectionChanged: (modes) => appThemeMode.choose(modes.single), ``` The entry keeps no mode of its own, so it also shows a mode that other code chose. The segments are a `SegmentedButton`, which takes its look from the `segmentedButtonTheme` of the theme of the app. In an app with [languages](https://doc.saymyframe.com/guides/languages.md), the texts of the entry are texts of the app, in English and in Ukrainian. Without them, the entry is in English. With a large text size, the names of the modes grow to at most one and a half times their size, and a name that is wider than its segment gets smaller and stays on one line. The entry does not wait until a choice is saved. If the preferences fail to save it, the error reaches the handlers of the uncaught errors of the app. The mode and its entry belong to the role, so they are the same with every module that provides the look. Such a module adds no entry for the mode. One with a setting of its own for its look, such as a color that the user picks, adds an entry of its own for it. ## In tests A test selects a mode with `appThemeMode.choose(mode)` and reads the selected one from `appThemeMode.value`. It shows that a mode is saved by reading `theme.mode` from the preferences after a choice, and that it is remembered by writing the key, running `initPreferences()` again and reading the mode; see [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md#in-tests). The app has one controller, and two things of it outlive a test, into the next test of the same file: its mode, and the preferences of the last start, through which `choose` saves from then on. So a test that selects a mode chooses `ThemeMode.system` again when it ends. That choice saves `system`, so a test that needs nothing saved removes `theme.mode` from the preferences. # Languages Source: https://doc.saymyframe.com/guides/languages An app with a module that provides the localization role shows its texts in the language of the device, or in the one that the user chose. Among the built-in modules, that is [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md). Without such a module, the app shows the texts of its modules in English. The app remembers the language that the user chose, so an app with the role always has [preferences](https://doc.saymyframe.com/guides/preferences.md) too. | File | From | What it holds | | --- | --- | --- | | `lib/core/l10n/app_locale.dart` | the localization role | The languages of the app, and the language that the user chose. | | `lib/core/l10n/language_setting.dart` | the localization role, in an app with a settings screen | The entry of the settings screen in which the user chooses the language. | | `lib/core/l10n/l10n.dart` | the module that provides the role | `context.l10n`, the texts of the app in the language of a `BuildContext`. | | `lib/l10n/app_.arb` | `gen_l10n` | The texts themselves, one file for each language. | [Texts and languages](https://doc.saymyframe.com/concepts/localization.md) explains how the texts of the modules get there. ## The languages of the app A module gives each of its texts in English, and can give translations into other languages. `smf create` takes every language that a text of the app is in, with English first, and writes them into `lib/core/l10n/app_locale.dart`. The built-in modules have their texts in English and in Ukrainian, such as the texts of the start screen of `home`, the title of the settings screen and the pages of the onboarding. [`flutter_core`](https://doc.saymyframe.com/modules/flutter-core.md#its-texts-and-the-languages-of-the-app), which every app has, has two such texts for its fallback start screen, which an app that no route starts has. So an app with `gen_l10n` and the built-in modules has two languages, also an app without a feature: ```dart title="lib/core/l10n/app_locale.dart" const appLocales = [Locale('en'), Locale('uk')]; ``` With `--locales en`, the app has `[Locale('en')]`. The app shows its texts in the language that the device prefers among them, and in the first of the list when the device asks for none of them. A text without a translation into a language of the app reads in English there, and `smf create` warns about it, with the module and the name of the text. An app can be only in a language in which Flutter has the texts of its own widgets, such as the tooltip of the back button. `smf create` leaves any other language of a text out of the app, and warns of it unless `--locales` chose the languages. On iOS, the languages of the app are also in `CFBundleLocalizations` of `ios/Runner/Info.plist`, since iOS shows an app in the languages that its bundle names. ### Choosing the languages `--locales` narrows the languages of the app and orders them, as in `--locales uk,en`. The first language is the one the app uses when the device asks for none of them. The run stops with a usage error when `--locales`: - leaves out `en`, since the app shows a text in English wherever it has no translation; - names a language that no text of the app is in; - names a language in which Flutter has no texts for its own widgets; - names a language twice; - has an empty code, as in `en,,uk`. A language of your own goes into the app once it is generated; see [Add a language](#add-a-language). In an app without a module that provides the localization, `--locales` has no effect, and `smf create` says so in a warning. ## Reading a text `lib/core/l10n/l10n.dart` gives every `BuildContext` the texts of the app: ```dart import 'package:my_app/core/l10n/l10n.dart'; Text(context.l10n.cartTitle) ``` `context.l10n` has a `String` getter for each text of the app, in the language of the context. The context is one below the root `MaterialApp`, such as the context of the `build` of a screen. A getter is not a constant, so a widget that reads one cannot be `const`. The getter of a text that a module or a role brings starts with its id, in lowerCamelCase, followed by the name of the text: the text `title` of the theme role is `themeTitle`. That keeps the texts of different owners apart, and `smf create` reports two texts that would still need one getter. The texts of Flutter's own widgets follow the language too: the role gives the root `MaterialApp` the delegates of `flutter_localizations` and adds the package to the app. ## The language that the user chose `lib/core/l10n/app_locale.dart` also keeps the choice of the user: | | | | --- | --- | | `appLocales` | The languages of the app, as `Locale`s. | | `appLocale` | The controller of the choice, the only one of the app. Its `value` is one of `appLocales`, or `null` while the app follows the languages of the device. `choose(locale)` puts the app into that language at once and saves the choice, and `choose(null)` follows the device again. | | `AppLocaleScope` | The widget around the root of the app. `AppLocaleScope.of(context)` returns the choice, and the widget of that context rebuilds when it changes. | | `restoreAppLocale` | The [restorer](https://doc.saymyframe.com/guides/preferences.md#remember-a-setting) of the choice, which the app calls before its first frame. | ```dart await appLocale.choose(const Locale('uk')); ``` The root of the app rebuilds in the new language, with the texts of every screen. `main()` puts the scope around the root widget, and the root `MaterialApp` takes its `locale` from it: ```dart title="lib/main.dart" runApp(AppLocaleScope(notifier: appLocale, child: const App())); ``` `choose` takes one of `appLocales`, or a locale of the language of one of them: `Locale('uk', 'UA')` chooses `Locale('uk')`. For a language that the app is not in, its future completes with an `ArgumentError`, and nothing changes. The app tells its languages apart by their codes alone, so `appLocales` has one locale for each language. Of two locales of one language, such as `Locale('pt', 'BR')` and `Locale('pt', 'PT')`, `choose` takes the first, whichever of them it is given. The choice is saved in the preferences under the key `localization.locale`, as the code of the language, and removed when the app follows the device again. When the app starts, the restorer takes the language that is saved. A code that is none of the languages of the app counts as nothing saved. Change the language only with `choose`, and write nothing under that key yourself. The future of `choose` completes once the choice is saved. If the preferences fail to save it, the future completes with their error. The app is in the new language by then and stays in it while it runs, but its next launch starts with what was saved before. The same choice again saves it. ### The entry on the settings screen In an app with a [settings screen](https://doc.saymyframe.com/guides/preferences.md#the-settings-screen), `lib/core/l10n/language_setting.dart` has `LanguageSetting`, the entry Language. It is a row with the choice of the user as its value: the language that the user chose, or System while the app follows the device. A tap on the row opens a sheet at the bottom of the screen, over the main navigation too. The sheet has System and each language of the app, with a check mark on the chosen one. A tap on an option closes the sheet and puts the app into that language at once. ![The sheet of the languages over the settings screen, in the dark theme: the title Language, and the options System, English with a check mark, and Π£ΠΊΡ€Π°Ρ—Π½ΡΡŒΠΊΠ°.](https://doc.saymyframe.com/demo/0.8/app_7_language.png) ![The settings screen after a tap on Π£ΠΊΡ€Π°Ρ—Π½ΡΡŒΠΊΠ°: the app is in Ukrainian, the row of the language Мова has the value Π£ΠΊΡ€Π°Ρ—Π½ΡΡŒΠΊΠ°, and the entries of the theme and the notifications are in Ukrainian too.](https://doc.saymyframe.com/demo/0.8/app_8_settings_dark_uk.png) With a large text size, the choice goes below the title of the row, where it has the whole width, and the sheet scrolls when its options do not fit. The entry shows each language by its name in that language, from `_names` in that file: ```dart title="lib/core/l10n/language_setting.dart" const _names = {'en': 'English', 'uk': 'Π£ΠΊΡ€Π°Ρ—Π½ΡΡŒΠΊΠ°'}; ``` SMF has the names of English and Ukrainian. The entry shows any other language by its code, until you add its name to `_names`. A name there is a string literal and not a text of the app, since the name of a language in that language is the same whatever language the app is in. The entry does not wait until a choice is saved. If the preferences fail to save it, the error reaches the handlers of the uncaught errors of the app. ## Add a text Where a text goes depends on the module that provides the localization, since that module keeps the texts. With `gen_l10n`, a text goes into the ARB files of `lib/l10n`, and `flutter gen-l10n` generates its getter; see [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md#add-a-text). Whichever module it is, read a text that a user sees through `context.l10n` and do not write it as a literal in a widget, so that it follows the language of the app. ## Add a language A new language goes into these places. For German: 1. The texts of the app. With `gen_l10n`, add `lib/l10n/app_de.arb` with `"@@locale": "de"` and the translations, and run `flutter gen-l10n`. 2. `appLocales` in `lib/core/l10n/app_locale.dart`: add `Locale('de')`, one locale for the language. 3. `CFBundleLocalizations` in `ios/Runner/Info.plist`: add `de`. 4. In an app with a settings screen, `_names` in `lib/core/l10n/language_setting.dart`: add `'de': 'Deutsch'`. Without it, the entry shows `de`. Add only a language in which Flutter has the texts of its own widgets, and add its texts first: every delegate of the root `MaterialApp` has to support each language of `appLocales`. The README of the app has the same steps, in its sections "Texts" and "Languages". ## In tests A test puts the app into a language with `appLocale.choose(locale)` and reads the choice from `appLocale.value`. It shows that the choice is saved by reading `localization.locale` from the preferences after a choice, and that it is remembered by writing the key, running `initPreferences()` again and reading the choice; see [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md#in-tests). The app has one controller, and its choice outlives a test, into the next test of the same file. So a test that chooses a language ends with `appLocale.choose(null)`, which also removes the key. # Sign-in Source: https://doc.saymyframe.com/guides/sign-in Sign-in in a generated app has two parts, each from a module of its own: | Part | Module | What it brings | | --- | --- | --- | | The screens | [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) | The sign-in, the sign-up and the password reset for an email address and a password, with a button for each other way to sign in of the app, the screen of the account with its entry on the settings screen, and the two guards of the routes that show them. | | The session and the accounts | A module that provides the auth role, among the built-in modules [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | `appSession`, which knows who uses the app and through which code signs in, up and out, and the service that keeps the accounts, here Firebase Authentication. | | Other ways to sign in | [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md), [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) | Sign-in with a Google account on Android and iOS, and with an Apple Account on iOS; see [ways to sign in](#ways-to-sign-in). | The screens need the session, so `sign_in` brings `firebase_auth` with it: ```bash smf create my_app -m home,sign_in,bloc,bottom_tabs ``` An app can also have the session without the screens, with `-m firebase_auth` alone. Its screens that sign a user in are then yours to write; see [an app without the screens](#an-app-without-the-screens). ![The sign-in in the light theme, in English: the cell Ma 5 among the cells of a table, the title Sign in with the line Choose how to sign in to your account. below it, the white buttons Continue with Google and Continue with Apple, then or, the fields Email and Password, Forgot password? below the password field, the button Sign in, and Create account in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png) ![The sign-in in the dark theme, in Ukrainian: the title Π’Ρ…Ρ–Π΄, the white buttons ΠŸΡ€ΠΎΠ΄ΠΎΠ²ΠΆΠΈΡ‚ΠΈ Π· Google and ΠŸΡ€ΠΎΠ΄ΠΎΠ²ΠΆΠΈΡ‚ΠΈ Π· Apple, the fields Π•Π»Π΅ΠΊΡ‚Ρ€ΠΎΠ½Π½Π° ΠΏΠΎΡˆΡ‚Π° and ΠŸΠ°Ρ€ΠΎΠ»ΡŒ, the light button Π£Π²Ρ–ΠΉΡ‚ΠΈ, and Π‘Ρ‚Π²ΠΎΡ€ΠΈΡ‚ΠΈ Π°ΠΊΠ°ΡƒΠ½Ρ‚ in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in_dark_uk.png) These are the screens of an app with [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) too, whose buttons are above the form; see [ways to sign in](#ways-to-sign-in). | File | From | What it holds | | --- | --- | --- | | `lib/features/sign_in/` | `sign_in` | The screens, their state and the functions of the guards. | | `lib/core/auth/app_session.dart` | the auth role | `appSession`, the session of the app, and `authMode`, who may use the app without an account. | | `lib/core/auth/guest_data.dart` | the auth role | `takeGuestData()`, which you edit: what moves to an account from the anonymous user who signs in to it. | | `lib/core/auth/auth_service.dart` | the auth role | `AuthService`, which the module that provides the role implements. The code of the app does not use it. | | `lib/core/auth/sign_in_methods.dart` | the auth role | `appSignInMethods`, the ways to sign in with Google, Apple or another identity provider that the modules of the app add. | | `lib/core/auth/firebase_auth_service.dart` | `firebase_auth` | The service on Firebase Authentication. | | `tool/enable_firebase_sign_in.dart` | `firebase_auth` | The script that [enables the sign-in methods](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication) in the Firebase project. | ## The mode The mode of the app says who may use it without an account. A run in a terminal asks for it, and `--auth-mode` answers in advance: ```text ? Who may use the app without an account? (↑↓ to move, enter to choose) ❯ Nobody: the user signs in first Everyone: an account only where a screen needs one Everyone, as an anonymous user with an id from the start ``` | `--auth-mode` | Who may use the app without an account | With `sign_in`, what the user sees | | --- | --- | --- | | `required`, the default | Nobody. | The sign-in in place of every screen, until the user is signed in to an account. With an [onboarding](https://doc.saymyframe.com/modules/onboarding.md), the onboarding comes first. | | `guest` | Everyone. The app has no user until someone signs in. | The app. The sign-in opens over a page when the user asks for a screen that needs an account, such as the screen of the account. | | `anonymous` | Everyone, as an anonymous user that the app signs in itself when it starts. Code then has the id of a user, `appSession.value.uid`, before anyone has an account. | The same as in `guest`. Signing up gives the anonymous user the account, with the same id. | A run without a terminal takes `required` when the option is not given, and does not stop for it. The auth role writes the mode into the app as a constant: ```dart title="lib/core/auth/app_session.dart" const AuthMode authMode = AuthMode.required; ``` To change the mode later, change that value, and keep the declaration as it is, on a line that it starts: the script that enables the sign-in methods reads the mode from that line. The module that provides sign-in has to allow what the mode needs. With `firebase_auth`, the mode `anonymous` needs anonymous users enabled in the Firebase project, which the script does when you run it again. ### An anonymous user from the start In the mode `anonymous`, an app without a user signs in anonymously when it starts, and waits for that for at most 3 seconds. When the sign-in fails or takes longer, the app starts without a user. So code handles a `SignedOutSession` in this mode too. The app tries again each time the user comes back to it, and after each call that leaves nobody signed in, such as a sign-out or the deletion of an account. A sign-in that took longer than the wait still becomes the session when it comes. In debug mode the app prints the error of an anonymous sign-in that failed. ## What keeps a user from a screen The mode keeps nobody from a screen on its own. A [guard of the routes](https://doc.saymyframe.com/guides/navigation.md#guards) does, and the session has the two values that such guards read: | | A guard that reads it | | --- | --- | | `appSession.allowsApp` | Stands before the whole app. It is `true` for the user of an account, and in the modes `guest` and `anonymous` for everyone. | | `appSession.hasAccount` | Stands only before the routes that it lists, the screens that need an account. It is `true` only for the user of an account, which an anonymous user is not. | Both are a `ValueListenable` that is computed from the session when it is read, and their listeners are those of the session. So a guard never finds one of them changed and the other not. `sign_in` declares both guards, `sign_in.gate` and `sign_in.hasAccount`, whose target is the sign-in. This is `routeGuards` of an app with the module and an onboarding: ```dart title="lib/core/router/app_router.dart" final List routeGuards = [ RouteGuard( 'onboarding.firstRun', allows: guard0.onboardingCompleted(), redirectTo: const OnboardingOnboardingLocation(), flow: const {'onboarding.onboarding'}, ), RouteGuard( 'sign_in.gate', allows: guard1.signInAllowsApp(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, ), RouteGuard( 'sign_in.hasAccount', allows: guard1.signInHasAccount(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, routes: const {'sign_in.account'}, ), ]; ``` - The screens of the sign-in only change the session. They neither close themselves nor navigate after a sign-in or a sign-out: the router does both when the guards change. See [after a guard changed](https://doc.saymyframe.com/guides/navigation.md#after-a-guard-changed). - After a sign-out, the next user comes to the screen that the app starts on, and not to the screen that the last one was on. - Once the user is signed in to an account, a navigation to a route of the sign-in, such as a link, shows the screen that the app starts on. ### A screen of yours that needs an account To keep users without an account from a screen of yours, add the full name of its route to the `routes` of `sign_in.hasAccount`, and the names of the routes below it too. In this sketch they are the two routes of a feature `orders` of your own: ```dart title="lib/core/router/app_router.dart" routes: const {'sign_in.account', 'orders.orders', 'orders.order'}, ``` A request for such a route opens the sign-in over the page that the user is on, and the route shows once the user is signed in. Such a route is outside the main navigation, and the app does not start on it. ### A screen of yours that offers to sign in In the modes `guest` and `anonymous`, a screen may offer to sign in. Open the sign-in with `push()`, so that back leads back: ```dart context.nav.signIn.signIn().push() ``` In the mode `required`, no code navigates to the sign-in: the gate shows it. ## The account The settings screen has the entry Account, which shows the email address of the account, or Not signed in. A tap opens the screen of the account, where the user signs out or deletes the account after a confirmation in a sheet. For a user without an account, in the modes `guest` and `anonymous`, the sign-in opens over the settings screen first. ![The settings screen in the light theme, in English: one card with the row Account, which shows ada.lovelace@example.com and an arrow, the row Subscription with Not active, then the row Language, the entry Theme, the row Notifications and the row Restore purchases. Below is the tab bar with Settings selected.](https://doc.saymyframe.com/demo/0.8/app_settings_account.png) ![The screen of the account: a back button, the title Account, the line You are signed in to this account:, a card with ada.lovelace@example.com, the button Sign out, and Delete account in red below it.](https://doc.saymyframe.com/demo/0.8/app_account.png) ![The screen of the account in the dark theme, in Ukrainian: the title Акаунт, the address of the account, the light button Π’ΠΈΠΉΡ‚ΠΈ, and Π’ΠΈΠ΄Π°Π»ΠΈΡ‚ΠΈ Π°ΠΊΠ°ΡƒΠ½Ρ‚ in red.](https://doc.saymyframe.com/demo/0.8/app_account_dark_uk.png) The entry is within reach where the settings screen is. With a main navigation, such as that of [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), the settings screen is one of its destinations. In an app without one, a screen of yours opens the settings screen, or the account directly; see [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#where-the-entry-is-within-reach). ## Ways to sign in Besides an email address and a password, a user can sign in with an account at an identity provider, such as Google or Apple. Each such way to sign in comes from a module of its own, which knows no provider of sign-in: ```bash smf create my_app -m home,sign_in,bloc,bottom_tabs,google_sign_in,apple_sign_in ``` | Module | Way to sign in | Platforms | | --- | --- | --- | | [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) | Continue with Google | Android and iOS | | [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) | Continue with Apple | iOS | The module gives the auth role its way to sign in: the label and the icon of its button, the platforms that it works on, the function that asks the identity provider for a credential, and the issuer of the tokens of the identity provider. The role lists the ways to sign in of the app in `appSignInMethods` of `lib/core/auth/sign_in_methods.dart`, in the order of the modules: ```dart title="lib/core/auth/sign_in_methods.dart" const List appSignInMethods = [ SignInMethod( label: _googleSignInLabel, icon: method0.GoogleSignInIcon(), platforms: {TargetPlatform.android, TargetPlatform.iOS}, credential: method0.googleCredential, issuer: 'https://accounts.google.com', ), SignInMethod( label: _appleSignInLabel, icon: method1.AppleSignInIcon(), platforms: {TargetPlatform.iOS}, credential: method1.appleCredential, issuer: 'https://appleid.apple.com', revokesOnDeletion: true, ), ]; ``` The sign-in and the sign-up of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#other-ways-to-sign-in) show a button for each way to sign in whose `isAvailable` is true on the platform of the app, above the form. In an app without such a module the list is empty, and the screens show the form alone. ### What a tap does The state of the screen calls the `credential` function of the way to sign in, which shows the sheet of its identity provider and returns a credential, and gives the credential to `appSession.signInWith`: ```dart final credential = await method.credential(); if (credential == null) return; // The user closed the sheet. await appSession.signInWith(credential); ``` - A function that returns `null` means that the user closed the sheet. That is no failure, and the screen goes back to how it was. - A user of an account, or someone signed out, signs in with the credential at once. - An anonymous user gets the identity and keeps the id. When the identity has an account already, the session signs in to that account with the same credential, and [the data of the guest](#the-data-of-a-guest) moves to it, as with a password. That sign-in may also fail with `accountExistsWithOtherMethod`, because the address of the identity has an account that signs in in another way: the provider of sign-in decides which. - Call the function from the state of a screen and never within a call of `appSession`, which runs one call after another and would wait for it. `AccountSession.issuers` lists the identity providers of the account, each the `issuer` of a `SignInMethod`. ### Deleting such an account The App Store asks an app with Sign in with Apple to revoke the tokens that Apple gave it when the user deletes the account. A way to sign in that needs this has `revokesOnDeletion`. For an account with such a way, on a platform where it works, `appSession.deleteAccount()` calls its `credential` function itself, and the sheet of the identity provider shows again. The provider of sign-in signs the user in again with the new credential, revokes the tokens and deletes the account. When the user closes the sheet, the call completes and deletes nothing. A confirmation with another account fails with `invalidCredentials`, and a revocation that fails with `notConfigured`. Neither deletes anything. ### The provider of sign-in The provider of the auth role takes the credentials and sets up its backend for each way to sign in. [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#google-and-apple) takes those of Google and Apple. It reports a way to sign in of another identity provider when the app is generated, and `smf create` leaves the module of that way out, or stops with `--strict`. Its script enables Google in the Firebase project and sets up what Google needs, and its section of the README tells how to enable Apple; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication). Until a way to sign in is set up, signing in with it fails with `notConfigured`. What no command can set up is a step by hand, and the run ends with a link to the guides of those steps: Apple in the Firebase console with its key (guides of [the provider](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md) and of [the key](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md)), the SHA of the release keys for Google ([guide](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md)), and, for Sign in with Apple, signing the iOS app with a paid Apple Developer team ([guide](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md)). ### The App Store App Store Review Guideline 4.8 asks an app on iOS that offers a login service of a third party, such as Google sign-in, to offer an equivalent way to sign in too: one that asks for no more than the name and the email address of the user and lets the user keep the address private. The App Store takes Sign in with Apple as such a way. `smf create` warns of an app without one, and the section "Sign-in" of its README says that the review may reject it: ```text [WARN] [role:auth]: The app offers Continue with Google on iOS, a login service of a third party, but no way to sign in that the App Store takes as an equivalent: one that asks for no more than the name and the email address of the user and lets the user keep the address private (App Store Review Guideline 4.8). (Add such a way to sign in on iOS, such as Sign in with Apple.) ``` With `--strict`, the warning `auth.no_equivalent_sign_in` stops the run; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). Add `apple_sign_in` next to `google_sign_in`, and the warning goes away. ## The session `appSession` is the one session of the app. Its `value` is an `AppSession`, and it notifies its listeners when that changes: | `appSession.value` | Who uses the app | | --- | --- | | `SignedOutSession` | Nobody that the app knows. Its `uid` is `null`. | | `AnonymousSession` | An anonymous user: one without an account, whom the app signed in itself. It has the `uid` of that user. | | `AccountSession` | The user of an account. It has the `uid` and the `email` of the account, which is `null` if the account has none, and the `issuers` of its ways to sign in with an identity provider. | `bootstrap()` starts the session in its platform phase, with `await initAuth()`, so the app knows who is signed in before its first frame. A widget of an app with `sign_in` reads who uses the app from the state manager, and rebuilds when the user signs in or out: `context.watch().state` with `bloc`, and `ref.watch(sessionProvider)` with `riverpod`. In an app without the module, a widget follows `appSession` with a `ValueListenableBuilder`. Code signs in, up and out through `appSession`, as the state of the screens of `sign_in` does: | Call | What it does | | --- | --- | | `appSession.signIn(email:, password:)` | Signs in to the account. An anonymous user becomes the user of that account, and [the data of the guest](#the-data-of-a-guest) moves to it. | | `appSession.signUp(email:, password:)` | Creates an account and signs in to it. An anonymous user gets the account and keeps the id, so everything that the user had stays. | | `appSession.signInWith(credential)` | Signs in with the credential of a [way to sign in](#what-a-tap-does). An anonymous user gets the identity and keeps the id, or signs in to the account that has it. | | `appSession.sendPasswordReset(email)` | Sends the message with which the owner of the account sets a new password. It completes whether the address has an account or not. | | `appSession.signOut()` | Signs the user out. | | `appSession.deleteAccount()` | Deletes the user who is signed in. The app is then without a user, as after a sign-out. For an account with a way to sign in that revokes on deletion, it [asks the identity provider again](#deleting-such-an-account) first. | The calls run one after another, in the order they were made, so the user of the app is the result of the call that was made last. The code of the app creates no other `AppSessionController`, and it calls neither `initAuth()` nor `createAuthService()` nor `appSession.start()`. ### A token for your server A server of the app tells who the user is by a token. `appSession.userToken()` gives the token of the user, and `null` when nobody is signed in. An anonymous user has one too. The provider of sign-in keeps it and renews it, so read it for each request rather than keep it. When a server refuses a token, `appSession.userTokenAfter(rejected)` gives the one to use instead. With [the REST client](https://doc.saymyframe.com/guides/rest.md#the-token-of-the-user), you need neither call: `appRest` adds the token to each request to the address of your API. The server checks the token itself. With [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md), it is a Firebase ID token, which a server verifies with the [Firebase Admin SDK](https://firebase.google.com/docs/auth/admin/verify-id-tokens). The Admin SDK takes only a token of its own Firebase project, so a token of another project fails there. ## Failures A call of `appSession` fails only with an `AuthFailure`, whose `reason` the app shows a text for. The screens of `sign_in` have a text for every reason, in `authFailureText()` of `lib/features/sign_in/sign_in_widgets.dart`. Code of yours catches the failure the same way: ```dart import 'core/auth/app_session.dart'; Future signIn(String email, String password) async { try { await appSession.signIn(email: email, password: password); return null; } on AuthFailure catch (failure) { return switch (failure.reason) { AuthFailureReason.invalidCredentials => 'Wrong email or password.', AuthFailureReason.network => 'No connection. Try again.', _ => 'Sign-in is unavailable.', }; } } ``` `app_session.dart` exports `AuthFailure` and `AuthFailureReason`, so the code of the app imports that file alone. | Reason | What happened | | --- | --- | | `invalidCredentials` | The email address and the password match no account. A wrong password and an address without an account are this one reason, so that nobody learns from the app which addresses have an account. | | `emailInUse` | The email address has an account already. | | `credentialInUse` | The identity of a way to sign in belongs to another account already. | | `accountExistsWithOtherMethod` | The email address of the identity has an account that signs in in another way. | | `weakPassword` | The provider takes no password as weak as this one. | | `invalidEmail` | The text is no email address. | | `userDisabled` | The account is disabled. | | `tooManyAttempts` | Too many attempts: the provider takes no more for a while. | | `network` | The device did not reach the provider. | | `recentSignInRequired` | The call needs a user who signed in a short while ago, as the deletion of an account does. Tell the user to sign out and sign in again. It is also the reason of a call for a user whose session has ended on the server, and that user is signed out on the device by then. | | `notConfigured` | Sign-in is not set up at the provider, such as a way to sign in that is not enabled there, or one whose identity provider the provider does not take. This is a mistake in the setup of the app. | | `unknown` | Anything else. | A failure may have a `developerHint`: what went wrong in the words of the provider. It is for you and not for the user, so show it in debug mode only, as the screens of `sign_in` do below the text of the failure. For `notConfigured` it explains the mistake, and for `unknown` it has the error. ## The data of a guest When an anonymous user signs in to an account that exists already, the user of the app changes from the guest to that account. What the app keeps under the id of the guest, such as a cart on a server, would be left behind. `takeGuestData()` says what moves: ```dart title="lib/core/auth/guest_data.dart" Future takeGuestData(String guestUid) async => null; ``` As generated it moves nothing. Write there what the app keeps under the id of a user. This sketch moves a cart: ```dart title="lib/core/auth/guest_data.dart" Future takeGuestData(String guestUid) async { final cart = await carts.read(guestUid); if (cart.isEmpty) return null; return (accountUid) => carts.add(accountUid, cart); } ``` - `appSession.signIn`, and `appSession.signInWith` for an identity that has an account, call the function before the sign-in, while the guest is still signed in and may read that data. It calls the function that it got back once the user of the account is signed in. - Only read in `takeGuestData()`: the sign-in may still fail, and then the guest stays. An error thrown there fails the sign-in before it starts. - An error of the function that it returns is reported as an error of the app, and the user stays signed in. - Call no method of `appSession` in either function. The sign-in is one of its calls, which run one after another, so the two would wait for each other. - The function is not called when a guest signs up, since the guest then keeps the id and everything under it. It is not called in an app without anonymous users either. ## An app without the screens With a module that provides the auth role and without `sign_in`, the app has the session and no guard that reads it. Every screen is open in every mode, `required` too. That includes a screen that a module made for users with an account: `smf create` warns of each such route when it generates the app. The screens that sign a user in are then yours, and so are the guards. A guard of your own goes into `routeGuards` of `lib/core/router/app_router.dart`, which an app has when one of its modules declares a guard, as [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) does. An app whose modules declare no guard has neither that list nor the code that asks it. This sketch is a gate for a sign-in screen of your own at `/login`, the route `login.login`: ```dart title="lib/core/router/app_router.dart" RouteGuard( 'login.signedIn', allows: appSession.allowsApp, redirectTo: const LoginLoginLocation(), flow: const {'login.login'}, resumes: false, ), ``` It comes after the gates of a first launch, such as that of the onboarding. A guard for the screens that need an account reads `appSession.hasAccount` and names those routes in its `routes`. ## The README and the guide for coding agents The auth role writes the section "Sign-in" of the README of the app: the mode of the app, what each mode means, that the mode gates nothing on its own, how to change it, and where the data of a guest moves. It also lists the ways to sign in of the app, each with its platforms and what a deletion asks of it, or tells where such a way goes in an app without one, and it says when the app lacks the equivalent that the App Store asks for. `firebase_auth` tells under "Firebase Authentication" how the sign-in methods are enabled, and each module of a way to sign in adds a section of its own, such as "Google sign-in". The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app has the section "Authentication" for the session, and with `sign_in` the section "Sign-in" for the screens. ## In tests The app has one session, and who is signed in outlives a test, into the next test of the same file. So a test signs out first, or expects nothing of who is signed in. | A test that | Does this | | --- | --- | | needs an account before the app starts | It calls `appSession.signUp()` before `bootstrap()`, without awaiting it. A call made before the first start waits for it, and the app then starts with that account. The test makes the call outside the body of a test, as in a `setUpAll`: made in the body of a widget test, it waits in the fake time of that body, and a start that runs in real time never completes. | | scripts what the provider answers | It gives `appSession.start()` a service of its own, a class of the test that implements `AuthService`. | | needs another mode | It creates an `AppSessionController` of its own with that mode, and disposes of it. | | checks what the next launch finds | It runs `initAuth()` again, which creates the service anew, with the user who is signed in, and starts the session with it. | | brings the user back to the app | It may go through any state of the lifecycle: the session looks only at `AppLifecycleState.resumed`. | In an app with `sign_in` in the mode `required`, a test that starts the app to look at another screen sees the sign-in unless an account is signed in. The first row is how such a test gets one. [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#in-tests) has more on tests of the screens and of their state. A test that runs `bootstrap()` starts the service of the provider, which needs its platform side; see [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#in-tests). # Notifications and push messages Source: https://doc.saymyframe.com/guides/notifications Notifications and push messages are two roles of SMF, each with a module that provides it: | Part | Role | Module | What it brings | | --- | --- | --- | --- | | Notifications | Notifications | [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) | `appNotifications`: the permission to show notifications, a notification now or at about a time to come, and the taps on them. | | Push messages | Push messages | [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) | `appPush`: the address of the device for the backend of the app, the messages that the backend sends there, and the taps on them. | The push role requires the notifications role, since a message in the foreground shows as a notification of the app, and the permission to show messages is that of the notifications. So `firebase_messaging` brings `local_notifications` with it while that module is the only one that provides the notifications: ```bash smf create my_app -m home,onboarding,settings,bottom_tabs,firebase_messaging ``` An app can also have the notifications without push messages, with `-m local_notifications`. | File | From | What it holds | | --- | --- | --- | | `lib/core/notifications/app_notifications.dart` | the notifications role | `appNotifications`, through which code shows notifications and asks for the permission, `NotificationPermission`, `notificationOwnerKey` and `initNotifications()`. It exports `AppNotification` and `NotificationTap`, so the code of the app imports this file alone. | | `lib/core/notifications/notifications_service.dart` | the notifications role | `NotificationsService`, the interface that the module that provides the role implements, `AppNotification`, `NotificationTap`, and the channel and the icon of the notifications. The code of the app does not use it. | | `lib/core/notifications/notifications_setting.dart` | the notifications role, in an app with a settings screen | `NotificationsSetting`, the entry of the settings screen. | | `lib/core/notifications/notifications_step.dart` | the notifications role, in an app with an onboarding | The functions of the step of the onboarding that asks for the permission. | | `android/app/src/main/res/drawable/ic_notification.xml`, `android/app/src/main/res/raw/notifications_keep.xml` | the notifications role | The small icon of a notification on Android, and the file that keeps it in a release build. | | `lib/core/push/app_push.dart` | the push role | `appPush`, through which code reads the address, the messages and the taps, and `initPush()`. It exports `PushMessage`. | | `lib/core/push/push_service.dart` | the push role | `PushService`, the interface that the module that provides the role implements, and `PushMessage`. The code of the app does not use it. | `bootstrap()` starts both in its platform phase, after the preferences, so the app knows its permission and the tap that launched it before its first frame: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await Firebase.initializeApp(options: firebaseOptionsOfFlavor); await initPreferences(); await initNotifications(); await initPush(); } ``` Neither role registers anything in a DI container. Code of the app uses `appNotifications` and `appPush`, two top-level variables, and calls neither `initNotifications()` nor `initPush()`, which only `bootstrap()` calls. ## Show and schedule a notification ```dart import 'core/notifications/app_notifications.dart'; await appNotifications.show( const AppNotification( id: 1, title: 'Your order is on its way', body: 'It arrives today.', data: {'order': '42'}, ), ); await appNotifications.schedule( const AppNotification(id: 2, title: 'Time for a break'), at: DateTime.now().add(const Duration(hours: 1)), ); ``` | Call | What it does | | --- | --- | | `appNotifications.show(notification)` | Shows the notification now. | | `appNotifications.schedule(notification, at: time)` | Shows the notification at about that time, not to the minute, also when the app is closed then and after the device restarts. The time must be in the future. | | `appNotifications.cancel(id)` | Removes the notification of the id, shown or scheduled. | | `appNotifications.cancelAll()` | Removes every notification of the app, shown or scheduled. | | `appNotifications.scheduled()` | Lists the notifications that are scheduled and not shown yet. | A notification is an `AppNotification` with an `id`, a `title`, and an optional `body` and `data`. The id is a 32-bit integer from 0 up, which the platforms keep, and a notification with the id of one that is shown or scheduled takes its place: showing a notification cancels the scheduled one of its id. `show()` and `schedule()` fail with an `ArgumentError` for an id that the app does not take, and `schedule()` for a time that is not in the future. Both complete whether the app may show notifications or not, so ask for the permission first where it matters. Every notification goes to one channel of the app on Android, whose name in the settings of the system is the name of the app. A notification shows also while the app is in the foreground. On Android it has `ic_notification.xml` as its small icon: replace the bell there with the icon of the app, a shape on a transparent background, and keep the name of the file, since `notifications_keep.xml` keeps the icon in a release build by that name. ## The permission The app needs the permission of the user to show notifications. `appNotifications.permission` is a `ValueListenable` of a `NotificationPermission`: | Value | What it means | | --- | --- | | `granted` | The user allowed it. | | `denied` | The app asked, and the user did not allow it or turned the notifications of the app off later. | | `notAsked` | The app may not show notifications, and has not asked yet. | `appNotifications.request()` asks the user, unless the app may show notifications already, and completes with the permission once the user answered, also with a no. On Android 13 and later an app that may not show notifications looks the same whether it asked or not, so the app remembers that it asked in the preferences, under `notifications.asked`. That is why the notifications role requires the preferences role. - Where the system has no question to show, as on Android before 13, the request opens the settings of the system for the notifications of the app instead. So one request is enough on every platform. - After `denied`, the system may not ask again: iOS asks only once, and Android stops after a second no. `appNotifications.openSettings()` opens the settings of the system, where the user turns the notifications on. - A request while another is on its way completes with that one, since Android shows one question at a time. - The app asks the system again each time the user comes back to it, so the permission follows a change in the settings of the system. The app asks nothing when it starts. Where it asks depends on the other roles of the app: | The app has | Where it asks | | --- | --- | | An onboarding, such as [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) | On a page of its own in the onboarding, "Turn on notifications", with the buttons Allow notifications and Not now. The onboarding shows the page only while the permission is `notAsked`, and a user who skips the onboarding does not see it. | | A settings screen, such as [`settings`](https://doc.saymyframe.com/modules/settings.md) | The entry Notifications shows On or Off. A tap asks while the app has not asked, and opens the settings of the system after that. | | Neither | Nowhere yet. Call `appNotifications.request()` where the user turns on something that notifies, so that the question of the system explains itself. | An app with both has both. The texts of the step and of the entry are in English and in Ukrainian, and follow the language of an app with a module that provides the localization. ![The step of the notifications in the onboarding: a dark green cell with a bell, the title Turn on notifications, the text The app tells you when something needs your attention, even when it is closed., the button Allow notifications, and Not now below it.](https://doc.saymyframe.com/demo/0.8/app_2_onboarding_notifications.png) ![The settings screen in the light theme, with the entry Theme, the row Language and the row Notifications with the value Off.](https://doc.saymyframe.com/demo/0.8/app_5_settings.png) Since a user may skip the onboarding or say Not now, code that needs notifications checks `appNotifications.permission` and calls `request()` itself. ## Taps A tap on a notification reaches `appNotifications.taps`, a stream of `NotificationTap`s, each with the `id` and the `data` of its notification. `appNotifications.launchTap` is the tap that launched the app, known once `bootstrap()` is over. Read both once the first screen is shown, and navigate as the rest of the app does: ```dart final tap = appNotifications.launchTap; if (tap != null) openOrder(tap.data['order']); appNotifications.taps.listen((tap) => openOrder(tap.data['order'])); ``` A notification runs no code of the app when it shows. An error of the provider when the user comes back to the app, or one that its taps send, has no caller, so it reaches the handlers of the uncaught errors of the app, and the notifications go on. ## Notifications with an owner A notification may have an owner: code that shows it and handles its taps itself, such as the push role, which shows the messages that arrive in the foreground. Such a notification names its owner under `notificationOwnerKey` in its `data` and has a negative id, so that it never takes the place of a notification of the app. `show()` and `schedule()` refuse a negative id without an owner, and an owner with an id from 0 up. `appNotifications.taps` and `launchTap` leave out the taps on a notification with an owner. `appNotifications.tapsOf(owner)` and `launchTapOf(owner)` give them to their owner, so the code of the app sees each tap once. `scheduled()` and `cancelAll()` take the notifications of an owner too. ## Push messages A backend sends push messages to the address of a device, through the provider of the push role. With `firebase_messaging` the address is the registration token of Firebase Cloud Messaging, and the backend sends through Firebase; see [Cloud Messaging](https://doc.saymyframe.com/guides/firebase.md#cloud-messaging). Firebase sends to iOS only once you have uploaded the APNs key of your team to the Firebase project, a step by hand with a [click-by-click guide](https://doc.saymyframe.com/setup/firebase-messaging-apns-key.md). Signing the app with your paid team has [a guide of its own](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md). ### The address `appPush.address` is a `ValueListenable` of the address of this device. It is `null` until the platform gives one, and the app works without it. The app asks for it when it starts, without waiting for it, so the first frame never waits for the network, and again each time the user comes back to the app while it has none. Listen to it and send each new address to the backend: it may come late, and it may change. ```dart import 'core/push/app_push.dart'; void sendAddressToBackend() { final address = appPush.address.value; if (address != null) backend.registerDevice(address); appPush.address.addListener(() { final address = appPush.address.value; if (address != null) backend.registerDevice(address); }); } ``` In debug mode the app prints each new address, so you can send this device a message by hand: ```text The address of this device for push messages: ``` On iOS the address needs a token of the Apple Push Notification service (APNs), which iOS gives only to a build signed with the entitlement `aps-environment`. The push role adds it to `ios/Runner/Runner.entitlements` with the value `development`, and the background mode `remote-notification` to `Info.plist`. - The iOS simulator on a Mac gets a token. One on a macOS virtual machine, such as a hosted CI runner, never does. - On an iPhone, signing with the entitlement needs a team of the paid Apple Developer Program, which is a step by hand of the app; see the [click-by-click guide](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md). With a free personal team, Xcode cannot sign the app. To run it on an iPhone then, remove the key `aps-environment` from `ios/Runner/Runner.entitlements`, and the app runs there without an address. The simulator needs no change. - The value `development` suits the builds that you run from Xcode. When Xcode exports the app for distribution, it takes the value of the provisioning profile. ### Messages A message is a `PushMessage` with `data`, and with an `id`, a `title` and a `body` when it has them. A value of its data that the platform gives as something other than a string is its JSON. | The app is | A message with a title or a body | A message with data alone | | --- | --- | --- | | In the foreground | Reaches `appPush.messages`, and shows as a notification. Where the system does not show it, the app shows it as a notification of its own through `appNotifications`, owned by the push role. | Reaches `appPush.messages`. | | In the background, or closed | The system shows it, on Android in the channel of the notifications of the app. | Runs no code of the app. | Either way the user has to allow the notifications of the app for a message to show. The push role asks for no permission itself: `appNotifications.request()` asks, as above. Images in a message do not show on iOS, which needs an extension of the app for them. ### Taps on messages `appPush.taps` tells of each tap on a message while the app runs, whether the system or the app showed it. `appPush.launchMessage` is the message whose tap launched the app, known once `bootstrap()` is over. Read both once the first screen is shown, and navigate as the rest of the app does. A tap on a message does not reach `appNotifications.taps`, so the code of the app sees each tap once. ## For a provider A module that provides one of these roles implements its interface, `NotificationsService` or `PushService`, and contributes the implementation as data of the role, as the providers of other service roles do; see [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#notifications-and-push-messages). The doc comments of the two interfaces in the app hold their contracts. In short: - The function that creates the service asks the user nothing, and may be called again. The service that it returns then has what the device kept, such as the scheduled notifications or the address. - A provider of notifications shows every notification in the channel `notificationChannelId` with a high importance and, on Android, the small icon `notificationIcon`, also in the foreground. `schedule` shows a notification at about its time, also after a restart of the device, and needs no permission for exact alarms. `show` cancels the scheduled notification of its id. `request` completes once the user answered, and opens the settings of the system where the platform has no question to show. - A provider of push messages never asks for the permission to show notifications, and never keeps the notifications of the app from showing in the foreground. Its `address` and `launchMessage` never throw, and the address stays the same from one launch to the next unless the platform gives the device another, which `addressChanges` tells of. `platformShowsInForeground` says whether the platform shows a message in the foreground. Where it does not, the service shows nothing of the message, and the app shows it. The structural rules `notifications.factory_calls` and `push.factory_calls` check that only the files of the implementation import the file of the interface, and `notifications.start_calls` and `push.start_calls` that only `bootstrap()` starts the roles. Only a running app shows whether a provider keeps to the rest. SMF's CI checks both roles in running apps with a fixture provider of each, and with a broken one that each test must fail on; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## The README and the guide for coding agents The notifications role writes the section "Notifications" of the README of the app: how the app shows notifications, the permission and where the app asks for it, and the small icon of Android. The push role writes "Push messages": the address and what it needs on iOS, how a message shows, and the taps. Each provider adds a section of its own, such as how to send a test message. The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app has the sections "Notifications" and "Push messages", with a note of the role and one of the provider in each. ## In tests A test of an app with these roles runs `bootstrap()`, which starts the service of each provider. The packages of the providers have no platform side for tests, so a test answers their channels itself; see [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md#in-tests) and [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md#in-tests). | A test that | Does this | | --- | --- | | scripts what a provider answers | It gives `appNotifications.start()` or `appPush.start()` a service of its own, a class of the test that implements `NotificationsService` or `PushService`. | | checks what the next launch finds | It runs `initNotifications()` or `initPush()` again, which creates the service anew with what the device kept. The address is then `null` until the new service gives one. | | brings the user back to the app | It may go through any state of the lifecycle: both roles look only at `AppLifecycleState.resumed`. | A call of `appNotifications` made before the first `initNotifications()` waits for it. The mocks of the modules start as on a first launch: the app may not show notifications and has not asked, so the onboarding shows its step. A request grants the permission, so a test that asks goes on with an app that may show notifications. # Purchases Source: https://doc.saymyframe.com/guides/purchases A generated app can sell premium access: the user buys a plan, such as a monthly or a yearly subscription or a payment once, and every plan gives the same access. It has two parts, each from a module of its own: | Part | Role | Module | What it brings | | --- | --- | --- | --- | | The purchases | Purchases | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | `appPurchases`: whether the user has premium access, known before the first frame, the plans of the current offer, a purchase and a restore. | | The screens | none | [`paywall`](https://doc.saymyframe.com/modules/paywall.md) | The paywall, the screen of the subscription, the guard that shows the paywall to a user without the access, a row of the settings screen and a step of the onboarding. | `paywall` requires the purchases role, so it brings `revenuecat` while that module is the only one that provides it, and `dart_define` for the API keys of RevenueCat in `.env`: ```bash smf create my_app -m home,onboarding,settings,bottom_tabs,paywall,bloc ``` An app can also have the purchases without the paywall, with `-m revenuecat`, and screens of your own. | File | From | What it holds | | --- | --- | --- | | `lib/core/purchases/app_purchases.dart` | the purchases role | `appPurchases`, through which code reads the access of the user, gets the plans, buys and restores, and `initPurchases()`. It exports the types of the answers, so the code of the app imports this file alone. | | `lib/core/purchases/purchases_service.dart` | the purchases role | `PurchasesService`, the interface that the module that provides the role implements, with `AppAccess`, `Plan`, `IntroOffer`, `BillingPeriod` and `PurchasesFailure`. The code of the app does not use it. | | `lib/core/purchases/restore_purchases_setting.dart` | the purchases role, in an app with a settings screen | `RestorePurchasesSetting`, the row of the settings screen that restores purchases. | | `lib/core/purchases/revenuecat_purchases_service.dart` | `revenuecat` | The purchases service on RevenueCat. | `bootstrap()` awaits `initPurchases()` in its platform phase, so the app knows the access of the user before its first frame. In an app with sign-in it comes after `initAuth()`, whatever the order of the modules, so the purchases are those of the user who is signed in. This is `bootstrap()` of an app with `revenuecat` and `firebase_auth`: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await Firebase.initializeApp(options: firebaseOptionsOfFlavor); await initAuth(); await initPurchases(); } ``` The start waits for the access at most 3 seconds, from what the device keeps. An access that comes later still counts, and the app does not wait for it. The role registers nothing in a DI container: code uses `appPurchases`, a top-level variable, and calls neither `initPurchases()` nor `createPurchasesService()`. ## The access of the user `appPurchases.value` is the `AppAccess` of the user: `NoAccess`, or `PremiumAccess` while a plan that the user bought is active. `appPurchases.hasPremium` is a `ValueListenable` that tells which, for a widget or a guard of the routes: ```dart import 'core/purchases/app_purchases.dart'; ValueListenableBuilder( valueListenable: appPurchases.hasPremium, builder: (context, premium, _) => premium ? const ExportButton() : const UpgradeHint(), ); ``` In an app with [`paywall`](https://doc.saymyframe.com/modules/paywall.md), a widget reads the access through the state manager of the app instead, as `context.watch().state` with BLoC or `ref.watch(premiumProvider)` with Riverpod. `PremiumAccess` tells: | Field | What it is | | --- | --- | | `expiresAt` | When the access ends, or `null` for an access that never ends, as of a plan paid once. | | `renews` | Whether the plan renews at the end of its period. | | `inTrial` | Whether the access is a free trial. | | `period` | How often the plan is billed, or `null` for a plan paid once and while the provider does not know it yet. | | `manageUrl` | The page of the store where the user manages or cancels the plan, or `null`. | The access changes when the user buys or restores, and when the provider learns of a renewal, an expiry, a refund or a grant made elsewhere. The app asks for the access again each time the user comes back to it. ## Buy and restore | Call | What it does | | --- | --- | | `appPurchases.plans()` | Gives the plans of the current offer, in the order of the provider. | | `appPurchases.purchase(plan)` | Buys the plan. It completes with `true` once the user has premium access, and with `false` when the user cancelled, which is no failure. | | `appPurchases.restore()` | Gives the user what the store account bought, such as on a new device, and completes with the access. | A `Plan` has an `id`, a `title`, its `price` as the store shows it, its `amount` and `currencyCode`, its `period`, which is `null` for a plan paid once, and its `introOffer`, a free trial or a lower price at first that this user may take. A `BillingPeriod` is a `count` of a `unit`: a day, a week, a month or a year. The calls run one after another, in the order they were made. A call fails only with a `PurchasesFailure`. Show a text of the app for its `reason`, and its `developerHint` in debug mode only: | Reason | What it means | | --- | --- | | `network` | The device did not reach the store or the provider. | | `pending` | The payment waits for an approval, as one that a parent approves. The access comes later without another call. | | `alreadyOwned` | The store account owns the plan already: a restore gives the access. | | `notAllowed` | The user may not pay on this device, as with parental controls. | | `unavailable` | The store, or the plan, is not available on this device or for this store account. | | `storeProblem` | The store failed on its side. Trying again later may help. | | `notConfigured` | Purchases are not set up, such as a key of the provider that is missing, or an offer without plans. The `developerHint` says what is missing. | | `unknown` | Anything else. The `developerHint` has the error. | A purchase whose answer gives no premium access fails with `notConfigured`, whichever provider gave it, since every plan gives that access. ## Screens only for premium users The role publishes `PurchasesRole.premium`, the condition of a route whose screen is only for a user with premium access. A route asks for it in its `conditions`, and a module that requires the role stands for it with a guard whose function returns `appPurchases.hasPremium`. [`paywall`](https://doc.saymyframe.com/modules/paywall.md) declares that guard, `paywall.hasPremium`, and its target is the paywall: a request for such a route from a user without the access opens the paywall over the page, and the router shows the route once the user has bought a plan. See [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md). In an app without such a guard, the routes that ask for the condition show to every user, and the role warns of nothing. A screen never redirects itself. ## Restore purchases In an app with a [settings screen](https://doc.saymyframe.com/modules/settings.md), the role gives it `RestorePurchasesSetting`, the row Restore purchases. A tap restores once and shows what the restore found: | The restore | The row says | | --- | --- | | found premium access | Your premium access is back. | | found nothing | No purchases to restore. | | failed | Couldn't restore purchases. Try again. In a debug build, the words of the provider are below it. | While a restore is on its way, the row shows a spinner and takes no other tap. A failure looks the same whatever its reason. A screen reader reads each result as it comes. The four texts are in English and in Ukrainian, and follow the language of an app with a module that provides the localization. In an app without a settings screen, the screen that sells offers the restore itself, as the paywall does with its link Restore purchases. ## Whose purchases they are Without sign-in, the purchases belong to this installation of the app. On another device, or after the app was installed again, the user restores them. With sign-in, such as [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md), `appPurchases` follows `appSession`. The purchases belong to the user of the session, by the id of the user, and to the user of this device while nobody is signed in: | What the user does | Whose the purchases are then | | --- | --- | | Buys without an account, then signs up | The new account's: it takes them over from the user of this device. An anonymous user keeps them too, since the account keeps the id of that user. | | Buys without an account, then signs in to an account that exists already | Still the user of this device's. The account gets them only through a restore. | | Signs out | The user of this device is a new one, with nothing bought. Without a restore, the next user of the device never gets the purchases of a user who signed out. | | Restores | The user who is signed in gets what the store account bought. The backend of the provider decides whether that moves purchases away from another user. | The app does not restore on its own: it restores where the user asks for it. A call of `appPurchases` waits for a change of the user, and a change of the user waits for the call on its way, so a purchase belongs to the user who made it. ## What a screen that sells shows The App Store and Google Play ask a screen that sells a plan to show: - the name of the plan, how long a period lasts and what the user gets; - the full price that the store charges for each period, shown more clearly than any other price on the screen, and for a yearly plan never mainly as a price per month; - for a free trial or a lower price at first, how long it lasts and the price after it; - that the plan renews until the user cancels, and how to cancel it in the store; - a way to restore purchases; - links to the terms of use and the privacy policy of the app; - a visible way to close the screen without buying. The [paywall](https://doc.saymyframe.com/modules/paywall.md#what-the-stores-ask-of-a-paywall) shows each of these. A screen of your own shows them too. ## While purchases are not set up Until the provider has what it needs, such as its API keys, the app runs without purchases. `appPurchases.value` stays `NoAccess`, every call fails with the reason `notConfigured`, and a debug build prints its hint once, which names what is missing. An error that no caller sees, such as one of the start or of a return to the app, changes nothing. `network`, `unavailable` and `storeProblem` say nothing then, so a store that does not answer reaches no crash report. Any other error reaches the handlers of the uncaught errors of the app. ## Steps by hand Selling in the stores takes steps that no command can do: agreements and products in App Store Connect and Google Play Console, and the setup of the provider. The purchases role lists the two steps in the stores, which every provider that sells there needs, and the provider lists its own. The README of the app lists them in its section "Finish the setup", and `smf create` prints the link to their guides. The guides of [the payments](https://doc.saymyframe.com/setup/purchases-store-agreements.md) and of [the products](https://doc.saymyframe.com/setup/purchases-store-products.md) show the stores click by click. ## For a provider A module that provides the role implements `PurchasesService` and contributes the implementation as data of the role, as the providers of the other service roles do; see [Provide a role](https://doc.saymyframe.com/extending/role-provider.md). The doc comments of the interface in the app hold its contract. In short: - The function that creates the service creates it without a user, asks the user nothing and never throws. It may be called again, and the new service has what the store and the provider kept. - `identify(userId)` comes before any other call. `null` stands for the user of this device. Identifying the user who is identified already does nothing. - `identify(null)` after another user starts a new user of this device, with nothing bought. When the user of this device is identified as a user that no `identify` named before, on any device, that user takes over the purchases of the user of this device. Any other identification keeps the purchases of each user apart. - `access()` completes from what the device keeps, and `accessChanges` tells of each change of the access that the provider learns of. - `plans()` gives at least one plan. A backend with nothing to offer fails with `notConfigured` and a hint. - `purchase(plan)` completes with the premium access once the store took the payment, and with `null` when the user cancelled. It fails with `pending` while the payment waits for an approval, and with `alreadyOwned` for a plan that the store account owns. - Every call fails only with a `PurchasesFailure`. Without what it needs, such as a key, the provider fails every call with `notConfigured` and a hint that names what is missing, and never stops the app. The structural rule `purchases.factory_calls` checks that only the files of the implementation import the file of the interface, `purchases.start_calls` that only `bootstrap()` starts the purchases, and `purchases.implementation_factories` that the function of the implementation is in its file and takes no arguments. Only a running app shows whether a provider keeps to the rest. ## The README and the guide for coding agents The purchases role writes the section "Purchases" of the README of the app: what `appPurchases` tells and does, what a screen that sells shows, the premium routes, whose the purchases are and where the user restores them, and what the app does while purchases are not set up. Each module adds a section of its own, such as "RevenueCat" and "Paywall". The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app has the section "Purchases", with a note of the role and one of the provider. In an app with sign-in, the role adds whose the purchases are, and in an app with a settings screen, where the restore is. [`paywall`](https://doc.saymyframe.com/modules/paywall.md) writes the section "Paywall". ## In tests A test of an app with the role runs `bootstrap()`, which starts the service of the provider. The package of [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md#in-tests) has no platform side for tests, so a test answers its channel itself. | A test that | Does this | | --- | --- | | scripts what a provider answers | It gives `appPurchases.start()` a service of its own, a class of the test that implements `PurchasesService`, with a user of its own, such as the value of a `ValueNotifier`. | | checks what the next launch finds | It runs `initPurchases()` again, which creates the service anew with what the store and the provider kept. | | starts the app with premium access | It buys a plan before `bootstrap()`, with `appPurchases.plans().then((plans) => appPurchases.purchase(plans.first))` made outside the body of a test, as in a `setUpAll`. Such a call runs within the first start, so the app starts with the access. | | brings the user back to the app | It may go through any state of the lifecycle: the role looks only at `AppLifecycleState.resumed`. | The mocks of a provider start as on a first launch: nothing is bought, and the offer has at least one plan. A purchase by a user without premium access succeeds at once. Whichever module provides the role, a fresh user who buys a plan has premium access, the next start of the app gives the same user the same access, and the purchases of each user stay apart. SMF's CI checks this in running apps with the role, with sign-in in each of its modes and without it, with a fixture provider, and with a broken one that keeps the purchases of every user together, which the tests must fail on. It also checks the row Restore purchases of the settings screen. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). # Values in .env Source: https://doc.saymyframe.com/guides/env Some modules need values that only you have, such as the public API key of a service or the address of a page. A module names each value as a key, and the role of the values in `.env` puts the keys of every module of the app into `.env` at the root of the app. You fill in the values there, and code reads them through `AppEnv`. | Part | Role | Module | What it brings | | --- | --- | --- | --- | | Values in .env | Values in .env | [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) | `AppEnv`, whose getters return the values of `.env`, compiled into the app with `--dart-define-from-file`. | A module that needs such values brings `dart_define` with it while that module is the only one that provides the role, as [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md), [`paywall`](https://doc.saymyframe.com/modules/paywall.md) and [`dio`](https://doc.saymyframe.com/modules/dio.md) do: ```bash smf create my_app -m paywall,bloc ``` | File | From | What it holds | | --- | --- | --- | | `.env` | the role | A comment and an empty line `KEY=` for each key of the app. You fill in the values here. It stays out of git. | | `.env.example` | the role | The same keys without values. It stays in git, so a clone of the app knows which values to fill in. | | `.gitignore` | the role adds a line | `.env`, under a comment that tells where its values come from. | | `lib/core/env/app_env.dart` | the module that provides the role | `AppEnv`, with a static getter for each key. | Right after `smf create`, every value is empty, and the app builds and starts. A module whose value is missing works without it as far as it can: [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) runs the app without purchases, [`paywall`](https://doc.saymyframe.com/modules/paywall.md) leaves out a link, and [the REST client](https://doc.saymyframe.com/guides/rest.md) fails a relative path with `notConfigured`. ## Write a value ```bash title=".env" # The public API key of the Test Store in RevenueCat, which starts with test_, for debug builds only REVENUECAT_TEST_KEY=test_AbCdEf123 # The address of the terms of use that the paywall links to PAYWALL_TERMS_URL="https://example.com/terms#refunds" ``` | You write | The app reads | | --- | --- | | `KEY=value`, a plain value without `#`, spaces or quotes | `value` | | `KEY="any value"`, in double quotes | `any value`. A value with a space, a `#` or a quote goes in double quotes. | | `KEY=value # a comment` | `value`. After a plain value, `#` starts a comment, so an address with an anchor needs the quotes. | | `KEY=` | `null`. An empty value counts as missing. | | A line that starts with `#` | Nothing: it is a comment. | The comment at the top of `.env` and `.env.example` says this in one line. Every module that provides the role reads both forms of a value alike. After a clone of the app, copy the example and fill it in: ```bash cp .env.example .env ``` ## One file for all flavors `.env` is one file, and it is not tied to a [flavor](https://doc.saymyframe.com/guides/flavors.md). A build of any flavor takes what `.env` has when its command runs. So when `staging` needs another address than `dev`, change the value by hand before you build it: ```bash title=".env" REST_BASE_URL=https://staging.example.com/v1 ``` ```bash flutter build apk --flavor staging --dart-define-from-file=.env ``` [CI](https://doc.saymyframe.com/guides/ci.md) writes a `.env` of its own for each job, from the variables of the environment of the job, with `dart tool/write_env.dart`. That script stops rather than replace a value, so a developer who runs it on a machine with a filled `.env` loses nothing. :::warning Every value ends up in the app, where anyone who has the app can read it. So `.env` holds only values that may be public, such as the public key of a service or the address of a page. Never put a secret there, such as the secret key of a server, a password or a private key. ::: ## Read a value Code reads a value only through the static getter of its key in `AppEnv`. The getter is the key in lowerCamelCase, and returns a `String?`, which is `null` while the value is empty or missing: ```dart import 'core/env/app_env.dart'; final terms = AppEnv.paywallTermsUrl; if (terms != null) showTermsLink(Uri.parse(terms)); ``` A getter returns its value at once, before any code of the app runs, `main()` included, so code reads it anywhere without waiting, and so does a test that does not start the app. Handle `null`: a value that nobody filled in yet is no error. Never read `.env` or `.env.example` from code. The keys of the built-in modules: | Key | Getter | Module | What goes there | | --- | --- | --- | --- | | `REVENUECAT_APPLE_KEY` | `AppEnv.revenuecatAppleKey` | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | The public API key of the App Store app in RevenueCat, which starts with `appl_` | | `REVENUECAT_GOOGLE_KEY` | `AppEnv.revenuecatGoogleKey` | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | The public API key of the Play Store app in RevenueCat, which starts with `goog_` | | `REVENUECAT_TEST_KEY` | `AppEnv.revenuecatTestKey` | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | The public API key of the Test Store in RevenueCat, which starts with `test_`, for debug builds only | | `PAYWALL_TERMS_URL` | `AppEnv.paywallTermsUrl` | [`paywall`](https://doc.saymyframe.com/modules/paywall.md) | The address of the terms of use that the paywall links to | | `PAYWALL_PRIVACY_URL` | `AppEnv.paywallPrivacyUrl` | [`paywall`](https://doc.saymyframe.com/modules/paywall.md) | The address of the privacy policy that the paywall links to | | `REST_BASE_URL` | `AppEnv.restBaseUrl` | the role [REST API](https://doc.saymyframe.com/guides/rest.md) | The address of the REST API of the app, such as `https://api.example.com/v1` | `REST_BASE_URL` belongs to the role, whichever module provides it. The keys are in `.env` in the order of the modules of the app, followed by those of the roles. The section "Values in .env" of the README of the app lists the keys of that app, each with its getter, where it comes from and what goes there. ## Get the values into the app How the values get into the app is up to the module that provides the role. With [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md), the `flutter` tool reads `.env` when a command that builds, runs or tests the app starts, given `--dart-define-from-file=.env`: ```bash flutter run --dart-define-from-file=.env ``` Without the argument, every getter is `null`. The run configurations of VS Code and Android Studio pass it for you, and a change of `.env` reaches the app once you start `flutter run` again; see [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md#run-test-and-build). ## A key of your own Put the key into both `.env.example` and `.env`, in UPPER_SNAKE_CASE, with a comment line above it that says what goes there. Then give `AppEnv` a getter for it, named by the key in lowerCamelCase, as the module that provides the role writes the others. The section of that module in the README of the app shows the getter. ## In a module of your own A module that needs a value gives the role a key, an `EnvKey` with a name and a description, and lists the role among the roles it requires or uses: ```dart static const apiKey = EnvKey( 'WEATHER_API_KEY', description: 'The public API key of the weather service', ); ``` - The name is in UPPER_SNAKE_CASE, of two words or more, and starts with the id of the module in upper case and an underscore, such as `WEATHER_` for a module `weather`. It never starts with `FLUTTER_`. - The description is one line of at most 100 characters. It becomes the comment of the key in `.env` and the doc of its getter. - A brick of the module reads the value through a variable of `envRole.varsOf(id, keys)`, named `env_`, such as `{{{env_weather_api_key}}}`. It is `AppEnv.weatherApiKey` in an app with the role and `null` in an app without it, so the code takes a `String?` there and is no `const`. - A module that requires the role may also read `AppEnv` in its own code. The module rule `env.keys` checks the keys and the variables of a module. `env.key_access` checks that the files of a module read only its own keys and those of the modules it depends on, and `env.keys_rendered` that `AppEnv` has a getter for every key. The template of a role that requires or uses the role gives a key the same way, for a value that the template reads whichever module provides its role, as the REST role does with `REST_BASE_URL`. Its name starts with the id of the role. ## For a provider A module that provides the role generates `AppEnv` in `lib/core/env/app_env.dart`: an `abstract final class` with a static `String?` getter for each key of `envRole.keysIn(input)`. Its getters keep to the contract of the role: - A getter returns the value that `.env` has for its key, or `null` when the value is empty or the key is missing. - It returns it at once, before any code of the app runs. A provider that loads `.env` while the app runs, which takes a `Future`, or that sets the values in `main()`, does not keep the contract. - A command of the `flutter` tool that builds, runs or tests the app gives `AppEnv` the values that `.env` has when the command runs, and nothing else runs after `.env` changes. A provider whose values need code generation after an edit of `.env` does not keep the contract either. A provider that needs arguments on those commands gives them to the role as `EnvToolArguments`, as `dart_define` gives `--dart-define-from-file=.env`. Code that runs the commands, such as a run configuration or a test tool, takes them from `envRole.toolArgumentsIn(input)` without knowing what they mean. ## In tests Whichever module provides the role, a getter returns the value that `.env` has for its key, and `null` for a key that `.env` leaves empty or lacks. SMF's CI checks this in running apps with the role, with a fixture provider, and with a broken provider that the test must fail on: one whose `AppEnv` returns an empty value as an empty text. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). # REST API Source: https://doc.saymyframe.com/guides/rest The REST role gives an app one client, `appRest`, for its requests to a REST API. The role is defined by what the client guarantees, and the guarantees live in code that the role generates, so they hold whichever module sends the requests. | Part | Role | Module | What it brings | | --- | --- | --- | --- | | The client | REST API | [`dio`](https://doc.saymyframe.com/modules/dio.md) | `appRest` in `lib/core/rest/app_rest.dart`, which sends its requests over a `Dio` | ```bash smf create my_app -m dio ``` The role reads the address of the API from `.env`, so `dio` brings [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) while that module is the only provider of the values in `.env`. No screen of the app makes a request on its own: the client is there for the code that you add. An app also gets two test files, `test/core/rest/rest_test_server.dart` and `test/core/rest/app_rest_test.dart`, and the permission `android.permission.INTERNET`. ## The address `REST_BASE_URL` in `.env` is the address of the API. Fill it in, then start `flutter run` again, since a command reads `.env` when it starts: ```bash title=".env" REST_BASE_URL=https://api.example.com/v1 ``` While it is empty, the app still builds and starts, and a relative path fails with `notConfigured`, whose hint names the key. On a device, `http://10.0.2.2:8080` is your computer on the Android emulator, and `http://127.0.0.1:8080` on the iOS simulator. A phone reaches it at its address on your network. Use `https` in a release. The client also sends the token of the user over `http://`, so an address in a release is yours to get right. `.env` is one file, not tied to a flavor. [Values in .env](https://doc.saymyframe.com/guides/env.md#one-file-for-all-flavors) tells how each environment gets its own address. ## Make a request `appRest` has `get`, `head`, `post`, `put`, `patch` and `delete`. A path joins the address, with or without a leading slash, and keeps the path of the address: ```dart final response = await appRest.get('notes', query: {'page': '1'}); ``` | Argument | What it does | | --- | --- | | `query` | The query of the address, as a map | | `headers` | Headers of this call | | `json` | For `post`, `put`, `patch` and `delete`: a value that the client sends as JSON | | `timeout` | The time of one attempt of this call, 30 seconds by default | | `cancel` | A `RestCancel` that ends this call | A full address with `http://` or `https://` goes where it says, such as a link to the next page or an upload address. A path that climbs out of the address with `..`, written as it is or encoded, fails with `rejected` before anything is sent. So encode what a user types with `Uri.encodeComponent`. Call the client from the state of a screen or from a repository, never from a widget. The code of the app creates no other client, and it calls neither `createRestTransport()` nor `appRest.use()`, which is for tests. ## Read the answer A `RestResponse` has `status`, `headers`, `bytes` and `text`. `decoded` turns the JSON of the body into your type: ```dart final note = response.decoded(Note.fromJson); ``` The JSON of a list is a `List`, so a function of a list takes that and casts its items inside: ```dart final notes = response.decoded( (List json) => [ for (final item in json) Note.fromJson(item as Map), ], ); ``` A body that is no JSON, a body of another type than the function takes, and any error of the function fail with `invalidResponse`. The role generates no models. For generated ones, run `flutter pub add json_annotation dev:json_serializable dev:build_runner` and pass the `fromJson` of the model. The `headers` have lower-case names and join several values of one header with `, `, so several `set-cookie` values cannot be told apart there. A body in a coding that the provider did not decode has `content-encoding` and `content-length`, and comes as it is. A body that it decoded has neither. ## Failures A call fails only with a `RestFailure`. Show a text of the app for its `reason`, and its `developerHint` in debug mode only. The hint never has a token, a query or a body. | Reason | When | | --- | --- | | `notConfigured` | A relative path, and `REST_BASE_URL` is empty or no address of a server | | `network` | The request did not reach a server, or the connection broke | | `timeout` | No complete answer within the timeout of the attempt, or no token of the user within `tokenWait`, 10 seconds | | `cancelled` | A `RestCancel` ended the call | | `unauthorized` | A 401, after one refresh of the token where the client added one | | `forbidden`, `notFound`, `conflict` | A 403, a 404, a 409 | | `rejected` | Any other 4xx, or a relative path that climbs out of the address | | `tooManyRequests` | A 429 | | `server` | A 5xx | | `invalidResponse` | A body that `decoded` does not take | | `unknown` | Anything else, such as a redirect of a `POST`, with the type of the error as its hint | `failure.status` has the status of the answer, `failure.response` the refusal itself, whose body may say why, and `failure.retryAfter` the wait that the server named and the client did not take. ## Repeats and redirects `GET` and `HEAD` repeat twice at most after a connection that failed and after 429, 502, 503 and 504. They keep to a `Retry-After` of up to 30 seconds. They also follow at most 5 redirects. Other methods never repeat, since the server may have done what they asked, and a redirect of another method fails with `unknown`. So never wrap a call in a loop of your own. The timeout is per attempt, so a `GET` with its repeats may take longer than the timeout. A debug build prints one line for each attempt, with the origin and the path alone. ## Cancel a call A `RestCancel` ends a call and its waits at once, and the call fails with `cancelled`. Give each call a cancel of its own, and cancel those on their way where the state of a screen is disposed of. This shape comes from a small consumer that SMF's tests keep, a list of notes on a server: ```dart final class Notes extends ValueNotifier { Notes() : super(const NotesLoading()); final Set _calls = {}; Future load() async { final cancel = RestCancel(); _calls.add(cancel); value = const NotesLoading(); try { final response = await appRest.get('notes', cancel: cancel); final notes = response.decoded(_notesOf); if (!cancel.isCancelled) value = NotesShown(notes); } on RestFailure catch (failure) { if (!cancel.isCancelled) value = NotesFailed(failure.reason); } finally { _calls.remove(cancel); } } static List _notesOf(List json) => [ for (final item in json) Note.fromJson(item as Map), ]; @override void dispose() { for (final call in _calls) { call.cancel(); } super.dispose(); } } ``` The state knows the role and no module behind it, with one import and no container or router. The widget reads `Notes` and shows a text for `NotesFailed.reason`. ## The token of the user In an app with [sign-in](https://doc.saymyframe.com/guides/sign-in.md), each request to the origin of `REST_BASE_URL` carries the token of `appSession` as `Authorization: Bearer `. The origin is the same scheme, host and port. No other request has the token. - A redirect to another origin takes the token away, with the `authorization`, `cookie` and `proxy-authorization` of the caller. Only a hop back to the origin of the app gets the token again. - A header `authorization` that a call gives stays in place of the token. - On a 401 of a request with that token, the client gets a new token once and repeats once, for every method. Calls at the same time share one refresh. - A second 401, a refresh that finds nobody, and a user other than the one who made the request all fail with `unauthorized`. That signs nobody out, since a server may refuse for other reasons, so the app decides what it means. - A request made while the app starts, before the session is known, waits for the start at most 3 seconds and goes without a token if the session is still not there. So make a request that needs the user after `bootstrap()`. The server checks the token itself. With [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) it is a Firebase ID token, and a server verifies it with the Firebase Admin SDK of the project of the flavor. The session also gives the token to other code, with `appSession.userToken()` and `appSession.userTokenAfter(rejected)`; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#a-token-for-your-server). ## In tests `flutter test` answers 400 to every `HttpClient`, which reaches your code as `rejected`. `RestTestServer` of `test/core/rest/rest_test_server.dart` is a local server that takes that stand-in away while it is open: ```dart late RestTestServer server; late AppRestClient client; setUp(() async { server = await RestTestServer.start(); client = AppRestClient( transport: createRestTransport(), baseAddress: '${server.address}/v1', ); }); tearDown(() => server.close()); test('a relative path reaches the address', () async { server.answerJson('GET', '/v1/notes', ['a', 'b']); final notes = await client.get('notes', query: {'page': '1'}); expect(notes.decoded((List json) => json.length), 2); expect(server.requests.single.uri.toString(), '/v1/notes?page=1'); }); ``` Each server takes a free port, so give the client `server.address`. To test code that calls `appRest` itself, point it at the server with `appRest.use(baseAddress: server.address)`, or script the answers with `appRest.use(transport: …)` and a `RestTransport` of the test. Inside `testWidgets` the time is fake, and a real socket never completes there. Make such a request in `tester.runAsync`, and let it end before the test does, since a request that is still running when the body ends fails the test with a pending timer. A plain `test()` runs in real time. ## For a provider A provider implements `RestTransport` of `lib/core/rest/rest_transport.dart`, one exchange on the wire. See [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#rest-api). # App icon and splash screen Source: https://doc.saymyframe.com/guides/app-icon-and-splash Two roles give an app its icon and the screen that the system shows while the app starts: | Part | Role | Module | What it brings | | --- | --- | --- | --- | | The icon | App icon | [`launcher_icons`](https://doc.saymyframe.com/modules/launcher-icons.md) | An opaque icon on iOS, and an adaptive icon with a themed variant on Android, in place of the logo of Flutter | | The screen | Splash screen | [`native_splash`](https://doc.saymyframe.com/modules/native-splash.md) | A screen for the light and for the dark mode of the device, in place of the white screen of `flutter create` | ```bash smf create my_app -m launcher_icons,native_splash ``` A run in a terminal asks for each. A run with `--no-input`, or a `-m` without these modules, keeps the logo of Flutter and a white launch screen. The tools run once the app has its packages. A run in a terminal asks first, and Enter runs them. A tool that fails costs a warning and the command for later, and you still get the app. The tools are only dev dependencies, so no code of the app imports them. ## The images The sources are in `assets/branding/`, and the app does not bundle them: | File | Size | What it is | | --- | --- | --- | | `icon.png` | 1024 by 1024, opaque | The icon on iOS and on older versions of Android. The App Store refuses an icon with alpha. | | `icon_foreground.png` | 1024 by 1024, on a transparent background | The adaptive icon of Android, and through its alpha the themed icon. Launchers cut it to a shape of their own and always keep a circle around its centre, as wide as 90% of the image. | | `splash_light.png` | 1152 by 1152, on a transparent background | The screen in the light mode of the device | | `splash_dark.png` | 1152 by 1152, on a transparent background | The screen in the dark mode of the device. Android 12 and later cut both images to a circle of two thirds of their width. | As generated, they show the mark of Say My Frame: the icon in cream on green, the screen in green on cream in the light mode and in cream on green in the dark mode. Replace them with your own before you release the app. [TRADEMARKS.md](https://github.com/saymyframe/smf_flutter_cli/blob/main/TRADEMARKS.md) says what holds for the mark. ## Replace them 1. Put your images in place of those in `assets/branding/`, with the same names. 2. Change the colours if they do not suit your images: `adaptive_icon_background` in `flutter_launcher_icons.yaml` is the colour behind the icon on Android, and `color` and `color_dark` in `flutter_native_splash.yaml`, with the same two under `android_12`, are the colours behind the screen. 3. Run the commands of the modules: ```bash dart tool/update_app_icon.dart dart run flutter_native_splash:create ``` 4. Commit what changed under `android/` and `ios/`. Use the script for the icon rather than `dart run flutter_launcher_icons`. The tool writes the name of the icon into a build setting of the Xcode project that takes `YES` or `NO`, and the script repairs that setting. ## One icon for all flavors All [flavors](https://doc.saymyframe.com/guides/flavors.md) share the icon and the screen. A file for a flavor does not change that: `flutter_launcher_icons-.yaml` turns `flutter_launcher_icons.yaml` off and does not switch the icon of a flavor on iOS, and on iOS the app keeps showing the screen of `flutter_native_splash.yaml` with a `flutter_native_splash-.yaml` too. So one icon for each flavor needs more than those files. ## A module of your own A module can provide either role, or both. See [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#app-icon-and-splash-screen). # CI Source: https://doc.saymyframe.com/guides/ci The CI role says what runs on a server once you push the app: the checks on each push, and on request a release APK for one environment. A module writes that in the format of its host. | Part | Role | Module | What it brings | | --- | --- | --- | --- | | CI | CI | [`github_actions`](https://doc.saymyframe.com/modules/github-actions.md) | `.github/workflows/ci.yml` | ```bash smf create my_app -m github_actions ``` ## What runs On each push to a branch, in a fresh copy of the repository: ```bash [ -f .env ] || cp .env.example .env flutter pub get dart format --output=none --set-exit-if-changed lib test flutter analyze flutter test --dart-define-from-file=.env ``` The first line and the argument of `flutter test` are there only in an app with [the values in `.env`](https://doc.saymyframe.com/guides/env.md). The checks need no setup: `.env` is not in git, so a fresh copy has `.env.example` with every value empty. On your machine the first line keeps your `.env`, so you can run the same commands before a push. On request, for one of the environments `dev`, `staging` and `prod`, the names of the [flavors](https://doc.saymyframe.com/guides/flavors.md) of the app: ```bash dart tool/write_env.dart flutter pub get flutter build apk --release --flavor --dart-define-from-file=.env ``` The APK is `build/app/outputs/flutter-apk/app--release.apk`, and the run keeps it. An app without values in `.env` skips the first line and the argument. The section "Continuous integration" of the README of the app lists the commands of that app. ## Start a build With `github_actions`, open **Actions**, then **CI**, then **Run workflow**, and pick an environment, or run: ```bash gh workflow run ci.yml -f environment=staging ``` `ci.yml` has to be on the default branch of the repository for that. The APK is an artifact of the run, named `app-staging-release`. The job of the checks has 20 minutes and the job of the build 45. A new push cancels the run of an older push of its branch. A build runs to its end, and a second build for the same environment waits for it. ## Values for each environment `.env` has one set of values, and a job writes its own. `tool/write_env.dart`, which the role generates in an app with the values in `.env`, takes the keys from `.env.example` and the value of each from the variable of the process with its name. It prints the keys that it found no value for, and never a value: ```text Wrote .env. No value for: REVENUECAT_APPLE_KEY, REVENUECAT_GOOGLE_KEY, REVENUECAT_TEST_KEY, PAYWALL_PRIVACY_URL. ``` | The script stops, and writes nothing, at | Why | | --- | --- | | A value with a double quote, a control character or a line separator | It fits neither form of a value in `.env`, and could add a line of its own. The script names the key. | | A `.env` that has a value already | It never replaces what a developer filled in. Delete `.env` to write it again. | With `github_actions`, each key is a variable of the GitHub environment of that name. In the repository, open **Settings**, then **Environments**, and create one environment for each of `dev`, `staging` and `prod` that you build. Set the variables under **Environment variables**, or with the GitHub CLI: ```bash gh variable set REST_BASE_URL --env staging --body 'https://staging.example.com/v1' ``` Repeat this for each environment that needs it. A build of an environment without a value for a key gets `null` from the getter of that key in `AppEnv`, and the app still builds. GitHub documents environment variables on a private repository only for its paid plans, though a private repository on the Free plan takes them with this command too. If yours does not, set **Repository variables** instead, which give every build the same values. Every value ends up in the app, where anyone can read it, so these are variables and never secrets of the repository. The workflow passes each value to the script through `env:` of the step, so no value becomes a part of the text of a script. A key of your own needs a line under `env:` of the step that writes `.env`, or the build leaves it empty: ```yaml - name: Write .env from the variables of the environment env: MY_SERVICE_KEY: ${{ vars.MY_SERVICE_KEY }} run: dart tool/write_env.dart ``` ## What has to be in git A job has only what is in git and what `flutter pub get` writes. So commit what the commands of your app wrote: - With Firebase, what `dart tool/configure_firebase.dart` writes. A flavor that is not configured [fails its build](https://doc.saymyframe.com/guides/firebase.md#a-flavor-that-is-not-configured) on Android once another flavor is. - With [`launcher_icons`](https://doc.saymyframe.com/modules/launcher-icons.md) and [`native_splash`](https://doc.saymyframe.com/modules/native-splash.md), the icon and the screen under `android/` and `ios/`. No job makes them. ## The version of Flutter The workflow runs the latest stable Flutter, so a new release can turn CI red with no change in your code: `flutter analyze` fails on a new deprecation, and the format check on a change of the formatter. To stay on the version that you develop with, add `flutter-version` under `channel: stable` in both jobs, with the version that `flutter --version` prints, and change it when you upgrade: ```yaml - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0 with: channel: stable flutter-version: 3.44.2 cache: true ``` Each `uses:` line is pinned to a full commit, with its tag in a comment after it, so the file does not change under you. Nothing updates these pins. To update an action, change the commit and the tag together. A build that fails on a download usually passes when you run it again. ## What stays with you The APK is signed as the Android project of the app signs a release, which is with the debug key in `android/app/build.gradle.kts`. So it is for testers. These are not part of the workflow, and you add them when the app needs them: - A signing key of your own. [Sign the app](https://docs.flutter.dev/deployment/android#sign-the-app) in the documentation of Flutter tells what changes in the Android project. The key is a secret, so it goes into the secrets of the host and never into `.env`. - An upload to a store. - A job for iOS. ## A module of your own A provider of the role writes `ciRole.pipelineIn` into the format of its host. See [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#ci). # Working with a coding agent Source: https://doc.saymyframe.com/guides/coding-agents Every generated app has a guide for the coding agents that work on it, at the root of the app: | File | What it holds | | --- | --- | | `AGENTS.md` | The guide: what the code of the app does not show. | | `CLAUDE.md` | One line, `@AGENTS.md`, which gives the same guide to the agents that read `CLAUDE.md` instead. | The guide is for an agent to read before it changes anything. It tells the rules of this app, so that you do not have to explain them in each session. ## What the guide says The code of an app shows what it does, and an agent can read it. The guide holds what the code does not show: a rule that holds across files, an order, what not to do and what to do instead, a placeholder, a step that needs a person. Setup that needs a person or an account, such as a Firebase project, stays in the `README.md` of the app. The guide starts with a short introduction and has a section for each part of the app that has notes for agents. The section of the app entry comes first, and the others follow in the order of their headings. This is the section "Preferences" of an app with [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md): > - `AppPreferences` in `lib/core/preferences/app_preferences.dart` remembers the settings of the app between its launches, such as the theme mode. It is not encrypted: never save a token, a password, an API key or an encryption key in it. > - To remember a setting, write a function that takes the `AppPreferences` and add it to `_restorers` in that file. In it, read the setting, put it into the state that the widgets listen to, and keep the preferences in that state for its writes. The function awaits nothing, and keeps the current value when nothing is saved. > - Name a key `.`, such as `theme.mode`, where the owner is the feature or the concern whose code keeps the setting. > - In the code of the app, do not call `createAppPreferences()` or `initPreferences()`. `bootstrap()` opens the preferences, and code gets them as the argument of its function in `_restorers`, or, with a DI container in the app, from the container. Widgets use the state and do not touch the preferences. A test may call both: `initPreferences()` opens the preferences again, as the next launch of the app does, and `createAppPreferences()` returns them. > > With `shared_preferences`: > > - In `lib/`, only `lib/core/preferences/shared_app_preferences.dart` imports the package. Other code uses `AppPreferences`. > - A number is read only as the type that it was saved as: `getDouble()` returns `null` for a key with an `int`, and `getInt()` for a key with a `double`. > - In a test that runs `bootstrap()`, first set `SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty()`. Without it, opening the preferences throws. Both names are from the package `shared_preferences_platform_interface`: add it as a dev dependency. > - `pubspec.yaml` keeps `shared_preferences_android` at 2.5.2 or later. With 2.5.0 and 2.5.1, a release build fails to open the preferences on Android, because R8 renames Kotlin classes that the package looks up by name. Before you change the constraint, check that a release build of the app starts on Android. The section of a role has two parts. First comes what holds whichever module provides the role, such as how code remembers a setting. Then the module that provides the role adds what comes with it, here after the line "With `shared_preferences`:". Replace the module with another provider of the role, and only the second part changes. ## The sections of an app A section is in the guide only when the app has what it describes. The table names the built-in module that brings each section: | Section | In an app with | What it tells | | --- | --- | --- | | App entry | every app | The order of `main()`, the phases of `bootstrap()`, where shared code and features go, that `StatusBarIcons` asks for the icons of the status bar around every screen, and what a `flutter` command builds without `--flavor`. In an app with [steps by hand](https://doc.saymyframe.com/guides/smf-create.md#steps-by-hand), also that only you do them: an agent points you to the section "Finish the setup" of the README instead of trying them. `flutter_core` adds where each flavor is in the native projects, and the commands to run after a change, the root widget with the one `MaterialApp` of the app, where the test of a file goes, and where the entitlements of the iOS app are. | | Analytics | [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) | That code records what users do through `AnalyticsService` and never through the SDK of a provider, where it gets the service, and how to add a provider. In an app with a router, the module adds that screen views need no code. | | App icon | [`launcher_icons`](https://doc.saymyframe.com/modules/launcher-icons.md) | Which images the icon comes from, and that an agent changes those and not what is made from them. The module adds the command, and what an agent does not run or add. | | Authentication | [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | That code signs in, up and out only through `appSession`, how it shows a failure, that the mode gates nothing on its own and which guard keeps a user from what, and where the data of a guest moves. It also tells where the ways to sign in with an identity provider are listed, what a tap on one of their buttons does with `appSession.signInWith`, what a deletion asks of them, and what `AccountSession.issuers` lists. The module adds which file is on Firebase Authentication, where a code of Firebase gets its reason, that the ways to sign in are enabled in the Firebase project, and that an agent runs the script that enables them only when asked. In an app with Google sign-in, it adds what its script does for Google, and with Sign in with Apple, that the key of Apple never goes into the app. | | CI | [`github_actions`](https://doc.saymyframe.com/modules/github-actions.md) | That CI runs the commands of the section "Continuous integration" of the README, so an agent keeps them passing and runs them before it finishes a change, and what `tool/write_env.dart` does. The module adds where the jobs are, how a new key reaches a build, how a value reaches a command, and how the actions are pinned. | | Crash reporting | [`firebase_crashlytics`](https://doc.saymyframe.com/modules/firebase-crashlytics.md) | Which function reports the errors that nothing handles, how code reports an error that it catches, and how to add a provider. The module adds that `tool/configure_firebase.dart` keeps the build phase working for `flutter build ipa`, and what to run after `flutterfire configure` by hand. | | Dependency injection | [`get_it`](https://doc.saymyframe.com/modules/get-it.md) | What a service is, where the services are registered, and that only the composition file of a feature resolves them. The module adds how its file registers a service. | | Events | [`event_bus`](https://doc.saymyframe.com/modules/event-bus.md) | What an event is, where code gets the one event service of the app, and what events are for. The module adds when a listener gets an event. | | Firebase | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | That `lib/firebase_options_of_flavor.dart` picks the options by the flavor of the build, that the options of a flavor are a placeholder until `tool/configure_firebase.dart` writes them, that an agent runs that script only when asked and never `flutterfire configure`, and what a test that starts the app needs. | | Google sign-in | [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) | Which file asks Google and how it starts the package, which errors become which reason, what the icon shows, and what a test replaces to sign in with Google. | | Home | [`home`](https://doc.saymyframe.com/modules/home.md) | What the start screen is for, and where the image that it shows is declared. | | Layout | [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md) | Who creates the shell of the main navigation, what a destination is, how its label follows the language, how to add one, and how code reaches a destination from a page shown over the main navigation. The module adds that it draws its bar itself, when the bar is hidden, how many destinations it should have, where the bar takes its colors from, and what a tab says to a screen reader. | | Localization | [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) | How code reads a text, where the languages of the app are, how code changes the language, and what a new language needs. The module adds where the texts are, how to add one, and the command to run after a change. | | Notifications | [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) | How code shows and schedules a notification and which ids it takes, how it asks for the permission and where the app asks, how it handles a tap, and the small icon of Android. The module adds which file is on flutter_local_notifications, how to add a channel, why a scheduled notification is inexact, and what its native files and a test need. | | Onboarding | [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) | That no code navigates to the onboarding or away from it, where its pages and its steps are and what the screen keeps around them, that the animations of a page end, how code finishes the onboarding and starts it again, and what a test of another screen does first. | | Onboarding screen | [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) | What a step of the onboarding is, how to add one, how a step that shows a screen of its own pushes it over the onboarding, and that skipping the onboarding skips its steps. | | Paywall | [`paywall`](https://doc.saymyframe.com/modules/paywall.md) | Where the paywall and the screen of the subscription are and which guard shows them, that no screen closes itself or navigates after a purchase or a restore, how to sell from a button and keep a screen for users with premium access, which files are the look and which the state, where the plans get their words and a failure its text, what the links need in `.env`, whose a purchase before a sign-in is, and what a widget test minds while a call is on its way. By the state manager of the app, it adds where the state of a screen is and how a widget reads the access, and in an app with an onboarding, how its step shows the paywall and who closes it. | | Preferences | [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md) | What the preferences are for, what never goes into them, and how code remembers a setting. The module adds how it reads numbers, what a test that runs `bootstrap()` needs, and why `pubspec.yaml` keeps `shared_preferences_android` at 2.5.2 or later. | | Purchases | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | What the access of the user is and where a widget reads it, how code gets the plans, buys, restores and shows a failure, what a screen that sells shows, how a screen is kept for users with premium access, what the app does while purchases are not set up, and which functions are not for the code of the app. In an app with sign-in, also whose the purchases are, and in an app with a settings screen, where the restore is. The module adds which file is on purchases_flutter, that the premium access is the entitlement `premium`, which API key a build takes and why, that nothing calls RevenueCat before it is configured, how a grant made on the dashboard reaches the app, and what a test answers in place of the package. | | REST API | [`dio`](https://doc.saymyframe.com/modules/dio.md) | How code makes a request through `appRest` and turns the body into a type, how it shows a failure, what repeats, how a call ends, and what a test needs. In an app with sign-in, which requests carry the token and what a 401 does. The module adds where an interceptor goes and what it may do. | | Push messages | [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) | Where the address of the device is and what to do with it, how a message shows in the foreground, how code handles a tap, and what the app does not handle. The module adds which file is on firebase_messaging, where the address comes from, why it sets the presentation options of iOS, and that the app never asks for the permission through the package. | | Router | [`go_router`](https://doc.saymyframe.com/modules/go-router.md) | How code navigates with `context.nav`, the three places that a route is in, and the types of its values. In an app with [guards](https://doc.saymyframe.com/guides/navigation.md#guards), also where the guards are, what tells a gate from a guard for some routes, how code adds either, and that a screen neither closes itself nor navigates after it changed a guard. The module adds how its file writes a route and, in an app with a layout, where a destination of the main navigation goes and that the router creates the main navigation anew. | | Settings screen | [`settings`](https://doc.saymyframe.com/modules/settings.md) | What an entry of the screen is and how to add one. The module adds where its screen is, what it shows with entries and without, and how code opens it in an app without a main navigation. | | Sign in with Apple | [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) | Which file asks Apple and what it returns, that Apple gives the name only at the first sign-in, which errors become which reason, the entitlement, and what a test sets to sign in with Apple. | | Sign-in | [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) | Where the screens of the sign-in are and which guards show them, that a screen neither closes itself nor navigates after a sign-in or a sign-out, which files are the look and which the state, where a failure gets its text, what a widget test minds while a call is on its way, where the buttons of the ways to sign in come from, and where the screen of the account and its entry are. By the state manager of the app, it adds where the state of a screen is and how a widget reads who uses the app. | | Splash screen | [`native_splash`](https://doc.saymyframe.com/modules/native-splash.md) | Which images the screen comes from, and that an agent changes those and not what is made from them. The module adds the command and what it rewrites. | | State management | [`bloc`](https://doc.saymyframe.com/modules/bloc.md) or [`riverpod`](https://doc.saymyframe.com/modules/riverpod.md) | How a screen with state is written with the state manager of the app: where its state is, how the screen passes it on to a view, where state that several screens read goes, what the state checks after a call that it awaited, and that a widget talks only to that state, never to a service or a DI container. | | Theme | [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md) | Where the look of the app is, how code changes and reads the theme mode, and where a screen takes its colors from. The module adds how its file creates both themes, where their colors and their font are, where a text field takes its look from, and what a change of the file must keep. | | Values in .env | [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) | How code reads a value of `.env` through `AppEnv` and handles `null`, that no secret goes into `.env`, and what a new key needs. The module adds the commands with `--dart-define-from-file=.env`, the run configurations that pass it, that `flutter run` starts again after an edit of `.env`, and how the getter of a new key reads its value. | ## Where the sections come from The app entry role generates both files in every app, whichever module provides the role. The roles and the modules of the app contribute the sections, as they contribute start-up code: a module knows nothing of the notes of the other modules, and `smf create` puts the sections together. So the guide of an app covers only what that app has. SMF checks the paths that a guide names. In its tests, each file or directory that a note names in backticks below a top-level directory of a Flutter project, such as `lib/` or `android/`, and each path to a Dart file, must be in the app of that guide. A module author reads more in [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). ## Keep it true The guide is a file of your app, like the rest of the code. Nothing writes it again, so it is right only as long as you keep it so, and its first paragraph asks the agent to do its part: "When you change what a section describes, change the section too." - When you change how a part of the app works, such as where its files are or which function code must call, change the section of that part. - When you add a part of your own with a rule that the code does not show, add a section for it under a heading of its own. - Keep to what the code does not show. A note that repeats the code makes the other notes harder to find. ## The documentation for your agent Every page of this documentation is also in Markdown, at its URL with `.md`, such as https://doc.saymyframe.com/guides/theme.md. [llms.txt](https://doc.saymyframe.com/llms.txt) lists the pages with a line about each, and [llms-full.txt](https://doc.saymyframe.com/llms-full.txt) has all of them in one file. An agent may know SMF from an older version, or not at all. Give it one of these before it picks the modules of an app or writes the command of `smf create`. # Firebase Source: https://doc.saymyframe.com/guides/firebase Five modules bring Firebase into an app: | Module | What it adds | | --- | --- | | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | Firebase itself: `firebase_core`, the options of the Firebase app, and its initialization at start-up. | | [`firebase_crashlytics`](https://doc.saymyframe.com/modules/firebase-crashlytics.md) | Crash reporting with Firebase Crashlytics. | | [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) | Analytics with Firebase Analytics, including screen views. | | [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | Sign-in with Firebase Authentication: an email address and a password, an anonymous user, and the ways to sign in of Google and Apple. The feature [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), the screens of sign-in, brings it. | | [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) | Push messages with Firebase Cloud Messaging: the address of the device for the backend of the app, the messages and the taps on them. | The last four depend on `firebase_core`, which `smf create` adds with them. Some of the setup is out of reach of any command, in the Firebase console and in your Apple Developer account: Google Analytics in the project, the APNs key of Cloud Messaging, Apple in Firebase Authentication, and the SHA of the keys of a release for Google. These are steps by hand. The README of the app lists them under "Finish the setup", and `smf create` ends with a link to [their guides](https://doc.saymyframe.com/setup.md), which show each one click by click. They repeat for each Firebase project that your [flavors](https://doc.saymyframe.com/guides/flavors.md) use; see [what repeats](#what-repeats-for-each-project). ## What SMF generates `firebase_core` gives the app a file of options for each [flavor](https://doc.saymyframe.com/guides/flavors.md), `lib/firebase_options_dev.dart`, `lib/firebase_options_staging.dart` and `lib/firebase_options_prod.dart`. `firebaseOptionsOfFlavor` in `lib/firebase_options_of_flavor.dart` picks the options by the flavor of the build, and `bootstrap()` initializes Firebase with them before the other services: ```dart await Firebase.initializeApp(options: firebaseOptionsOfFlavor); ``` `appFlavor` is a constant, so a release build keeps only the options of its own flavor. The options come from your Firebase project, where the [FlutterFire CLI](https://pub.dev/packages/flutterfire_cli) registers the apps. Until a flavor is configured, its file is a placeholder in the form that flutterfire writes, so the app compiles but a build of that flavor stops at start-up with an `UnsupportedError` that gives the command. The module also adds the script `tool/configure_firebase.dart`, which configures one flavor, and asks for iOS 15.0 or newer, which the Firebase SDKs need and the app has already. It adds a Firebase section to the README of the app with the commands below. ## Before generation: the machine The FlutterFire CLI needs a few tools, so SMF checks the machine before it generates an app with Firebase: | Check | What it looks for | | --- | --- | | Firebase CLI | The [`firebase` command](https://firebase.google.com/docs/cli), which the FlutterFire CLI runs to reach your Firebase projects. SMF runs `firebase --version` to see that it works. | | Firebase login | An account logged in to the Firebase CLI, as `firebase login:list --json` reports it. SMF then lists your Firebase projects with `firebase projects:list --debug` to see that Google still accepts the login. | | FlutterFire CLI | flutterfire_cli 1.4.1 or a later 1.x, activated globally, as `dart pub global activate flutterfire_cli 1.4.1` does. | | Xcode project tools | On macOS, Ruby with the gem xcodeproj 1.23.0 or newer, with which the FlutterFire CLI sets up the iOS app in its Xcode project. | | Setup of the Xcode project on a Mac | On other systems, a warning: the FlutterFire CLI changes the Xcode project only on macOS. | | Firebase CLI 15.34.0 or later | For an app with `firebase_auth`: the first Firebase CLI that enables sign-in methods without adding a web app to a project that has the apps of `flutterfire configure`, which SMF reads from `firebase --version`. SMF does not update the Firebase CLI. For an older one, it tells which command it found, in which version, and how to update it. | The app compiles without any of them, so none of them stops the run. A missing one is a warning with instructions, and `smf create --explain` shows the state of each. In a terminal, unless the run has `--skip-external-setup`, SMF offers to fix what it can, and asks before each step. Each question says what the check found and how to fix it by hand, then asks whether to set it up now. It can install the Firebase CLI with npm, also when a `firebase` command is on the `PATH` but does not run, such as one that needs another Node.js. The question then says how `firebase --version` ended. When Node.js is missing or older than 20, it installs Node.js first: on macOS with nvm when the Node.js on the `PATH` is one of nvm, or else with Homebrew or nvm, with nvm on Linux, and with winget, Chocolatey, Scoop or the portable ZIP of Node.js on Windows. The installation can take minutes, and its progress shows what it is doing. When the directory of the Firebase CLI is not on the `PATH` of new terminals, the installation adds it to the profile of the shell or, on Windows, to the `PATH` of the user. On Linux it also moves the global directory of npm to `~/.npm-global`, so that it needs no sudo, and adds a `firebase` command to `~/.local/bin` that runs the Firebase CLI with the Node.js that installed it, whatever Node.js a terminal has, such as another default version of nvm. On macOS, it adds that command, and `~/.local/bin` to the `PATH` of new terminals, when it installs the Firebase CLI with a Node.js of nvm. SMF lists these changes afterwards. When npm fails on macOS or Linux, SMF offers the standalone binary of the Firebase CLI instead, `curl -sL https://firebase.tools | bash`, which may ask for your password to write to `/usr/local/bin`. It can log you in with `firebase login`, which asks its own questions in the terminal. `firebase login` waits for the browser to come back to a server on the machine, which a browser on another machine cannot reach. So when `SSH_CONNECTION`, `SSH_CLIENT` or `SSH_TTY` has a value, as in a session over SSH, SMF runs `firebase login --no-localhost` instead. That command gives a link to open on any device and asks for the authorization code shown there. On a remote machine where none of them has a value, log in yourself with `firebase login --no-localhost`. A login of the Firebase CLI can expire or be revoked. `firebase login:list` still lists such an account, but the Firebase CLI can no longer reach your projects, so flutterfire finds no project and offers to create one. That is why SMF checks the login with `firebase projects:list --debug`, which only reads. The Firebase CLI reports the same error whether Google rejects the login or cannot be reached at all, and only its debug output tells the two apart. If Google rejects the login, SMF says that it has expired or is no longer valid and offers to log you in again with `firebase login --reauth`, or with `firebase login --reauth --no-localhost` over SSH. Plain `firebase login` would only say that you are logged in already. If the command cannot reach Google, as on a machine without a network, SMF says that it could not check the login and why, and leaves the configuration for later. The check needs the network and usually takes a few seconds; SMF shows the progress "Checking the machine" while the checks run. On a network that drops requests without answering, SMF gives up on the listing after 40 seconds and says that it could not check the login. Ctrl-C stops the check, along with the whole run. It can activate flutterfire_cli 1.4.1 when no version is active or an older one is. The question names the version that is active and says that 1.4.1 takes its place: ```text FlutterFire CLI 1.4.1 or a later 1.x is needed by firebase_core, but flutterfire_cli 1.4.0 is active. Activate 1.4.1 in its place with "dart pub global activate flutterfire_cli 1.4.1". Set it up now? ``` SMF never replaces a newer major version, which other apps may need, and only tells you how to activate 1.4.1 in that case. SMF cannot install the gem xcodeproj for you. Install it with `gem install xcodeproj`, with a Ruby version manager or, for the Ruby of macOS, with sudo. :::note On Windows, SMF installs with a PowerShell script. CI runs it on Windows with the Node.js of the machine, but the installation of Node.js by the script, with winget, Chocolatey, Scoop or the portable ZIP, has not run on Windows yet. ::: ## After generation: configure `dev` Once the app has its packages, SMF shows the command below and asks whether to run it now. It runs the command in the app with the terminal attached, so the FlutterFire CLI can ask you for the Firebase project: ```bash dart tool/configure_firebase.dart dev ``` The script configures one flavor, here the one that a `flutter` command builds without `--flavor`. It runs `flutterfire configure` with the ids of that flavor. On macOS it runs it three times, once for each Xcode build configuration of the flavor, since flutterfire writes one build configuration in a run. Elsewhere it runs it once. flutterfire registers the Android and iOS apps of the flavor in the project and writes: - `lib/firebase_options_dev.dart`; - `android/app/src/dev/google-services.json`; - `firebase.json`; - on macOS, `ios/flavors/dev/GoogleService-Info.plist` and the changes to the Xcode project. The script then formats the options and runs [what follows each configuration](#what-follows-each-configuration). SMF prints the command for later instead of running it in these cases: - The run has no terminal or has `--no-input`, and the FlutterFire CLI needs you to choose a project. - The run has `--skip-external-setup`. - A check that the command needs did not pass: the Firebase CLI, the login, the FlutterFire CLI or, on macOS, the gem xcodeproj. The command would fail, so SMF does not ask about it. SMF names these checks with the command, also when the run has no terminal or skips external setup, so you know what to set up before you run the command. - You answer no, or the command fails. A command that you or the options of the run left for later is listed after the line that the app is created. A command that failed, or that only a check kept from running, is a warning. [The machine and external setup](https://doc.saymyframe.com/guides/smf-create.md#the-machine-and-external-setup) shows both. The app is complete either way. Run the command in its directory when you are ready. In an app with `firebase_auth`, a second question follows once the script configured the flavor: whether to [enable the sign-in methods](#sign-in-methods-of-firebase-authentication) in the project that you chose. ## One project for each flavor Each flavor may have a Firebase project of its own, or share one with another flavor. `smf create` only configures `dev`. Configure the others when you need them, with one command for each flavor: ```bash dart tool/configure_firebase.dart staging --project=my-app-staging dart tool/configure_firebase.dart prod --project=my-app ``` | Part of the command | What it does | | --- | --- | | The flavor | Required. The script stops without one, or with a name that is no flavor of the app. | | `--project=` | The Firebase project. In a terminal you may leave it out, and flutterfire asks. Without a terminal, the script stops without it. | | Other arguments | They go to flutterfire as they are, such as `--account=`. | Commit what the script writes: the options, `android/app/src//google-services.json`, `firebase.json` and `ios/flavors//GoogleService-Info.plist`. A build from a clone of the repository, such as one of [CI](https://doc.saymyframe.com/guides/ci.md), uses them. Run the script again at any time. It changes nothing but the ids of the build phases that flutterfire added, or moves the flavor to another project. The ids of each flavor are at the top of the script, so if you change them in the Android and Xcode projects, change them there too. Use this script rather than `flutterfire configure`. That command writes one configuration that every flavor then shares: `ios/Runner/GoogleService-Info.plist` goes into the resources of every flavor, and `android/app/google-services.json` is what the Google services plugin takes for any variant without a file of its own. ### What repeats for each project A Firebase project knows each flavor as an app of its own, and what you set in one project is not in another. So the same has to be done for the other environments, if they need it. SMF does not hide this, because Firebase works this way with or without SMF. A flavor that shares a project with another needs only what goes with its own app. | What | How often | How | | --- | --- | --- | | The apps and the options | Each flavor | `dart tool/configure_firebase.dart --project=` | | The [sign-in methods](#sign-in-methods-of-firebase-authentication) | Each project | `dart tool/enable_firebase_sign_in.dart --project ` | | What Google sign-in needs | Each project, and each machine that builds for debugging | The same script, for the apps that `firebase.json` names in that project | | [Google Analytics](https://doc.saymyframe.com/setup/firebase-analytics-google-analytics.md) | Each project | By hand | | [The APNs key](https://doc.saymyframe.com/setup/firebase-messaging-apns-key.md) | Each Apple app that you send to. One key serves every app of its team. | By hand | | [Apple as a sign-in method](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md), with [its key and Services ID](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md) | Each project | By hand | | [The SHA of the release keys](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md) | Each Android app that such a key signs | By hand, or with the Firebase CLI | | [The App ID](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md) | Each bundle id that you sign | By hand | ### A flavor that is not configured | Where | What happens | | --- | --- | | No flavor is configured | Every build passes, and the app stops at start-up with an `UnsupportedError` that gives the command. | | Android, once another flavor is configured | The build of a flavor that is not fails with `File google-services.json is missing`. | | iOS without Crashlytics | It builds and stops at start-up with that `UnsupportedError`, unless a build phase that flutterfire adds for another Firebase package fails the build first. | | iOS with Crashlytics, on macOS, once another flavor is configured | The build fails in the phase of Crashlytics with `FirebaseJsonException: Please run "flutterfire configure"`. | In each case, what it takes is `dart tool/configure_firebase.dart --project=`. In Xcode, select the scheme of a flavor. It builds that flavor. The scheme `Runner` takes the flavor from `ios/Flutter/Generated.xcconfig`, which has none after a fresh `flutter pub get`, so `appFlavor` is `null` there and `firebaseOptionsOfFlavor` throws an `UnsupportedError`. `flutter build ios --config-only --flavor ` gives that file a flavor. ### What follows each configuration After its last run of flutterfire, the script runs `dart format` on the options, which only warns when it fails, and then each Dart file of `tool/firebase_configured/`, in the order of their names. A module that depends on `firebase_core` puts a file there for what has to follow each run of flutterfire, as `firebase_crashlytics` does below. An app whose modules have nothing to run there has no such directory. You can add a file of your own too. ## Crashlytics and `flutter build ipa` For an app with Crashlytics, the FlutterFire CLI adds a build phase to the Xcode project on macOS that uploads the debug symbols with the upload script of Crashlytics. Flutter keeps the Swift packages of the app, and the script with them, in `build/ios/SourcePackages`. The phase of flutterfire_cli 1.4.1 looks for the script in the build directory of Xcode, which `flutter run` and `flutter build ios` set to `build/ios`, but `flutter build ipa` does not, so the archive would fail in that phase. flutterfire writes the phase again each time it runs, so `firebase_crashlytics` adds `tool/firebase_configured/fix_crashlytics_phase.dart`, and `tool/configure_firebase.dart` runs it after each flavor. On macOS it points the phase at `build/ios/SourcePackages`, changes nothing else in `ios/Runner.xcodeproj/project.pbxproj`, and leaves a project that it fixed already as it is. Elsewhere it does nothing. After running `flutterfire configure` yourself on macOS, run it too: ```bash dart tool/firebase_configured/fix_crashlytics_phase.dart ``` The phase looks up the build configuration in `firebase.json`, so a build of a [flavor that is not configured](#a-flavor-that-is-not-configured) fails there. ## Google Analytics [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) records its events in Google Analytics, which a Firebase project that `flutterfire configure` creates does not have. Until Google Analytics is on in the project, the app logs its events, but they show up nowhere. Turning it on is a step by hand of every app with the module, once in each Firebase project of your flavors, and the [click-by-click guide](https://doc.saymyframe.com/setup/firebase-analytics-google-analytics.md) shows each screen. A project that has Google Analytics already needs nothing. ## Sign-in methods of Firebase Authentication An app with [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) needs one more thing than the configuration: the ways to sign in are enabled in the Firebase project, not in the code. That is Email/Password in every mode of the app, Anonymous when the [mode](https://doc.saymyframe.com/guides/sign-in.md#the-mode) of the app is `anonymous`, and Google and Apple for the [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in) of an app with [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) or [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md). Until they are enabled, signing in and signing up fail with the reason `notConfigured`, and the `developerHint` of the failure tells how to enable them. In the mode `anonymous`, the app also starts without a user. The module generates a script of the app that enables them, `tool/enable_firebase_sign_in.dart`. Right after `dart tool/configure_firebase.dart dev` configured the app, `smf create` asks whether to run it: ```text Enabling the sign-in methods of the app in its Firebase project (dart tool/enable_firebase_sign_in.dart), for firebase_auth. If the app signs in with Google, it also gives Google the app's name and the Firebase CLI account's email for its consent screen, registers the SHA-1 and SHA-256 of this machine's Android debug key (creating the key if there is none, as the first debug build would), downloads the app's Firebase files again and writes the iOS URL scheme into ios/Runner/Info.plist. Run it now? ``` A step cannot tell which ways to sign in the app has, so `smf create` asks the same question in every app with `firebase_auth`, also in one without Google. SMF prints the command for later instead of asking in these cases: - `tool/configure_firebase.dart` did not run, or failed, or you left it for later. The script waits with it. - The run has no terminal, has `--no-input` or has `--skip-external-setup`. - The Firebase CLI of the machine is missing or older than 15.34.0. To enable the methods later, or after you changed the mode of the app to `anonymous`, run the script in the directory of the app: ```bash dart tool/enable_firebase_sign_in.dart ``` Each project needs the methods enabled, and a run covers one project. So once `firebase.json` has several, the script stops and lists them. Run it once for each: ```bash dart tool/enable_firebase_sign_in.dart --project my-app-staging dart tool/enable_firebase_sign_in.dart --project my-app ``` | What the script does | | | --- | --- | | The project | It reads the id of the project from `firebase.json`, where `tool/configure_firebase.dart` wrote it, and says which project it enables the methods for. `--project ` names another. It stops when `firebase.json` has no project or several, unless you name one. | | The mode | It reads the mode from `authMode` in `lib/core/auth/app_session.dart`, and enables Anonymous only in the mode `anonymous`. It stops when that file does not tell the mode. | | The methods | It enables them with `firebase deploy --only auth` of the Firebase CLI, which enables what its configuration names. It never disables a method. | | The files of the app | It runs the Firebase CLI in a temporary directory, with a configuration of its own there, and removes the directory. `firebase.json` of the app stays as it is, so a `firebase deploy` of the app does not touch the sign-in methods. It changes no file of the app but those that Google needs, as below. | | The account | In that temporary directory, an account that `firebase login:use` chose for the directory of the app does not apply. `--account ` names the account. | | Other arguments | They go to the Firebase CLI as they are, such as `--debug`. | | Ctrl+C | The script lets the Firebase CLI end, removes the temporary directory and exits with the code 130. | The Firebase CLI enables the methods through an app of the project. Before 15.34.0 that had to be a web app, and the Firebase CLI added one, named "Default Web App", to a project without one. 15.34.0 takes an app of any platform, and adds a web app only to a project without any app. The script runs after `tool/configure_firebase.dart`, which registers the Android and iOS apps, so the project has an app by then. The script asks the Firebase CLI for its version first, and stops with what to do when it is missing or older. You can also enable the methods in the Firebase console: open [Authentication > Sign-in method](https://console.firebase.google.com/project/_/authentication/providers) of each project that a flavor is configured for, and enable Email/Password, Anonymous for the mode `anonymous`, and Google and Apple for the ways to sign in of the app. ### Google For a way to sign in of Google, the script does more than enable it: - It gives Google the name of the app and the email address of the account of the Firebase CLI for the consent screen that users see when they sign in. The address is the support email there: the one that `--account` names, or else the one that the Firebase CLI is logged in as. When the Firebase CLI runs as no user account, as with a service account, the script leaves Google out and says so. Run it with `--account ` then, or enable Google in the Firebase console. - It registers the SHA-1 and SHA-256 of the Android debug key of the machine that runs it for each of those Android apps, which Google uses to recognize the Android app, with `firebase apps:android:sha:create`, and only the hashes that the project does not list yet. When the machine has no debug key yet, the script creates it where the Android Gradle plugin keeps it, as the first debug build would. Every machine has a debug key of its own, so run the script on each machine that builds the app for debugging, or add the SHA of its key in the Firebase console, in the settings of the Android app. - It downloads the Firebase files of those apps again, such as `android/app/src/dev/google-services.json` and `ios/flavors/dev/GoogleService-Info.plist`, once they have the clients of Google, and writes them to the paths that `firebase.json` names. - It writes the URL scheme of each of those iOS apps, `REVERSED_CLIENT_ID` of its `GoogleService-Info.plist`, into `CFBundleURLTypes` of `ios/Runner/Info.plist`. The flavors share that file, so it lists a scheme for each iOS app that the script ran for, in the build of every flavor. It adds a scheme and removes none: after a flavor moves to another project, remove the scheme of the former project there by hand. The script sets up the debug key, the files and the URL scheme only for the apps that `firebase.json` names in the project of the run, and a project that no flavor is configured for gets none of it. So after you configure a flavor for another project, run the script for that project too. A step that fails after the methods are enabled ends the script with the code 1, and what it did before stays done. A release of the Android app is signed with another key, whose SHA-1 and SHA-256 Google needs too: those of the upload key, and of the app signing key of Google Play, under Test and release > App integrity in the Play Console. Add each with the Firebase CLI, for the Android app of each flavor that such a key signs, with the id of that app and of its project from `firebase.json`: ```bash firebase apps:android:sha:create --project= ``` This is a step by hand of the app, and the [click-by-click guide](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md) shows where the Play Console has both keys and where the Firebase console takes them. ### Apple No command of the Firebase CLI enables Apple, so in an app with Sign in with Apple the script tells what to set in the Firebase console: add Apple under [Authentication > Sign-in method](https://console.firebase.google.com/project/_/authentication/providers). Deleting an account that signs in with Apple revokes the tokens that Apple gave the app, as the App Store asks of an app with Sign in with Apple (App Store Review Guideline 5.1.1(v)). Firebase does that with the Services ID and the OAuth code flow configuration, which you enter in the settings of the Apple provider there: your Apple team ID, and the Key ID and the private key of a key for Sign in with Apple. The private key is a secret: enter it in the console yourself, and never put it into the app or its repository. Until they are set, deleting an account that signs in with Apple fails with `notConfigured`, and the account stays. Both are steps by hand of the app, and the click-by-click guides of [the provider](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md) and of [the key and the Services ID](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md) show each screen, from the key and the Services ID in your Apple Developer account to the settings of the Apple provider. The ways to sign in are a setting of the project. A project that you configure the app for later needs them enabled too. Firebase sends the message with which a user sets a new password from a template of the project, under [Authentication > Templates](https://console.firebase.google.com/project/_/authentication/emails). In an app with [languages](https://doc.saymyframe.com/guides/languages.md), the app asks Firebase for the message in the language that it is in. ## Cloud Messaging An app with [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) receives push messages through Firebase Cloud Messaging. Firebase sends messages to iOS through the Apple Push Notification service (APNs), with an APNs key of your team. You upload the key by hand: 1. In your Apple Developer account, under Certificates, Identifiers & Profiles, create a key under Keys with the Apple Push Notifications service (APNs) enabled. Download its `.p8` file, and note its Key ID and your Team ID. 2. In the Firebase console, open the settings of the project, then Cloud Messaging, and upload the key under the configuration of the Apple app, with its Key ID and your Team ID. The Firebase console has this configuration under each Apple app of the project, so check it for the iOS app of each flavor that you send to, and repeat the upload where it has no key. One key serves every app of its team, so the file and the ids stay the same. A key sends only to the apps of its team, so register the bundle id of each flavor that you send to as an App ID in that team, with Push Notifications. The section "Flavors" of the README of the app lists the bundle ids. The key matters only for sending: the iOS app gets its address without it, but Firebase cannot send to that address. The iOS app is also signed with the entitlement `aps-environment`, which the push role adds, and a free personal team cannot sign it; see [Push messages](https://doc.saymyframe.com/guides/notifications.md#push-messages). The upload of the key and the App ID are steps by hand of the app, and the click-by-click guides of [the key](https://doc.saymyframe.com/setup/firebase-messaging-apns-key.md) and of [the App ID](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md) show each screen. ### A test message To send a device a test message, run the app in debug mode and copy the address that it prints: ```text The address of this device for push messages: ``` In the Firebase console, open Messaging, create a notification campaign, choose Send test message and paste the address. A server sends a message with the HTTP v1 API of Firebase Cloud Messaging: `POST https://fcm.googleapis.com/v1/projects//messages:send`, with an OAuth token of a service account of the project of the flavor and the address as the `token` of the message: ```json { "message": { "token": "", "notification": {"title": "Hello", "body": "A message from the backend"}, "data": {"screen": "tasks"} } } ``` A message with a notification shows on the device once the user has allowed the notifications of the app, and its `data` reaches the app as the `data` of a `PushMessage`; see [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md#push-messages). ## Configure again, or on another machine To configure a flavor for another Firebase project, or to set it up on another machine, run in the directory of the app: ```bash dart pub global activate flutterfire_cli 1.4.1 firebase login dart tool/configure_firebase.dart staging --project= ``` Skip the activation if `dart pub global list` shows flutterfire_cli 1.4.1 or a later 1.x already. If `firebase login` says that you are logged in already but flutterfire finds no Firebase project, your login has probably expired. Run `firebase login --reauth`. With `firebase_auth`, then run `dart tool/enable_firebase_sign_in.dart --project ` for the new project. The script changes the Xcode project only on macOS, and the build phases that flutterfire adds there, such as the upload of the debug symbols of Crashlytics, run `flutterfire` from `~/.pub-cache/bin`. So every Mac that builds the app for iOS needs the FlutterFire CLI activated globally. ## An app configured with flutterfire_cli 1.4.0 The phase for Crashlytics that flutterfire_cli 1.4.0 adds does not find the upload script where Flutter puts the Swift packages, so `flutter run` and `flutter build ios` fail in that phase, even after you activate 1.4.1. Activate 1.4.1 and run `tool/configure_firebase.dart` again on a Mac for each configured flavor, and the new phase replaces the old one. ## Linux and Windows On a system other than macOS, `tool/configure_firebase.dart` runs flutterfire once, which registers the iOS app and writes its options, but writes no `GoogleService-Info.plist` and leaves the Xcode project as it is, without the build phases it adds for some Firebase packages. The script says so when it ends. Run it again for that flavor on a Mac before building the iOS app there. SMF warns about this before it generates the app. ## In CI A run without a terminal cannot choose a Firebase project, so in CI `smf create` generates the app with the placeholder options and prints the command for later, and after it the command that enables the sign-in methods of an app with `firebase_auth`. Such a run installs nothing either. Add `--skip-external-setup` anyway, as the command in [scripts and CI](https://doc.saymyframe.com/guides/smf-create.md#in-scripts-and-ci) does. It also holds back the steps of other modules that need an external service but ask nothing, which a run without a terminal would otherwise start. `tool/configure_firebase.dart` itself works without a terminal once it has `--project`. [The CI of an app](https://doc.saymyframe.com/guides/ci.md) needs no flutterfire on Android: it builds from the files that you committed. # Troubleshooting Source: https://doc.saymyframe.com/guides/troubleshooting ## Installing and running `smf` ### `smf: command not found` `dart pub global activate` installs `smf` in the directory of globally activated Dart packages, `~/.pub-cache/bin` on macOS and Linux, which may not be on your `PATH`. Add it as the [Dart documentation](https://dart.dev/tools/pub/cmd/pub-global#running-a-script-from-your-path) describes, and open a new terminal. ### The Flutter SDK is missing or too old `smf create` checks the Flutter SDK before it generates anything. It uses the `flutter` on the `PATH` and the `dart` of the same SDK. If there is no `flutter` there, [install Flutter](https://docs.flutter.dev/get-started/install) and add its `bin` directory to the `PATH`. The apps need Flutter 3.44 or newer and Dart 3.12 or newer. `flutter_core` sets these constraints, and every app needs it for the app entry, so with an older SDK `smf create` stops before it generates anything and names both versions: ```text Generation stopped because of 2 errors. error [flutter_core]: flutter_core needs Dart ^3.12.0, but the Flutter SDK at /path/to/flutter/bin/flutter has Dart 3.10.1. (Upgrade Flutter.) error [flutter_core]: flutter_core needs Flutter >=3.44.0, but the Flutter SDK at /path/to/flutter/bin/flutter has Flutter 3.41.0. (Upgrade Flutter.) ``` Upgrade Flutter, or put a newer Flutter SDK first on the `PATH`. ## Errors of `smf create` The [exit code](https://doc.saymyframe.com/guides/smf-create.md#exit-codes) tells what kind of problem it was. | Code | What to do | | --- | --- | | 64 | The command line was wrong or incomplete. The message says what to change, and `smf create --help` lists the options. A run without a terminal also stops with 64 when it would have to ask, such as for the app name, for what to do with an existing directory (`--on-conflict`), or for which of several modules provides a role. | | 1 | Generation failed, and the messages say why. If the app was generated already, it stays in a temporary directory that the message names, so you can look at it. | | 70 | An unexpected error, which is a bug of `smf` or of a module. Run the same command again with `--verbose` for the full log, and please [report it](https://github.com/saymyframe/smf_flutter_cli/issues). | ### "Leaving out …" By default, `smf create` leaves out a module that cannot work in the app, with a warning that says why, and generates the rest. Add `--strict` to stop instead. A module that every app needs, such as `flutter_core`, is never left out: its problem stops the run. See [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). ### "Generation stopped because of a warning about the app" With `--strict`, a warning about what the app is made of stops the run too, such as `router.no_start` for an app whose routes mark none as a start screen. The message names the code of each warning, and the role that reported it. Fix what the warning names, such as `--start` for the start screen, or run without `--strict` to generate the app as it is. ### The app's directory already exists In a terminal, `smf create` asks what to do. Without one, choose with `--on-conflict`: `replace`, `copy` to create the app next to it, or `cancel`. ## Building the app ### A release build has the id and the name of `dev` A `flutter` command without `--flavor` builds `dev`, in release mode too. A build for a store names the flavor, as in `flutter build appbundle --flavor prod`. See [Flavors](https://doc.saymyframe.com/guides/flavors.md#run-and-build-a-flavor). ### The APK or the app bundle is not where a script expects it The name of the flavor is part of the path: `build/app/outputs/flutter-apk/app-dev-release.apk` and `build/app/outputs/bundle/devRelease/app-dev-release.aab`, also for a build without `--flavor`. ### iOS builds with Xcode 27 Xcode 27 builds only for iOS 15 and newer, which Flutter follows from version 3.47. With Flutter 3.44 and Xcode 27: - `flutter build ios --simulator` fails in `debug_unpack_ios`: Flutter passes both architectures of the simulator to `lipo -verify_arch`, which takes one in Xcode 27. Build for the architecture of your Mac: ```bash FLUTTER_XCODE_ARCHS=arm64 flutter build ios --simulator ``` - A plugin that installs with CocoaPods and asks for iOS 13 or 14 keeps that version, which Xcode 27 refuses. Flutter 3.47 raises it to the version of the app. So for iOS builds with Xcode 27, use Flutter 3.47 or newer. The apps of SMF set the minimum iOS version to 15.0. ### Xcode cannot sign the app for an iPhone with a free personal team The iOS app signs with `ios/Runner/Runner.entitlements`. Push messages add the entitlement `aps-environment` there, and Sign in with Apple adds `com.apple.developer.applesignin`. Signing with either needs a team of the paid Apple Developer Program. The simulator signs the app without one. Signing the app once with such a team is a step by hand of the app, and the [click-by-click guide](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md) shows each screen. To run the app on an iPhone with a free personal team, remove the key from `ios/Runner/Runner.entitlements`. Without `aps-environment` the app runs without an address for push messages, and without `com.apple.developer.applesignin` Sign in with Apple fails with `notConfigured`. See [push messages](https://doc.saymyframe.com/guides/notifications.md#the-address) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md#the-capability). ### `flutter analyze` reports problems in `build/` On macOS, Flutter copies the Swift packages of plugins that depend on other plugins into `build/ios/SourcePackages`, together with their examples, which do not analyze in the app. That is why the `analysis_options.yaml` of a generated app leaves `build/**` out of the analysis. Keep that exclusion if you replace the file. ### `flutter analyze` fails in a directory whose path has letters beyond ASCII With Flutter 3.44 and 3.47, `flutter analyze` stops with exit code 255 and a `FormatException: Unterminated string` from `LspByteStreamServerChannel` when the path of the app has a letter beyond ASCII, such as `Γ©` or a Cyrillic letter. An app of `flutter create` in that directory fails the same way, so the cause is in Flutter, not in SMF: the tool counts the length of a message to the analysis server in UTF-16 code units instead of bytes. Flutter fixed it in its main branch ([flutter/flutter#191377](https://github.com/flutter/flutter/pull/191377)). Until your Flutter has the fix, keep the app in a directory whose path has only ASCII letters, or analyze it with `dart analyze`, which works there and reports the same issues: ```bash dart analyze --fatal-infos ``` `flutter pub get` and `flutter test` work in such a directory. ## CI ### `tool/write_env.dart` stops `.env has values, which this script would replace` means what it says: the script never replaces a value, so delete `.env` to write it again. When it names a key, the value of that key has a double quote, a control character or a line separator, which `.env` cannot hold. See [Values for each environment](https://doc.saymyframe.com/guides/ci.md#values-for-each-environment). ### CI turned red with no change in the code CI runs the latest stable Flutter, so a new release can fail `flutter analyze` on a new deprecation, and the format check on a change of the formatter. See [The version of Flutter](https://doc.saymyframe.com/guides/ci.md#the-version-of-flutter). ## Testing the app ### A test that runs `bootstrap()` fails with "The SharedPreferencesAsyncPlatform instance must be set" The app has [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md), and `bootstrap()` opens the preferences, which a test has no platform side for. Put the preferences of the package into memory before the test runs `bootstrap()` or `main()`: ```dart import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; // ... and in the test, before bootstrap() or main(): SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); ``` Both names come from the package `shared_preferences_platform_interface`, each from a library of its own. Add the package to the app as a dev dependency with `flutter pub add dev:shared_preferences_platform_interface`. ### A test that runs `bootstrap()` fails in the start of the notifications or of the push messages The packages of [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md#in-tests) and [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md#in-tests) have no platform side for tests, and `bootstrap()` starts both. `flutter test` registers no implementation of the plugin of flutter_local_notifications for the platform. So a test that runs `bootstrap()` or `main()` calls `AndroidFlutterLocalNotificationsPlugin.registerWith()` first, and answers the method channels itself with `setMockMethodCallHandler` of `TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger`: `dexterous.com/flutter/local_notifications` for the notifications and `plugins.flutter.io/firebase_messaging` for the push messages. The guide for coding agents of the app says the same. A test of a screen needs none of this: it gives `appNotifications.start()` or `appPush.start()` a service of its own; see [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md#in-tests). ### A test that signs a user up before the app starts never finishes A call of `appSession` that is made before the app starts waits for the start-up. Made in the body of a widget test, it waits in the fake time of that body, and a start-up that runs in real time, as in `tester.runAsync`, then never completes. Make the call outside the body of a test, as in a `setUpAll`, and do not await it. See [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#in-tests). ## Texts and languages ### `context.l10n` lacks a text that an ARB file has The app has [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md), and gen-l10n of Flutter writes the code that reads the ARB files. Run `flutter gen-l10n` after every change of the files in `lib/l10n`, a new file included: `flutter pub get` generates the code in a fresh clone of the app, and does not notice a new file. The language also goes into `appLocales` and into the `Info.plist` of the iOS app; see [Add a language](https://doc.saymyframe.com/guides/languages.md#add-a-language). ## Sign-in ### Signing in or signing up fails with `notConfigured` The app has [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md), and the way to sign in is not enabled in the Firebase project. The screens of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) then say only that sign-in is unavailable, and show the `developerHint` of the failure below that text in a debug build. The hint tells both ways to enable it: ```text AuthFailure: notConfigured (Sign-in is not enabled in the Firebase project my-project (Firebase answered operation-not-allowed). To fix it, run `dart tool/enable_firebase_sign_in.dart` in the directory of the app, or enable Email/Password, and Anonymous for an app that signs in anonymous users, in the Firebase console under Authentication > Sign-in method: https://console.firebase.google.com/project/my-project/authentication/providers) ``` Run the script, or enable Email/Password in the Firebase console, and Anonymous for an app in the mode `anonymous`; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication). On iOS and macOS, Firebase may answer for a project without Authentication with an internal error that says no more. The hint then says that this may be the cause, or another internal error. ### The iOS app stops when the user taps Continue with Google On iOS, the Google Sign-In SDK stops the app when the app has no iOS client of Google or not the URL scheme of that client in `ios/Runner/Info.plist`. google_sign_in does not catch the exception that the SDK throws then. With `firebase_auth`, run `dart tool/enable_firebase_sign_in.dart` after `tool/configure_firebase.dart`, which downloads the Firebase files with the client and writes the URL scheme; see [what Google needs](https://doc.saymyframe.com/modules/google-sign-in.md#what-google-needs). ### On Android, Continue with Google fails with `notConfigured` Google knows the Android app by the SHA-1 of the key that signs it. When the Google project does not know the key, Credential Manager answers `[16] Account reauth failed.` after the user picked an account, and `googleCredential()` fails with `notConfigured`, with that answer in its `developerHint`. A device that cannot reach Google gets the same answer. Register the SHA-1 and SHA-256 of the key: the script of `firebase_auth` registers those of the debug key of the machine that runs it, and a release needs those of the upload key and of the app signing key of Google Play; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#google). `[28444] Developer console is not set up correctly.` means something else: Google does not take the server client of the app as a web client of the Google project, as when `initialize()` gets the id of the Android client; see [what Google needs](https://doc.saymyframe.com/modules/google-sign-in.md#what-google-needs). ### Deleting an account that signs in with Apple fails with `notConfigured` Firebase revokes the tokens of Apple when such an account is deleted, with the Services ID and the key of Apple that you enter in the settings of the Apple provider in the Firebase console. Until they are set, the deletion fails with `notConfigured`, and the account stays. See [Firebase](https://doc.saymyframe.com/guides/firebase.md#apple). ### In the mode `anonymous`, the app starts without a user The app signs in an anonymous user when it starts and waits for that for at most 3 seconds. When the sign-in fails or takes longer, as without a network or while anonymous users are not enabled at the provider, the app starts with a `SignedOutSession`. In debug mode it prints the error of a sign-in that failed: ```text The anonymous sign-in failed, so the app has no user: AuthFailure: notConfigured (...) ``` The app tries again each time the user comes back to it. With `firebase_auth`, enable Anonymous in the Firebase project: run `dart tool/enable_firebase_sign_in.dart` again once `authMode` is `anonymous`; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication). ### Every screen is open although the mode is `required` The mode keeps nobody from a screen on its own. A guard of the routes that reads `appSession.allowsApp` does, and an app without such a guard shows every screen in every mode. The feature [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) declares that guard. An app with `firebase_auth` and without `sign_in` has none; see [an app without the screens](https://doc.saymyframe.com/guides/sign-in.md#an-app-without-the-screens). ### `smf create` warns that a route is for users with an account A module of the app asks for an account on a route, and no module of the app has a guard that stands for that condition, so every user gets to the screen. The app is generated all the same. Add `sign_in`, whose guard stands for the condition, or keep the other users away with a guard of your own that reads `appSession.hasAccount`; see [an app without the screens](https://doc.saymyframe.com/guides/sign-in.md#an-app-without-the-screens). ### In an app without tabs, nothing leads to the account The entry of the account is on the settings screen, which a main navigation shows, such as the tabs of [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md). In an app without a main navigation, no screen leads to the settings screen. Open it from a screen of yours with `context.nav.settings.settings().push()`, or open the account directly with `context.nav.signIn.account().push()`. ### The script says that it cannot tell the sign-in mode of the app `tool/enable_firebase_sign_in.dart` reads the mode from the declaration of `authMode` in `lib/core/auth/app_session.dart`. Keep that declaration in the form in which it was generated, on a line that it starts and with a mode as its value: ```dart title="lib/core/auth/app_session.dart" const AuthMode authMode = AuthMode.required; ``` A computed value, an indented declaration or a second declaration stops the script, which does not guess. ### The script says that `firebase.json` is missing or has no project `tool/configure_firebase.dart` writes the Firebase project of each flavor into `firebase.json`, and the script reads it from there. Configure a flavor first, with the command of the section "Firebase" of the README of the app, or name the project: ```bash dart tool/enable_firebase_sign_in.dart --project ``` When `firebase.json` has several projects, as when flavors have projects of their own, the script stops and lists them. A run covers one project, so run it once for each. ### The Firebase CLI did not enable the sign-in methods The script prints what to try after the Firebase CLI failed: - It runs the Firebase CLI in a temporary directory, where an account that `firebase login:use` chose for the directory of the app does not apply. If the Firebase CLI ran as the wrong account, name the account: `dart tool/enable_firebase_sign_in.dart --account `. - The log of the Firebase CLI, `firebase-debug.log`, was in that directory, which the script removes. To see what the Firebase CLI did, run the script with `--debug`. - The Firebase console enables the methods too, under Authentication > Sign-in method. With a Firebase CLI older than 15.34.0, the script stops before that and tells how to update it. ## REST API ### A request fails with `notConfigured` `REST_BASE_URL` in `.env` is empty, or is no address of a server, and the path is relative. Fill it in, give the command `--dart-define-from-file=.env`, and start `flutter run` again. See [The address](https://doc.saymyframe.com/guides/rest.md#the-address). ### A request in a test fails with `rejected` `flutter test` answers 400 to every `HttpClient`. Start a `RestTestServer`, which takes that stand-in away. See [In tests](https://doc.saymyframe.com/guides/rest.md#in-tests). ### A test with a request never finishes, or fails with a pending timer Inside `testWidgets` the time is fake, and a real socket never completes there. Make the request in `tester.runAsync`, and let it end before the body of the test does. ## Notifications and push messages ### The address for push messages stays `null` The app works without an address, and `appPush.address` is `null` until the platform gives one. On iOS the address needs a token of the Apple Push Notification service, which iOS gives only to a build signed with the entitlement `aps-environment`. The iOS simulator on a Mac gets a token, and one on a macOS virtual machine, such as a hosted CI runner, never does. On Android, Firebase has no token without Google Play services or a network. See [the address](https://doc.saymyframe.com/guides/notifications.md#the-address) and [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md#the-address-of-the-device). ## Firebase ### The app stops at start-up with an `UnsupportedError` The flavor of the build is not configured for Firebase yet, and its `lib/firebase_options_.dart` is still the placeholder. Run `dart tool/configure_firebase.dart --project=` in the app. See [One project for each flavor](https://doc.saymyframe.com/guides/firebase.md#one-project-for-each-flavor). An error that says that the app has no Firebase options for the flavor `null` comes from a run of the scheme `Runner` in Xcode. Select the scheme of a flavor instead. See [Xcode](https://doc.saymyframe.com/guides/flavors.md#xcode). ### A build fails with `File google-services.json is missing` Once one flavor is configured for Firebase, Android builds of the others need their files too. Run `dart tool/configure_firebase.dart --project=` for the flavor of the build. A plain `flutter build` builds `dev`, so that is the flavor to configure first. See [A flavor that is not configured](https://doc.saymyframe.com/guides/firebase.md#a-flavor-that-is-not-configured). ### An iOS build fails with `FirebaseJsonException: Please run "flutterfire configure"` The build phase of Crashlytics looks up the build configuration in `firebase.json`, and the flavor of the build is not configured. Run `dart tool/configure_firebase.dart --project=` on a Mac, rather than `flutterfire configure`. ### `flutter run` or `flutter build ios` fails in the phase `flutterfire upload-crashlytics-symbols` The app was configured with flutterfire_cli 1.4.0, whose phase for Crashlytics does not find the upload script where Flutter puts the Swift packages. Activate 1.4.1 and run `tool/configure_firebase.dart` again on a Mac for each configured flavor. See [Firebase](https://doc.saymyframe.com/guides/firebase.md#an-app-configured-with-flutterfire_cli-140). ### `flutter build ipa` fails in the phase for Crashlytics The phase of flutterfire_cli 1.4.1 does not find the upload script when Flutter archives the app. `tool/configure_firebase.dart` fixes the phase after each of its runs, but `flutterfire configure` by hand writes the phase again. After such a run on macOS, run `dart tool/firebase_configured/fix_crashlytics_phase.dart`. See [Crashlytics and `flutter build ipa`](https://doc.saymyframe.com/guides/firebase.md#crashlytics-and-flutter-build-ipa). ### `firebase login` does not finish on a remote machine `firebase login` waits for the browser to come back to a server on the machine where it runs, which a browser on another machine cannot reach. SMF runs `firebase login --no-localhost` instead when `SSH_CONNECTION`, `SSH_CLIENT` or `SSH_TTY` has a value, as in a session over SSH. If none of them has one, press Ctrl-C to stop the login, and log in yourself with `firebase login --no-localhost`. The run goes on without the login and prints the command to configure Firebase later. ### SMF says that the Firebase login has expired or is no longer valid `firebase login:list` still lists your account, but Google rejected the login when SMF listed your Firebase projects with `firebase projects:list --debug`. A login can expire or be revoked, for example when you remove the Firebase CLI's access in your Google account or when your organization asks you to sign in again. Log in again with `firebase login --reauth`, or over SSH with `firebase login --reauth --no-localhost`. In a terminal, SMF offers to do this for you. Plain `firebase login` only says that you are logged in already. Until the login works, `flutterfire configure` finds no Firebase project and offers to create one. ### SMF says that the Firebase login could not be checked SMF could not finish listing your Firebase projects with `firebase projects:list --debug`, so it does not know whether the login works, and it leaves the configuration for later. The warning gives the reason. A line such as `request to … failed, reason: getaddrinfo ENOTFOUND …`, or one with `ECONNREFUSED`, `ETIMEDOUT` or a certificate error, means that the Firebase CLI could not reach Google. Check your internet connection. Behind a proxy, set `HTTPS_PROXY` in the terminal that runs `smf`; the Firebase CLI reads it. `did not finish in 40 s` means that no answer came, as happens on a network that drops requests. SMF stops the command after 40 seconds and shows the progress "Checking the machine" while it waits. Once the network works, run `smf create --explain` to see the state of every check, then configure Firebase in the app with the command from its README. ### The Firebase CLI is installed, but SMF does not find it SMF looks for `firebase` on the `PATH` of the terminal that runs `smf`. After installing it yourself, open a new terminal, or add its directory to the `PATH`, and run `smf create --explain` to see the state of every check. ### SMF says that the Firebase CLI does not run SMF runs `firebase --version` to check the Firebase CLI. A `firebase` command can be on the `PATH` and still fail, such as one that runs the Firebase CLI of another Node.js, or a Firebase CLI on a Node.js that is too old for it. The warning says how the command ended. In a terminal, SMF offers to install the Firebase CLI again; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#before-generation-the-machine). If the old command still does not run after that installation, SMF says so. A new terminal may find it before the new Firebase CLI, as with a Firebase CLI of an older default version of nvm, so remove it. # Modules Source: https://doc.saymyframe.com/modules These are the modules that `smf create` offers. Each one is a Dart package on pub.dev, but you never add them to an app yourself: `smf create` puts what they generate into the app. | Module (`-m`) | Package | Kind | Role it provides | Adds to the app | | --- | --- | --- | --- | --- | | [`flutter_core`](https://doc.saymyframe.com/modules/flutter-core.md) | `smf_flutter_core` | scaffold | App entry | The Flutter project, `main()`, start-up and root widget, in every app, and the screen that an app starts on when no route starts it | | [`go_router`](https://doc.saymyframe.com/modules/go-router.md) | `smf_go_router` | infrastructure | Router | The router of the features' routes, with go_router | | [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md) | `smf_bottom_tabs` | layout | Layout | Tabs at the bottom for the destinations of the features, in a bar that it draws in the colors of the theme | | [`home`](https://doc.saymyframe.com/modules/home.md) | `smf_home_flutter` | feature | none | A start screen at `/home`, which welcomes the developer of the app and lists the next steps | | [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) | `smf_onboarding` | feature | Onboarding screen | The onboarding at `/onboarding`, which the app shows on its first launch until the user finishes it, with the steps that other modules add | | [`settings`](https://doc.saymyframe.com/modules/settings.md) | `smf_settings` | feature | Settings screen | A settings screen at `/settings`, with the settings of the modules in one group, a row for each | | [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) | `smf_sign_in` | feature | none | The screens of sign-in, sign-up and password reset for an email address and a password, with a button for each other way to sign in of the app, and the screen of the account with its row on the settings screen, with BLoC or with Riverpod | | [`paywall`](https://doc.saymyframe.com/modules/paywall.md) | `smf_paywall` | feature | none | The paywall at `/paywall`, which sells premium access with the plans of the current offer, the screen of the subscription at `/paywall/subscription`, its row on the settings screen and its step in the onboarding, with BLoC or with Riverpod | | [`bloc`](https://doc.saymyframe.com/modules/bloc.md) | `smf_bloc` | infrastructure | State management | `flutter_bloc` | | [`riverpod`](https://doc.saymyframe.com/modules/riverpod.md) | `smf_riverpod` | infrastructure | State management | `flutter_riverpod` and its `ProviderScope` | | [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md) | `smf_material_theme` | infrastructure | Theme | A light and a dark Material 3 theme with a palette, text styles and a bundled font, in `lib/core/theme/app_theme.dart` | | [`launcher_icons`](https://doc.saymyframe.com/modules/launcher-icons.md) | `smf_launcher_icons` | infrastructure | App icon | An opaque icon on iOS and an adaptive icon with a themed variant on Android, made with flutter_launcher_icons from two images in `assets/branding/` | | [`native_splash`](https://doc.saymyframe.com/modules/native-splash.md) | `smf_native_splash` | infrastructure | Splash screen | The screen that the system shows while the app starts, for the light and the dark mode, made with flutter_native_splash from two images in `assets/branding/` | | [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) | `smf_gen_l10n` | infrastructure | Localization | The texts of the app in ARB files, one for each language, with gen-l10n of Flutter | | [`get_it`](https://doc.saymyframe.com/modules/get-it.md) | `smf_get_it` | infrastructure | Dependency injection | Registration of the app's services in get_it | | [`event_bus`](https://doc.saymyframe.com/modules/event-bus.md) | `smf_event_bus` | infrastructure | Events | A `CommunicationService` on the event_bus package | | [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md) | `smf_shared_preferences` | infrastructure | Preferences | `AppPreferences` on the shared_preferences package, for the settings that the app remembers | | [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) | `smf_dart_define` | infrastructure | Values in .env | `AppEnv`, which gives the app the values of `.env` with `--dart-define-from-file` | | [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) | `smf_local_notifications` | infrastructure | Notifications | Notifications now and at about a time to come, the permission to show them and the taps on them, with flutter_local_notifications | | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | `smf_firebase_core` | infrastructure | none | Firebase for each flavor: options, initialization, the script `tool/configure_firebase.dart`, setup of the machine | | [`firebase_crashlytics`](https://doc.saymyframe.com/modules/firebase-crashlytics.md) | `smf_firebase_crashlytics` | infrastructure | Crash reporting | A `CrashReporter` on Firebase Crashlytics | | [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) | `smf_firebase_analytics` | infrastructure | Analytics | An `AnalyticsService` on Firebase Analytics, and screen views | | [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) | `smf_firebase_messaging` | infrastructure | Push messages | Push messages with Firebase Cloud Messaging: the address of the device for the backend, the messages and the taps on them | | [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | `smf_firebase_auth` | infrastructure | Authentication | Sign-in with Firebase Authentication: an email address and a password, an anonymous user, or a way to sign in of Google or Apple, and a script that enables the sign-in methods in the Firebase project | | [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) | `smf_google_sign_in` | infrastructure | none | Google sign-in on Android and iOS: `googleCredential()`, the icon of its button with the "G" of Google, and a way to sign in for the auth role | | [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) | `smf_apple_sign_in` | infrastructure | none | Sign in with Apple on iOS: `appleCredential()`, the icon of its button, a way to sign in for the auth role, and the entitlement of the capability in `ios/Runner/Runner.entitlements` | | [`dio`](https://doc.saymyframe.com/modules/dio.md) | `smf_dio` | infrastructure | REST API | The requests of `appRest` over a `Dio` | | [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) | `smf_revenuecat` | infrastructure | Purchases | Premium access with RevenueCat: the plans of the default offering, a purchase, a restore, and the access of the user before the first frame | | [`github_actions`](https://doc.saymyframe.com/modules/github-actions.md) | `smf_github_actions` | infrastructure | CI | `.github/workflows/ci.yml`: the checks on each push, and a release APK for an environment on request | The kind of a module decides the rules it follows. A feature keeps its files in `lib/features//` and declares routes, a layout provides the main navigation, and infrastructure sets up a service or a library without screens of its own. A feature can provide a role too, as `settings` does, and it can keep its state with the state manager of the app, as `sign_in` and `paywall` do in a variant for each. See [the module model](https://doc.saymyframe.com/concepts/module-model.md). ## Roles and their files A role generates the part of the app that other code counts on, whichever module provides it. These files belong to the roles rather than to a module: | Role | Files | What they declare | | --- | --- | --- | | App entry | `AGENTS.md`, `CLAUDE.md`, `lib/core/app/status_bar_icons.dart`, `test/core/app/status_bar_icons_test.dart`, and the sections of the flavors and the steps by hand in `README.md` | The guide for coding agents that work on the app; `StatusBarIcons`, which asks for the icons of the status bar that suit the theme, and its widget test | | Onboarding screen | `lib/core/onboarding/onboarding_steps.dart` | `OnboardingStep` and `appOnboardingSteps`, the steps that the modules add to the onboarding | | Router | `lib/core/router/app_router.dart`, `lib/core/router/navigation.dart` | `AppRouter`, `appRouter`, the location classes and `context.nav`. In an app with guards, also `routeGuards`, `redirectOf()`, `flowIsOver()`, `guardChanges` and `GuardedNavigation` | | Layout | `lib/core/layout/destination.dart` | `Destination`, the label and icon of an item of the main navigation, and `appDestinations`, the destinations of the app | | Theme | `lib/core/theme/theme_mode.dart`, and `lib/core/theme/theme_mode_setting.dart` in an app with a settings screen | `appThemeMode`, the theme mode that the user selected, `AppThemeModeScope` and `restoreAppThemeMode`; `ThemeModeSetting`, the entry of the settings screen | | Localization | `lib/core/l10n/app_locale.dart`, and `lib/core/l10n/language_setting.dart` in an app with a settings screen | `appLocales`, the languages of the app, `appLocale`, the language that the user chose, `AppLocaleScope` and `restoreAppLocale`; `LanguageSetting`, the entry of the settings screen | | Dependency injection | `lib/core/di/service_locator.dart` | `ServiceLocator`, `resolve()` | | Events | `lib/core/events/communication_service.dart` | `AppEvent`, `CommunicationService`, `createCommunicationService()` | | Preferences | `lib/core/preferences/app_preferences.dart` | `AppPreferences`, `initPreferences()`, `createAppPreferences()` | | Analytics | `lib/core/analytics/analytics_service.dart` | `AnalyticsService`, `createAnalyticsService()` | | Crash reporting | `lib/core/crash_reporting/crash_reporter.dart` | `CrashReporter`, `createCrashReporter()`, `installCrashReporting()` | | Authentication | `lib/core/auth/app_session.dart`, `lib/core/auth/auth_service.dart`, `lib/core/auth/guest_data.dart`, `lib/core/auth/sign_in_methods.dart` | `appSession`, the session of the app, `authMode` and `initAuth()`; `AuthService`, the interface of a provider, `AuthFailure` and `SignInCredential`; `takeGuestData()`, which the developer of the app edits; `SignInMethod` and `appSignInMethods`, the ways to sign in of the app | | Notifications | `lib/core/notifications/app_notifications.dart`, `lib/core/notifications/notifications_service.dart`, `android/app/src/main/res/drawable/ic_notification.xml`, `android/app/src/main/res/raw/notifications_keep.xml`, `lib/core/notifications/notifications_setting.dart` in an app with a settings screen, and `lib/core/notifications/notifications_step.dart` in an app with an onboarding | `appNotifications`, `NotificationPermission` and `initNotifications()`; `NotificationsService`, `AppNotification` and `NotificationTap`; the small icon of Android and the file that keeps it in a release build; `NotificationsSetting`, the entry of the settings screen; `notificationsStepShows()` and `allowNotifications()`, the functions of the step of the onboarding | | Push messages | `lib/core/push/app_push.dart`, `lib/core/push/push_service.dart` | `appPush` and `initPush()`; `PushService`, the interface of a provider, and `PushMessage` | | Purchases | `lib/core/purchases/app_purchases.dart`, `lib/core/purchases/purchases_service.dart`, and `lib/core/purchases/restore_purchases_setting.dart` in an app with a settings screen | `appPurchases`, the premium access of the user, and `initPurchases()`; `PurchasesService`, the interface of a provider, `AppAccess`, `Plan` and `PurchasesFailure`; `RestorePurchasesSetting`, the entry of the settings screen | | Values in .env | `.env`, `.env.example`, a line of `.gitignore`, `.vscode/launch.json` and `.run/.run.xml` | The values that you fill in, the same keys without values, the line that keeps `.env` out of git, and a run configuration for each flavor. Every provider generates `AppEnv` in `lib/core/env/app_env.dart`, with a getter for each key | | REST API | `lib/core/rest/app_rest.dart`, `lib/core/rest/rest_transport.dart`, `lib/core/rest/session_tokens.dart` in an app with sign-in, `test/core/rest/rest_test_server.dart`, `test/core/rest/app_rest_test.dart`, and the permission `android.permission.INTERNET` | `appRest`, the REST client of the app, `RestFailure`, `RestResponse` and `RestCancel`; `RestTransport`, the interface of a provider; what gives the client the token of `appSession`; `RestTestServer`, a local server for the tests of the app; a real request through the provider | | CI | `tool/write_env.dart` in an app with values in `.env` | The script that writes `.env` for a job. The commands of CI are in the README, and a provider writes them in the format of its host | The state management role, the settings screen role, the app icon role and the splash role have no files of their own that code reads: screens use the state management libraries directly, the module that provides the settings screen generates the screen, and each module of the icon and the screen generates its two images in `assets/branding/`. Besides the files above, the files of the app entry come from `flutter_core`. ## Routes, settings and texts of the modules A module does not reach into another module. It gives a role what the role collects from every module: a route, a guard, a restorer of a setting, a row of the settings screen, a step of the onboarding, a text, a key of `.env`. In an app with every module above, the router, the preferences, the settings screen, the onboarding and the localization get these from the modules, and from four roles. The services of the modules and what follows the screens are on the pages of the modules. | From | Routes and guards | Restorer of the preferences | Row of the settings screen | Texts, in English and in Ukrainian | | --- | --- | --- | --- | --- | | `home` | `/home`, a destination | | | The label of its tab, and the 14 texts of its screen | | `onboarding` | `/onboarding`, and the guard `onboarding.firstRun` | `restoreOnboarding` | | The six texts of its screen | | `settings` | `/settings`, a destination | | | The title of its screen, which is the label of its tab too | | `sign_in` | `/sign_in` with `/sign_in/sign_up` and `/sign_in/reset_password` below it, `/sign_in/account`, which asks for an account, and the guards `sign_in.gate` and `sign_in.hasAccount` | | Account | The 49 texts of its screens | | `google_sign_in`, `apple_sign_in` | | | | The label of the button of each, Continue with Google and Continue with Apple | | `paywall` | `/paywall`, and `/paywall/subscription`, which asks for premium access, and the guard `paywall.hasPremium` | | Subscription | The 65 texts of its screens, the three texts of its row, and the four texts of its step of the onboarding, Unlock premium | | The theme role, with `material_theme` | | `restoreAppThemeMode` | Theme | The four texts of its row | | The localization role, with `gen_l10n` | | `restoreAppLocale` | Language | The two texts of its row | | The notifications role, with `local_notifications` | | `restoreNotifications` | Notifications | The three texts of its row, and the four texts of its step of the onboarding, Turn on notifications | | The purchases role, with `revenuecat` | | | Restore purchases | The four texts of its row | So the settings screen of such an app has the rows Account and Subscription, and after them the rows Theme, Language, Notifications and Restore purchases, in the order of the modules that provide the four roles. The onboarding shows the step of the notifications and then the step of the paywall before its last page. The preferences restore four settings before the first frame, and the router asks four guards: the gate of the onboarding, then the gate of the sign-in, then the guard of the routes that need an account, and last the guard of the routes that need premium access. Such an app starts on `/home`, so `flutter_core` gives it no texts: only an app that no route starts has the two texts of its fallback start screen. `revenuecat` gives the role of the values in `.env` the three API keys of RevenueCat, `paywall` the addresses of its terms of use and its privacy policy, and the REST role the address of the API; see [Values in .env](https://doc.saymyframe.com/guides/env.md). A module of your own gives the roles the same things; see [Extending SMF](https://doc.saymyframe.com/extending.md). Three modules also add files that are not code, and declare them in `pubspec.yaml`: `home` the image of its screen, in `lib/features/home/assets/`, `google_sign_in` the "G" of Google for its button, in `lib/core/google_sign_in/assets/`, and `material_theme` the font of its themes with its license, in `assets/fonts/geist/`. # `flutter_core` Source: https://doc.saymyframe.com/modules/flutter-core | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_flutter_core`](https://pub.dev/packages/smf_flutter_core) | scaffold | App entry | nothing | added to every app | `flutter_core` creates the Flutter app that every SMF app starts from: the Android and iOS projects, `main()`, the start-up sequence, the root widget, `pubspec.yaml`, and, in an app that no route starts, the screen that the app starts on instead. It provides the app entry role, and every app needs exactly one provider of that role, so `smf create` adds `flutter_core` to every app. ## What it adds to the app | File | What it holds | | --- | --- | | `lib/main.dart` | `main()`: `WidgetsFlutterBinding.ensureInitialized()`, `await bootstrap()`, then `runApp()` with the root widget inside the wrappers of other modules. | | `lib/bootstrap.dart` | `bootstrap()`, where the other modules put their start-up code, phase by phase. It imports neither `material` nor `cupertino`. | | `lib/app.dart` | `App`, the root widget: a `MaterialApp.router` with the router's configuration when the app has a router, or else a `MaterialApp` that shows the fallback start screen. `App` creates it in its `build`, with the arguments that modules and roles give it, such as the theme. Its `builder` holds the widgets that other modules put around the content of every route. | | `lib/core/app/fallback_start_screen.dart` | Only in an app that no route starts: `FallbackStartScreen`, [the screen](#the-fallback-start-screen) that such an app starts on, and `FallbackStartView`, which the screen builds with its texts. | | `test/core/app/fallback_start_screen_test.dart` | Only in an app that no route starts: a widget test of the fallback start screen. | | `pubspec.yaml` | The dependencies of all modules, with Dart `^3.12.0` and Flutter `>=3.44.0`, and `flutter_lints` for the lints. | | `analysis_options.yaml` | The lints of a new Flutter app, with `build/**` left out of the analysis. | | `README.md` | The name of the app, the line "Generated with Say My Frame", and the sections that other modules add. | | `.gitignore`, `.metadata` | The files of the same names that `flutter create` writes. | | `android/`, `ios/` | The projects of `flutter create` of Flutter 3.44, with the identifiers of the app and the [flavors](https://doc.saymyframe.com/guides/flavors.md) `dev`, `staging` and `prod`. | The native projects are those that `flutter create --platforms=android,ios` writes with Flutter 3.44.2, with a few changes: - The names and identifiers come from the app. The Android namespace, application id and Kotlin package path, and the iOS bundle id, come from `--org` and the app name. - The flavors are plain text, with no package. The Gradle file of the app has `flavorDimensions` and `productFlavors`, each with its id suffix and its name on the device. On iOS, the Xcode project has `Debug-`, `Profile-` and `Release-` in each of its three configuration lists, and a shared scheme for each flavor. The Android label is the placeholder `${appName}` and the iOS display name the setting `APP_DISPLAY_NAME`, so each flavor has a name of its own: the name of the app in title case, with `Dev` or `Staging` after it, and without either for `prod`. The scheme `Runner` and the plain configurations stay, with the id and the name of `prod`. - The minimum iOS version is 15.0, the lowest that Xcode 27 builds for, unless a module needs a higher one. The Xcode project has no development team. - The Android manifest, `Info.plist`, `AppDelegate.swift` and the Gradle files have places where other modules add permissions, keys, components, code and plugins; see [the sockets of the app entry](https://doc.saymyframe.com/concepts/sockets.md#the-sockets-of-the-app-entry). A place that gets nothing leaves no line. So an app whose modules add nothing there has the files of `flutter create`, apart from two changes below: an empty `dependencies` block in the Gradle file of the app, and `Runner.entitlements`, which the Runner target signs with. - The Gradle file of the app ends with a `dependencies` block for the dependencies of the modules, which stays empty when no module adds one. It also has the two places of core library desugaring: the switch in `compileOptions` and the library in `dependencies`. - `ios/Runner/Runner.entitlements` holds the entitlements of the iOS app, such as Push Notifications or Sign in with Apple, which modules add. Every build configuration of the Runner target signs with the file, also while it is empty, as Xcode does when it adds a capability. With nothing in it, the file changes nothing of how the app is signed. The app entry role adds two files to every app too, whichever module provides it: `lib/core/app/status_bar_icons.dart` with `StatusBarIcons`, which the root wraps around the content of every route, and its widget test, `test/core/app/status_bar_icons_test.dart`. The widget asks the system for dark icons of the status bar on a light theme and for light ones on a dark theme. A screen with an `AppBar` gets the icons that suit its bar. The test is in every app, so `flutter test` has a test to run in an app whose modules bring none. The app also gets `AGENTS.md` and `CLAUDE.md`, the guide for coding agents. They come from the app entry role, whichever module provides it, so an app with another provider of the role has them too. To the section "App entry" of the guide, the module adds where each flavor is in the native projects, the commands to run after a change, the rules of its root widget with the one `MaterialApp` of the app, where the test of a file goes, and that the entitlements of the iOS app are in `ios/Runner/Runner.entitlements`, which the Signing & Capabilities tab of Xcode edits too. See [Working with a coding agent](https://doc.saymyframe.com/guides/coding-agents.md). ## The fallback start screen An app has the fallback start screen only when no route can start it: an app without a router, which shows the screen as the home of its root, and an app with a router whose features mark no route to start on, where the screen is at `/`. It is a screen for you, the developer of the app. An app with a feature whose route can start it, such as [`home`](https://doc.saymyframe.com/modules/home.md), gets neither the screen nor its test nor its texts. The screen shows, in the middle: 1. The app as a cell of the periodic table, with smaller cells around it. `smf create` makes the symbol and the number of the cell from the name of the app, `Ma` and 5 for `my_app`: the first letters of its first two words, or the first two letters of a name of one word, and how many letters and digits the name has. 2. The name of the app. 3. A hint: "No start screen yet. Add a feature with a route, or replace this screen." 4. The path of the file of the screen, `lib/core/app/fallback_start_screen.dart`. A tap copies it, and a snack bar says so. | | | | --- | --- | | Colors and fonts | The screen takes its colors and its text styles from the theme of the app, so it follows the theme mode. The path and the number of the cell are in the monospaced font of the device. | | Motion | The screen comes in with a short fade, once. On a device that asks for less motion, it is there at once. | | Large text | The screen scrolls when it is too small for what it shows. The letters of the cell keep their size, since the cell is a picture, and the path grows to at most one and a half times its size. | | Screen readers | A screen reader passes over the cell, and announces the name of the app as a header and the path as a button. | ### Its texts and the languages of the app The hint and the word that the snack bar says before the path, Copied, are texts of the module, in English and in Ukrainian. In an app with a module that provides the localization, such as [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md), they are the texts `flutterCoreFallbackHint` and `flutterCoreFallbackCopied` of the app, and the screen shows them in the language of the app. Without one, they are in English. The module gives the localization role the two texts only in an app that has the screen. So such an app with a module that provides the localization is in English and in Ukrainian unless `--locales` says otherwise, also an app without a feature; see [Languages](https://doc.saymyframe.com/guides/languages.md#the-languages-of-the-app). `FallbackStartScreen` only reads the two texts and gives them to `FallbackStartView`, which shows the rest. In an app with `gen_l10n`: ```dart title="lib/core/app/fallback_start_screen.dart" class FallbackStartScreen extends StatelessWidget { /// Creates the screen. const FallbackStartScreen({super.key}); @override Widget build(BuildContext context) => FallbackStartView( hint: context.l10n.flutterCoreFallbackHint, copied: context.l10n.flutterCoreFallbackCopied, ); } ``` So the widget test of the app shows the view with texts of its own, and needs neither the root of the app nor its texts: ```dart title="test/core/app/fallback_start_screen_test.dart" /// Shows the view of the fallback start screen with texts of the test. Future _show(WidgetTester tester) => tester.pumpWidget( const MaterialApp( home: FallbackStartView(hint: 'A hint', copied: 'Copied'), ), ); ``` The test checks that the view names the app and the file, that a tap copies the path, and that the view fits a small phone with the largest text size. ### Give the app a start screen In an app that shows the screen, replace it with the first screen of your own. The widget test is a test of `FallbackStartView`, so change it with the view, or remove it with the view, and with the two texts in an app with `gen_l10n`. ## Start-up phases `bootstrap()` runs the start-up code that modules and roles add, in four phases, in this order: | Phase | What goes there | | --- | --- | | early | Code that must come before anything else | | platform | Platform services, such as `await Firebase.initializeApp(...)`, `installCrashReporting()` and `await initPreferences()` | | DI | The services of the app: `await registerDependencies();` | | late | Code that needs those services | `main()` runs the root widget inside the wrappers that modules add, such as the `ProviderScope` of Riverpod. `App` builds below them, so an argument of the root `MaterialApp` can read an inherited widget among the wrappers from the `BuildContext` of `App`, and the root rebuilds when that widget notifies. The theme mode reaches the root this way. ## Choosing it Every app has a provider of the app entry role. While `flutter_core` is the only module that provides it, you don't choose it: `smf create` adds it by itself. ## Requirements The app needs Flutter 3.44 or newer and Dart 3.12 or newer, and runs on iOS 15 or newer. For iOS builds with Xcode 27, see [troubleshooting](https://doc.saymyframe.com/guides/troubleshooting.md#ios-builds-with-xcode-27). # `go_router` Source: https://doc.saymyframe.com/modules/go-router | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_go_router`](https://pub.dev/packages/smf_go_router) | infrastructure | Router | nothing | `-m go_router` | `go_router` routes the app with [go_router](https://pub.dev/packages/go_router) 17. The features of the app declare their routes for the router role, which generates the typed navigation, `context.nav`, and this module turns the routes into a `GoRouter`. ## What it adds to the app - `go_router: ^17.5.0` in the dependencies. - `lib/core/router/app_router_factory.dart` with `createAppRouter()`, which creates the router of the app once, on first use: a `_GoRouter`, a class of that file that extends `GoRouter`. The router role adds, whichever module provides it, `lib/core/router/app_router.dart` with `AppRouter` and `appRouter`, and `lib/core/router/navigation.dart` with the location classes and `context.nav`. With a router, the root widget of the app becomes a `MaterialApp.router`. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the router role describes navigation and the three places of a route under "Router". The module adds how its file writes a route as a `GoRoute`, that `initialLocation` and the route `/` change together, and, in an app with a layout, where the destinations of the main navigation go and that the router creates the route of the main navigation anew. ## The routes - Every route is a `GoRoute` under the namespace of its feature, such as `/home` or `/catalog/item/:id`, with its children below it. - The name of a route is its full name, such as `home.home`. The listeners of the screen get it as the name of the screen, and navigator observers as the name of the page. - The router imports each screen with a prefix of its own, so the names of screens never clash. - The app opens on its start route, and `/` redirects to it. When no route can start the app, as in an app without features, `/` shows the fallback start screen. Screens get the values of their parameters from the location. An `int` or a `double` is parsed with `tryParse`, and a `bool` must be `true` or `false` exactly. An optional value that the location does not have, or that is not of its type, is `null`. A location without a valid required value, such as `/catalog/item/abc` for an `int`, shows the error screen of go_router. ## The main navigation When the app has a layout, such as [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), and destinations, they form the main navigation: a `StatefulShellRoute.indexedStack` with a branch for each destination, in the order of the features, which shows the `AppShell` of the layout. The router gives the shell `appDestinations` of the layout role, and renders neither a label nor an icon itself. - The routes below a destination stay in its branch, which keeps its stack while another branch is selected. - The app opens on the branch of its start route. - The other top-level routes are outside the main navigation, and the router matches the destinations first. - Without destinations, or without a layout, there is no main navigation. go_router keeps the pages of the branches, and the navigators that show them, with the route of the main navigation, for as long as a page of that route is in the widget tree ([flutter/flutter#148768](https://github.com/flutter/flutter/issues/148768)). A main navigation that came back sooner, such as in the same turn, would have the pages of its branches again. So the router keeps its routes in a `RoutingConfig` that go_router follows, and each time the main navigation leaves the pages of the router, it puts a new route for the main navigation there, which `_mainNavigation()` creates. The main navigation then comes back with each branch on its destination, also in the same turn or while the transition to the page that took its place is on its way. ## Navigation `context.nav` navigates through this router from any context, even one above the router. - `go()` shows the location with the chain of its parents below it, in the branch of the location when it is in the main navigation. - `push()` shows the location on top and completes with the value its page returns. In the main navigation it goes on top of the stack of the selected branch, whichever branch the location belongs to, as go_router does. - `replace()` replaces the top of the stack with the location, as go_router's `pushReplacement` does. go_router shows the main navigation only once, so a location in it can only go on top of the main navigation itself. On a page shown over the main navigation, `push()` and `replace()` of such a location throw a `StateError` that says to use `go()`, and leave the stack as it is. On a page with no main navigation below it, `push()` brings the main navigation back on top with the location. See [Navigation](https://doc.saymyframe.com/guides/navigation.md). ### Without a page of a route go_router has no page of a route in two states: before it shows its first location, and while it shows its error screen in place of the whole stack, for a location that no route matches or that the redirect of a route refuses. It then has no page to push over and none to replace. `GoRouter.push` would keep the error screen and never complete, or throw for a location in the main navigation, and `GoRouter.pushReplacement` throws for want of a page. So in both states, `push()` and `replace()` of the router give go_router their location as `go()` does. The location shows with the pages of its chain, in place of the error screen, and such a `push()` completes with `null`. An error screen that a push showed over a page is a page of go_router, which pushes over it and replaces it like any other. ## The back button of the system The router closes the route on top when the user presses the back button of the system, as [the router role asks](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data). With no route to close, it leaves the button to the system, which closes the app. go_router shows its error screen in place of the whole stack, for a location that no route matches or that the redirect of a route refuses, and then has no page of a route. Asked to close the route on top, its delegate throws a `StateError` there ([flutter/flutter#187616](https://github.com/flutter/flutter/issues/187616)). So the `_GoRouter` of the module has a dispatcher of the button of its own, which asks the root navigator while go_router has no page: - A route that is shown over the error screen, such as a dialog, closes. - With no route to close, the button is left to the system, as on the first page of the app. - A `BackButtonListener` below the router hears of the button first there too. - An error screen that a push showed over a page is a page of go_router, which closes it. ## Guards A module can keep the user from the rest of the app until a condition holds, with a [guard](https://doc.saymyframe.com/concepts/guards.md), or only from the routes that ask for a [condition](https://doc.saymyframe.com/concepts/conditions.md). In an app whose modules declare guards, the router asks them through the `GuardedNavigation` that the router role generates, which keeps the location that the user comes back to. The router remembers nothing of the gates itself, and it knows a location by its URI. It asks at three places: - `go()`, `push()` and `replace()` ask once, before they hand a location to go_router, with the routes of the pages that the user can get back to. - The top-level `redirect` of the `GoRouter` asks about the locations that go_router parses on its own, with no pages: the one the app starts on, those of the platform, and that of a branch of the main navigation that the user selects. - The router listens to `guardChanges` of the role. When a guard starts or stops allowing, it tells the role of the pages that pushes showed, the one on top first, and of the location below them. A page that `replace()` showed over other pages counts as one that a push showed, as it is one to go_router. What it does with the answers: | The role answers | What the router does | | --- | --- | | A location in place of the stack: the target of a gate, the location that the user comes back to, or `/` for a flow that is over. | It goes to the location, and a `push()` that asked completes with `null`. The target of a gate is outside the main navigation, so the router gives go_router a new main navigation, and no branch keeps a page. A `go()` to `/` leaves the branches that are not selected as they are. | | The target of a guard that stands for a condition, to open over the page on top. | It pushes the target and keeps the request waiting: how to make it again and, for a `push()`, the future that it returned. It keeps one request, and drops it once no page of the flow is among its pages, as when the user went back. | | Pages to close: those of a flow that is over, or of routes whose condition stopped holding. | It takes them out of the pages of go_router with one `restore()`, and completes their pushes with `null` once the frame is over. Then it makes the request that waited again, or drops it when the role says so. | A `redirect` can only send go_router to another location. So when the role answers a location from the platform with a page to open over the screen that the app starts on, the target of such a guard or a page of its flow that a link asked for, the router sends go_router to `/` and pushes that page once the parse is over. Two links that arrive in one turn open it once, for the later one. A second link to the page that is on top keeps that page, with what the user typed there: the router puts it back over `/` and pushes no new one. The `redirect` of go_router runs within each call of go_router, also within those that the router makes itself, and it asks with no pages, as for a link. The answer of the role depends on the pages, so the router counts its own calls, and the `redirect` asks nothing within them: - A call is the router's own when it hands go_router a location that it asked about itself, or that the role answered, or pages that are shown already. A refresh of go_router is one, since it parses the location below the pushed pages again. - The push of the target of a guard is one too. If the `redirect` were asked about it, the role would answer to open the target again, without end. The router throws a `StateError` then, and does not hang the app. While go_router has no page of a route, the router asks the role nothing itself. `go()`, `push()` and `replace()` give go_router the location as `go()` does, and the `redirect` asks about it. So the flow of a guard opens over `/` there, in place of the error screen too. The router does not hand `guardChanges` to go_router as its `refreshListenable`. A refresh asks only about the location below the pushed pages, and gives each of those pages a new completer. In an app without guards, `app_router_factory.dart` has none of this code. [Ask the guards in a router](https://doc.saymyframe.com/extending/router-guards.md#with-go_router) shows the code. ## Observers and listeners of the screen Every navigator, the root one and the one of each branch, creates observers of its own from the factories that modules give the router role. The branches do not notify the observers of the root navigator, so each page is reported once. For an observer, switching branches is not a navigation event. To follow the screen the user sees, modules such as [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md) give the router role listeners of the screen instead. The router listens to its go_router delegate and calls each listener once whenever the page on top of the app changes or shows another location, including on a switch to another branch, as [the router role promises](https://doc.saymyframe.com/extending/role-provider.md#following-the-router). The listener gets the full name of the route and the location, such as `home.home` and `/home`. For a screen that is not a route of a module, the route is `null`. That is the fallback screen, at `/`, and the error screen of go_router, at the location it could not show. The router calls each listener on its own, so a listener that throws keeps no other from hearing of the screen, and what it throws reaches neither the router nor the handlers of the errors of the app. In debug mode the router prints it. The listeners hear only of pages that the user saw. When the router closes the pages of a flow and the request that waited shows another page over the page below them, they hear of that other page and not of the page below. ## Options `--start=` sets the full path of the route the app starts on. It can name any route without required parameters that is outside the flow of a guard and asks for no condition, and a run without a terminal needs it when several routes can start the app. See [the start screen](https://doc.saymyframe.com/guides/navigation.md#the-start-screen). ## Choosing it `smf create` asks which module provides the router, with None as one of the answers. When a module you chose needs a router and `go_router` is the only module that provides one, `smf create` adds it by itself instead. To choose it without the question: ```bash smf create my_app -m go_router ``` ## Version The module uses go_router 17, which works with the Material library of Flutter 3.44. go_router 18 looks for the `MaterialApp` of the separate `material_ui` package to choose Material pages, and apps on Flutter 3.44 do not use that package. # `bottom_tabs` Source: https://doc.saymyframe.com/modules/bottom-tabs | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_bottom_tabs`](https://pub.dev/packages/smf_bottom_tabs) | layout | Layout | a router | `-m bottom_tabs` | `bottom_tabs` shows the main navigation of the app as tabs in a bar at the bottom. Features declare which of their routes are destinations of the main navigation, each with a label and an icon, such as Home with the home icon, and this module generates the widget around them. ## What it adds to the app The module adds `lib/core/layout/app_shell.dart` with `AppShell`, a `Scaffold` whose body is the screen of the selected destination. Below the screen is a bar with a tab for each destination: its icon over its label, below a hairline. The file draws the bar itself, with the widgets `_TabBar` and `_Tab`, in the colors of the theme of the app, so the file is where you change the look of the bar. The module adds no package to the app. - The selected tab differs from the others only in its color, which it takes over a moment. No tab changes its size, and the bar has no indicator behind the selected icon. - A tap on a tab selects its destination, with the tick of a selection on the device when it is another tab. The screen of the new destination fades in while it rises a little. - A label is a text of the feature of its tab, so the tabs follow the language of the app. - With a single destination there is nothing to switch to, so the bar is hidden and the screen fills the app. ![The bar below the start screen in the light theme: the tabs Home and Settings, each an icon over its label, below a hairline. Home is the selected tab, in green.](https://doc.saymyframe.com/demo/0.8/app_4_home.png) ![The bar below the settings screen in the dark theme, in Ukrainian: the labels of the tabs are in Ukrainian, and the second tab is the selected one.](https://doc.saymyframe.com/demo/0.8/app_8_settings_dark_uk.png) The layout role adds `lib/core/layout/destination.dart`, whichever module provides the layout. It has `Destination`, the icon of an item and a function that returns its label, and `appDestinations`, the destinations of the app. A tab calls `destination.label(context)` each time it builds and keeps nothing of what it returned, so a label is in the language that the app is in. The role also requires every layout to keep `destinations`, `currentIndex` and `onSelect` of its `AppShell` public, so a test of the app can find a destination by its label and icon, select it with `onSelect` and read the selected one from `currentIndex` without knowing the module. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the layout role describes the shell and the destinations under "Layout". The module adds that it draws the bar itself and hides it while the app has fewer than two destinations, to keep to five, where the bar takes its colors from, and what a tab says to a screen reader. ## Change the look of the bar The bar is not the `NavigationBar` of Material, but it takes its colors where that bar does: from the navigation bar theme of the app, `NavigationBarTheme.of(context)`. For a color that the theme does not set, it reads the color scheme: | Part of the bar | From the navigation bar theme | Otherwise, from the color scheme | | --- | --- | --- | | The icon and the label of the selected tab | The color of `iconTheme` for a selected destination | `primary` | | The icon and the label of the other tabs | The color of `iconTheme` | `onSurfaceVariant` | | The background of the bar | `backgroundColor` | `surface` | | The hairline above the bar | | `outlineVariant` | So for other colors, set them in the `navigationBarTheme` of the theme of the app. With [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md#the-components), that is in `lib/core/theme/app_theme.dart`, where the selected tab gets the accent of the theme. The bar reads nothing else of that theme: the height, the indicator and the text style of a label there do not change it. A label has the style `labelMedium` of the text theme. Everything else is in `app_shell.dart`: the size of an icon, the space between an icon and its label, how long a tab takes to change its color, and how the screen of a destination comes in. Two constants at the top of the file hold the height of the bar and the limit of the text size of a label: ```dart title="lib/core/layout/app_shell.dart" /// The least height of the bar above the inset of the device. The bar grows /// when a label needs more. const double _barHeight = 64; /// The most that the text size of the device scales the label of a tab. A /// long press on a tab shows its label in a tooltip, at the full text size. const double _maxLabelScale = 1.3; ``` ## Large text, screen readers and less motion The bar gives what a navigation bar of Flutter would give: - The text size of the device scales a label up to 1.3 times. A label keeps to one line and ends with an ellipsis when its tab is too narrow for it, and a long press on a tab shows the label in a tooltip at the full text size. The bar is at least 64 high above the inset of the device, and grows when a label needs more. - Each tab is one button for a screen reader, with the label of its destination, selected or not. What you add to a tab, such as a badge, is not read unless the `Semantics` of the tab says it. - For a user who asks the device for less motion, the tab and the screen change at once. ## How the router uses it The module that provides the router builds the main navigation around the shell, with a branch for each destination in the order of the features. Each branch keeps its stack while another tab is selected. The app opens on the tab of its start screen, and an app without destinations has no main navigation. See [Navigation](https://doc.saymyframe.com/guides/navigation.md#tabs-and-other-main-navigation). ## Limits The bar shows at most five destinations, as the Material Design guidelines advise. A feature whose destination does not fit is left out of the app with a warning, and with `--strict`, `smf create` stops instead. ## Choosing it `smf create` asks which module provides the layout before it asks about the router, and offers None as well. To choose it without the question: ```bash smf create my_app -m home,bottom_tabs ``` The layout requires a router, which `smf create` adds when only one module provides it. # `home` Source: https://doc.saymyframe.com/modules/home | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_home_flutter`](https://pub.dev/packages/smf_home_flutter) | feature | none | a router | `-m home` | `home` is the start screen of the app. As generated, it is a welcome to you, the developer of the app: it names the app and lists what to do next. You replace its content with the first screen of your app. ## What the screen shows From the top: 1. A greeting by the time of the day and the name of the app, next to the mark of Say My Frame. The greeting is Good morning before noon, Good afternoon until six in the evening, and Good evening after that. 2. A card that tells that the app is ready. It shows the app as a cell of the periodic table, next to cells that light up one after another. 3. Three next steps, each with the path or the address that it is about: | Step | What a tap copies | | --- | --- | | Make this screen yours | `lib/features/home/home_screen.dart` | | Add a feature | `lib/features/` | | Read the docs | `doc.saymyframe.com` | A snack bar says what was copied. 4. A last line, Built with Say My Frame. ![The start screen in the light theme, in English, at 15:41: the greeting Good afternoon and the name My App next to the mark of Say My Frame, a dark green card with the cell Ma 5 that says Your app is ready, and the first next steps with their paths. Below is the tab bar with Home selected.](https://doc.saymyframe.com/demo/0.8/app_4_home.png) ![The same screen in the dark theme, in Ukrainian, with the greeting Π”ΠΎΠ±Ρ€ΠΈΠΉ дСнь. The card keeps its colors, and the texts of the screen and the labels of the tabs are in Ukrainian.](https://doc.saymyframe.com/demo/0.8/app_9_home_dark_uk.png) `smf create` makes the symbol and the number of the cell from the name of the app. The symbol is the first letter of its first word and the first letter of its second word, or the first two letters of a name of one word. The number is how many letters and digits the name has. For `my_app` they are `Ma` and 5, at the top of the file: ```dart title="lib/features/home/home_screen.dart" /// The name of the app, as the screen shows it. const _appName = 'My App'; /// The symbol of the app in its cell, as an element of the periodic table /// has one: the first letters of the first two words of its name, or the /// first two letters of a name of one word. const _appSymbol = 'Ma'; /// The number in the cell of the app: how many letters and digits its name /// has. const _appNumber = 5; ``` | | | | --- | --- | | Colors and fonts | The screen takes its colors and the styles of its texts from the theme of the app, whichever module provides it, so it follows the theme mode. Only the card keeps the colors of Say My Frame in the light and in the dark theme. A path is in the monospaced font of the device. | | Motion | When the screen opens, its parts rise in one after another, once, and then nothing moves. So a widget test that waits for the screen with `pumpAndSettle()` returns. | | Less motion | On a device that asks for less motion, the parts are there at once. | | Large text and small phones | The screen scrolls. The symbol and the number of the cell keep their size, since the cell is a picture. The path of a step and the snack bar grow to at most one and a half times their size, and take as many lines as they need. A narrow card leaves out the cells that would reach the cell of the app. | | Screen readers | A screen reader announces the name of the app and the heading of the steps as headers, and each step as one button. It reads the mark as Say My Frame and passes over the cell of the app. | `HomeScreen` takes a function `now` that tells the time, `DateTime.now` unless a test gives its own, so a test can show each greeting whatever the time of the machine. ## What it adds to the app | In the app | What it is | | --- | --- | | `lib/features/home/home_screen.dart` | `HomeScreen`, the screen. | | `lib/features/home/assets/smf_mark.png` | The mark of Say My Frame, an image. The files of the same name in `2.0x/` and `3.0x/` next to it are for the screens with more pixels. | The module declares the image in `pubspec.yaml`. Flutter finds the other two files next to it, so they have no line of their own: ```yaml title="pubspec.yaml" flutter: uses-material-design: true assets: - "lib/features/home/assets/smf_mark.png" ``` The module adds no package to the app. It gives the router role one route: | | | | --- | --- | | Path | `/` of the feature, so the full path is `/home` | | Full name | `home.home` | | Navigation | `context.nav.home.home()` | | Destination | Home, with the home icon, in the main navigation when the app has a layout | | Start | The app can start on it | When no other route can start the app, the app opens on `/home`, and `/` redirects there. When other routes can start it too, `smf create` asks which one, or takes it from `--start`. The label of the destination and the 14 texts of the screen are texts of the module, in English and in Ukrainian: the three greetings, the two texts of the card, the heading of the steps, a title and a text for each step, Copied, and the last line. In an app with a module that provides the localization, such as [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md), they are texts of the app under names that start with `home`, from `homeLabel` to `homeFooter`, and the screen shows them in the language of the app. Without one, the screen shows them in English. The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app gets a section "Home", which says that the screen is a welcome whose content you replace, and where the image that it shows is declared. ## Make the screen yours Replace the content of `lib/features/home/home_screen.dart` with the first screen of your app. Keep the class `HomeScreen` with a `const` constructor that needs no arguments, since the router creates the screen with `const HomeScreen()`, and keep the route while the app starts there: ```dart title="lib/features/home/home_screen.dart" import 'package:flutter/material.dart'; /// The screen that the app starts on. class HomeScreen extends StatelessWidget { /// Creates the screen. const HomeScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('My App')), body: const Center(child: Text('The first screen of the app')), ); } ``` Then take out what only the welcome needs: - Once no screen shows the mark, remove the three files in `lib/features/home/assets/` and their line in `pubspec.yaml`. - In an app with `gen_l10n`, remove the texts of the welcome from the ARB files once no code reads them, and run `flutter gen-l10n`. Keep `homeLabel`, the label of the destination, which `lib/core/layout/destination.dart` reads in an app with a layout. The generated screen has no app bar, and it does not tell the system which icons the status bar needs. The root of the app does that for every screen, from the theme, so a screen of your own without an app bar needs no `AnnotatedRegion` for them either. ## Requirements As a feature, `home` requires the router role, whichever module provides it. While `go_router` is the only module that provides the router, `smf create` adds [`go_router`](https://doc.saymyframe.com/modules/go-router.md) by itself. What moves on the screen is the state of the screen itself, so `home` works with any module that manages state or with none, and it needs no services. ## Choosing it `smf create` asks which features the app has, with this one selected already, so Enter takes it. A run without a terminal takes only the modules that it was given. To choose it without the question: ```bash smf create my_app -m home ``` # `onboarding` Source: https://doc.saymyframe.com/modules/onboarding | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_onboarding`](https://pub.dev/packages/smf_onboarding) | feature | Onboarding screen | a router, preferences | `-m onboarding` | On its first launch, the app shows the onboarding in place of every other screen. It has two pages: a welcome with the name of the app, and a page that ends it. A page is a picture with a title and a text below it. The picture is a cell of the periodic table among smaller cells, over a grid that fades at its edges. Skip is above the pages. Below them are a mark for each page and one button of the whole width: Next, and Get started on the last page, where Skip is gone. Skip and Get started finish the onboarding. The app then shows the screen that it starts on, and later launches open there. The module provides the onboarding screen role, so other modules can add steps to the onboarding, such as a page that asks for the permission to show notifications or a page that offers premium access. Each step gets a page of its own before the last page, in the look of the other pages; see [steps of other modules](#steps-of-other-modules). ![The first page of the onboarding: a cell with the symbol Ma and the number 1 among smaller cells, the title My App with a welcome below it, Skip at the top, a mark for each page, and the button Next.](https://doc.saymyframe.com/demo/0.8/app_1_onboarding_welcome.png) ![The step of the notifications on the second page: a dark green cell with a bell and the number 2, the title Turn on notifications with a text below it, the button Allow notifications, and Not now below it. Skip is at the top.](https://doc.saymyframe.com/demo/0.8/app_2_onboarding_notifications.png) ![The last page of the onboarding: a dark green cell with a check mark and the number 3, the title You are all set, and the button Get started. The background has a green tint, and Skip is gone.](https://doc.saymyframe.com/demo/0.8/app_3_onboarding_ready.png) These are the pages of an app with [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md), whose step asks for the permission to show notifications on a page between the two of the module. ## What it adds to the app Three files in `lib/features/onboarding/`: | File | What it holds | | --- | --- | | `onboarding_screen.dart` | `OnboardingScreen`, which shows the pages one at a time, with Skip, the marks and the button around them. | | `onboarding_pages.dart` | The pages: the list that `onboardingPages()` returns, the widget `OnboardingPage`, and `OnboardingPageScope`, which tells a page how far the pages are turned. | | `onboarding_status.dart` | `onboardingStatus`, which knows whether the user has finished the onboarding. | Whichever module provides it, the onboarding screen role adds `lib/core/onboarding/onboarding_steps.dart`, with the class `OnboardingStep` and `appOnboardingSteps`, the steps that the modules of the app add to the onboarding. The list is empty in an app whose modules add none. The module gives the roles of the app what they need to run the onboarding: | Role | What the module gives it | | --- | --- | | Router | The route `onboarding.onboarding` at `/onboarding`, and the guard `onboarding.firstRun` of the stage `welcome`, which keeps the user in the onboarding until it is finished. | | Onboarding screen | The name of that route, as the screen of the role, so that code which knows only the role finds the onboarding. | | Preferences | The restorer `restoreOnboarding`, which reads before the first frame whether the onboarding is finished. The key is `onboarding.completed`. | | Localization | Its six texts, in English and in Ukrainian. In an app without a module that provides the localization, the screen shows them in English. | The module adds no package and no asset to the app: the picture of a page is drawn in code. The page that the user sees is the state of a `PageController` in the screen, so the onboarding works with any module that manages state, or with none. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "Onboarding": that no code navigates to the onboarding or away from it, where its pages and its steps are and what the screen keeps around them, that the animations of a page end, how code finishes the onboarding and starts it again, and what a test of another screen does first. The onboarding screen role writes the section "Onboarding screen": what a step is, how to add one, and that skipping the onboarding skips its steps. ## What the screen shows The cell of the first page has the symbol of the app, as an element has one. `smf create` makes it from the name of the app: the first letter of its first word and the first letter of its second word, `Ma` for `my_app`, or the first two letters of a name of one word, `No` for `notes`. The cell of the last page has an icon on the primary color. The number in the corner of a cell is the place of its page. | | | | --- | --- | | Colors and fonts | The screen takes its colors and its text styles from the theme of the app, in its light and in its dark mode, so it follows a theme of your own. It names no font but the monospaced one of the device, for the number in a cell. | | Motion | When a page is first shown, its cells come in one after another. While the pages turn, by a swipe or by Next, the cells move at different speeds, the texts fade, the background blends into the color of the last page, and the marks follow. Each of these animations ends, so a widget test that waits for the screen with `pumpAndSettle()` returns. | | Less motion | On a device that asks for less motion, the cells are there at once, and Next shows the next page without the turn. The button of a step takes no tap while its action runs, instead of spinning. | | Large text | A page scrolls when it is too small for what it shows, as with a large text size on a small phone. Skip grows with the text size of the device, but the labels of the buttons below the pages grow only by half, so that the pages keep some room on a small phone. The title of a page is large already, so it grows only by half too. Titles, the texts of the pages and the labels of the buttons break between their words and never inside one, also on the pages of the steps: a text whose longest word would not fit is only as large as that word allows. The letters and the number in a cell keep their size, since they are part of the picture. | | Screen readers | A screen reader announces the title of each page as a header and passes over the picture and the marks. | ## The screen never navigates `onboarding` is a feature with a [guard of routes](https://doc.saymyframe.com/concepts/guards.md). While it is not finished, the router shows `/onboarding` in place of every other location: the one the app starts on, a link from the platform, and each `go()`, `push()` and `replace()`. So nothing navigates to the onboarding, and the screen navigates nowhere. Skip and Get started only change what the guard reads. This is what the button below the pages does, in an app with `gen_l10n`: ```dart title="lib/features/onboarding/onboarding_screen.dart" if (step == null) { onPressed = isLast ? onboardingStatus.complete : _next; label = isLast ? context.l10n.onboardingDone : context.l10n.onboardingNext; } else { // A button that spins keeps its colour and does nothing. onPressed = _running ? (spins ? () {} : null) : () => _run(step); label = step.action(context); } ``` Once the onboarding is finished, the router leaves it for the location that the user asked for, or for the screen that the app starts on. The guard has the stage `welcome`. In an app with another guard that asks who the user is, such as the gate of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), the onboarding comes first, whichever order the modules were named in. On a first launch of such an app, the user goes through the onboarding first. In an app that nobody uses without an account, the sign-in comes after it. Nothing is saved before the user finishes. An app that is closed in the middle of the onboarding starts it from its first page the next time. ## Finish it and start it again `onboardingStatus` in `onboarding_status.dart` is the one status of the app: | | | | --- | --- | | `onboardingStatus.completed` | A `ValueListenable`: whether the user has finished the onboarding. | | `onboardingStatus.complete()` | Finishes the onboarding at once and saves that. The router leaves the onboarding. | | `onboardingStatus.restart()` | Starts the onboarding again at once and saves that. The router shows it in place of the screen that the user is on. | To show the onboarding again, call `restart()` where the user asks for it, such as in the handler of a tap on a row of the settings, and navigate nowhere: ```dart onPressed: onboardingStatus.restart, ``` Once the user finishes the onboarding again, they are back on the screen that they were on. From a page pushed over another screen, they come back to the screen below the pushed pages. Do not navigate to `/onboarding` to show it: the guard decides when the app shows the onboarding. Once the onboarding is finished, a navigation to that route, such as a link, shows the screen that the app starts on, or the screen of another guard of the app while that one does not allow. Only `restart()` shows the onboarding again. Call both functions outside the build of a frame, such as in the handler of a tap, because the router navigates when the status changes. The future of each completes once the status is saved. If the preferences fail to save it, the future completes with their error. The app has left or shown the onboarding by then, and its next launch has what was saved before. ## Steps of other modules A module can add steps to the onboarding without knowing which module shows it: it gives the onboarding screen role an `OnboardingStep`, and the template of the role writes the steps of the app into `appOnboardingSteps`. Two steps come with the built-in modules: | Step | From | Stage | Title | Buttons | Shows while | | --- | --- | --- | --- | --- | --- | | `notifications.permission` | the notifications role, with [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) | `permission` | Turn on notifications | Allow notifications, and Not now | the app has not asked for the permission | | `paywall.offer` | [`paywall`](https://doc.saymyframe.com/modules/paywall.md) | `offer` | Unlock premium | See plans, which shows the paywall over the onboarding, and Not now | the user has no premium access | The steps come in the order of their stages, the permissions before the offers. The steps of one stage come in the order of their modules, and then those of the templates of roles. So in an app with both, the page of the notifications comes before the page of the paywall, whatever the order of the modules: ```dart title="lib/core/onboarding/onboarding_steps.dart" const List appOnboardingSteps = [ OnboardingStep( icon: Icons.notifications_active_outlined, title: _notificationsPermissionTitle, text: _notificationsPermissionText, action: _notificationsPermissionAction, run: step0.allowNotifications, later: _notificationsPermissionLater, showIf: step0.notificationsStepShows, ), OnboardingStep( icon: Icons.workspace_premium_outlined, title: _paywallOfferTitle, text: _paywallOfferText, action: _paywallOfferAction, run: step1.showPaywall, later: _paywallOfferLater, showIf: step1.paywallStepShows, ), ]; ``` The screen reads the list once, when it opens: - It asks each step for its `showIf` then, and leaves out a step that returns `false`. A step that it shows stays while the user is on the onboarding, also once its `showIf` would leave it out. - It shows each step that it kept on an `OnboardingPage` of its own, with the icon of the step in the cell, in the order of the list, before the last page of `onboardingPages()`. - On the page of a step, the button below the pages is the action of the step. A tap calls its `run` once, with the `BuildContext` of the screen, and the button spins in place of its label until the future completes. A step that shows a screen of its own, as the paywall does, pushes it on the navigator at the root of the app, over the onboarding, and its future completes once that screen is closed. Meanwhile the pages stay where they are and the buttons of the step take no tap. Then the screen shows the next page, also when the future fails. The error goes on to the handlers of the errors of the app. - A step with a `later`, such as Not now, has a second button below that one, which shows the next page without the action. In an app with such a step, every page keeps the room of that button, so the pages keep their size while they turn. - A swipe past a step calls no action, and Skip skips the steps too, as it skips the pages. So code that needs what a step does, such as the permission to show notifications, asks for it too and does not rely on the onboarding alone. To add a step of your own, add an `OnboardingStep` to `appOnboardingSteps`; for a step of a module of your own, see [Add a step to the onboarding](https://doc.saymyframe.com/extending/onboarding-steps.md). ## Replace the pages The pages are a list in `onboarding_pages.dart`, in the order the user goes through them. To add, remove or reorder a page, change that list. The screen keeps what is around the pages: Skip, a mark for each page, and the button, which is Get started on the last page of the list. This list has a page of its own between the two of the module: ```dart title="lib/features/onboarding/onboarding_pages.dart" List onboardingPages(BuildContext context) => [ OnboardingPage( symbol: 'Ma', title: 'My App', text: 'Welcome! We are glad you are here.', ), OnboardingPage( icon: Icons.notifications_outlined, title: 'Stay in the loop', text: 'We tell you when something new arrives.', ), OnboardingPage( icon: Icons.check_rounded, title: 'You are all set', text: 'Enjoy the app.', ), ]; ``` A page is any widget. `OnboardingPage` is the one of the module. It takes a title, a text, and a `symbol` or an `icon` for its cell: letters in an outlined cell, or an icon in a cell of the primary color. On every other page the smaller cells are on the other side, so two pages in a row do not look the same. - In an app with a module that provides the localization, the pages read their texts as `context.l10n.onboardingWelcome` and so on, from the texts of the app. Add the texts of your pages there too; see [Languages](https://doc.saymyframe.com/guides/languages.md#add-a-text). The label of the button on the last page is the text `onboardingDone`. - A screen reader announces the title of an `OnboardingPage` as a header, since the page wraps it in `Semantics(header: true)`. Do the same for the title of a page of your own. - Let every animation of a page of your own end. A widget test that waits for the app to settle with `pumpAndSettle()` never returns on a screen that animates without end. ### A page that moves with the pages The screen puts an `OnboardingPageScope` around each page. Its `turned` tells how far the pages are turned away from the page: zero while the page is the one on the screen, up to one once the user has turned on to the next page, and down to minus one before the user has reached it. Its `controller` is the `PageController` of the pages, which notifies while they turn. `OnboardingPage` builds itself from the two, and a page of your own can do the same: ```dart title="lib/features/onboarding/onboarding_pages.dart" @override Widget build(BuildContext context) { final scope = OnboardingPageScope.maybeOf(context); if (scope == null) return _build(context, turned: 0, index: 0); return AnimatedBuilder( animation: scope.controller, builder: (context, _) => _build(context, turned: scope.turned, index: scope.index), ); } ``` `maybeOf` returns `null` for a page that is shown outside the screen of the onboarding, as in a widget test of the page alone. ### See the pages again The app shows the onboarding once for each install. To see it again while you edit the pages, clear the data of the app or install it anew. You can also call `onboardingStatus.restart()` in `main()` after `bootstrap()`, and take the call out once the pages are done. Before `bootstrap()` the call has no lasting effect, because the start-up takes what the preferences have saved. ## In tests A test that starts the app to look at another screen finishes the onboarding before the app starts. Otherwise it sees the onboarding: ```dart SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); await onboardingStatus.complete(); await tester.runAsync(app.main); ``` Before the app opened its preferences, `complete()` changes only memory and saves nothing. The first statement puts the preferences of `shared_preferences` into memory, which every test that starts such an app needs; see [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md#in-tests). ## Choosing it `smf create` asks which module provides the onboarding screen, and offers None as well. To choose this one without the question, here with a start screen: ```bash smf create my_app -m home,onboarding ``` The module requires a router and preferences, and `smf create` adds each when only one module provides it: ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding go_router: the only provider of the router role, which home requires. Adding shared_preferences: the only provider of the preferences role, which onboarding requires. ``` # `settings` Source: https://doc.saymyframe.com/modules/settings | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_settings`](https://pub.dev/packages/smf_settings) | feature | Settings screen | a router | `-m settings` | `settings` is the settings screen of the app: a large title and, below it, the settings that the roles and the modules of the app have, such as the theme mode and the language, in one group on a card. In an app without a setting, the screen has a note for you, the developer of the app, in place of the group. ## What it adds to the app `lib/features/settings/settings_screen.dart` with `SettingsScreen`, and one route for the router role: | | | | --- | --- | | Path | `/` of the feature, so the full path is `/settings` | | Full name | `settings.settings` | | Navigation | `context.nav.settings.settings()` | | Destination | Settings, with the settings icon, in the main navigation when the app has a layout | | Start | Not a start screen; the app starts on it only with `--start /settings` | The module adds no package to the app. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the settings screen role tells under "Settings screen" what an entry is and how to add one. The module adds where its screen is, what it shows with entries and without, and how code opens it in an app without a main navigation. ## The settings A module with a setting gives the settings screen role the widget of its entry, and this module only shows the entries. They come in the order of the role: first the entries of the modules, in the order of the modules, then the entries that the roles of the app add themselves, in the order of the modules that provide those roles. The theme role adds the theme mode, the localization role the language, and the notifications role the permission to show notifications. Among the built-in modules, [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) gives an entry: the row of the account. The screen shows the entries one below the other in one group, a card with a line between each two. The title and the group are in a list, which scrolls. ![The settings screen in the light theme, in English: the title Settings, and one card with the entry Theme, whose segments are System, Light and Dark with Light selected, the row Language with the value English, and the row Notifications with the value Off. Below is the tab bar with Settings selected.](https://doc.saymyframe.com/demo/0.8/app_5_settings.png) ![The settings screen in the dark theme, in Ukrainian: the title, the names of the modes, the rows of the language and of the notifications and the labels of the tabs are in Ukrainian, and Dark is the selected mode.](https://doc.saymyframe.com/demo/0.8/app_8_settings_dark_uk.png) This is the file of the screen in such an app, with [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md) and [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) chosen in that order, without the code of its title and of its frame: ```dart title="lib/features/settings/settings_screen.dart" import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:my_app/core/l10n/l10n.dart'; import 'package:my_app/core/l10n/language_setting.dart' as entry1; import 'package:my_app/core/theme/theme_mode_setting.dart' as entry0; // ... child: ListView( padding: const EdgeInsets.fromLTRB(16, 20, 16, 32), children: [ title, const SizedBox(height: 20), const _Group( children: [entry0.ThemeModeSetting(), entry1.LanguageSetting()], ), ], ), // ... /// The group of the entries of the screen: its [children] one below the /// other on a card, with a line between them. class _Group extends StatelessWidget { const _Group({required this.children}); final List children; @override Widget build(BuildContext context) => Card( clipBehavior: Clip.antiAlias, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ for (final (index, child) in children.indexed) ...[ if (index > 0) const Divider(height: 1, indent: 56), child, ], ], ), ); } ``` The screen imports the file of each entry with a prefix of its own, such as `entry0`, so two entries with the same class name never clash. To add an entry of your own by hand, see [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md#the-settings-screen). [Add a setting](https://doc.saymyframe.com/extending/settings.md) shows how a module gets its entry there. The four entries of the roles are the same with every module that provides those roles: | Entry | What it shows | | --- | --- | | The theme mode | Its title, and three segments below it, System, Light and Dark, each with its icon above its name. See [Theme](https://doc.saymyframe.com/guides/theme.md#the-entry-on-the-settings-screen). | | The language | A row with the choice of the user as its value. A tap opens a sheet with the languages of the app. See [Languages](https://doc.saymyframe.com/guides/languages.md#the-entry-on-the-settings-screen). | | The notifications | A row with the title Notifications, and On or Off, whether the app may show notifications. A tap asks for the permission while the app has not asked, and opens the settings of the system after that. See [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md#the-permission). | | The restore of purchases | A row with the title Restore purchases. A tap restores what the store account bought and shows below the title what it found. See [Purchases](https://doc.saymyframe.com/guides/purchases.md#restore-purchases). | ### An entry that leads to a screen An entry need not change a setting itself. The entry of [`paywall`](https://doc.saymyframe.com/modules/paywall.md), Subscription, tells whether the user has premium access and opens the screen of the subscription. The entry of `sign_in` is a row with the title Account, and below it the email address of the account that the user is signed in to, or Not signed in. A tap opens the screen of the account over the settings screen. This is the screen in an app with `gen_l10n` chosen before `material_theme`, and with `local_notifications`: ![The settings screen in the light theme, in English: one card with the row Account, which shows ada.lovelace@example.com and an arrow, the row Subscription with Not active, then the row Language, the entry Theme, the row Notifications and the row Restore purchases. Below is the tab bar with Settings selected.](https://doc.saymyframe.com/demo/0.8/app_settings_account.png) In an app with `sign_in`, `gen_l10n` and `material_theme`, chosen in that order, the group has three entries, that of the module first: ```dart title="lib/features/settings/settings_screen.dart" const _Group( children: [ entry0.AccountSetting(), entry1.LanguageSetting(), entry2.ThemeModeSetting(), ], ), ``` The entry reads who is signed in from the state manager of the app and passes it to a row that keeps nothing. This is the entry with `bloc`: ```dart title="lib/features/sign_in/account_setting.dart" class AccountSetting extends StatelessWidget { /// Creates the entry. const AccountSetting({super.key}); @override Widget build(BuildContext context) { final session = context.watch().state; return AccountSettingRow( signedIn: session is AccountSession, email: session is AccountSession ? session.email : null, onTap: () => context.nav.signIn.account().push(), ); } } ``` It follows the rule of every entry: a `const` constructor that requires no arguments, and its state from its owner. See [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#the-account). The title of the screen is a text of the module, Settings in English and ΠΠ°Π»Π°ΡˆΡ‚ΡƒΠ²Π°Π½Π½Ρ in Ukrainian, and the label of its tab is the same text. In an app without a module that provides the localization, both are in English. A screen reader announces the title as a header. A title that is too long for its line, as with a large text size, gets smaller and stays on one line. ## An app without settings In an app whose modules have no setting, the file has no group. Below the title, the screen shows a note for you: - a picture, a cell with an icon; - "No settings yet", and "A module with a setting adds its entry here. You can add your own in this file."; - the path of the file, `lib/features/settings/settings_screen.dart`. A tap copies it, and a snack bar says so. The note is in English in every app. A module that provides the theme of the app, such as `material_theme`, its texts, such as `gen_l10n`, or its notifications, such as `local_notifications`, brings a setting, and `sign_in` brings the entry of the account. So an app with one of them has the group and never the note. The first entry takes the place of the note; [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md#the-settings-screen) shows the change. The note comes in once, and at once on a device that asks for less motion. On a small phone with a large text size, the title and the note scroll, and the path grows to at most one and a half times its size. ## Opening the screen With a layout, such as [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), the screen is a destination of the main navigation, after the destinations of the features chosen before it. There it has no app bar. Without a layout, nothing that SMF generates opens the screen, and `smf create` warns of that unless the app starts on the screen. That matters most in an app with [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), whose entry of the account is on this screen. Open the screen from your own code, on top of the current screen: ```dart context.nav.settings.settings().push() ``` Shown that way, the screen has an app bar with a back button, which leads back. `go()` would replace the stack with the settings screen alone, and nothing would lead back from it. The screen is not a start screen, so an app whose only screen is this one starts on the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#the-fallback-start-screen), even with a layout. The fallback screen is outside the main navigation, so nothing opens the settings screen there either. Add a feature with a start screen, such as [`home`](https://doc.saymyframe.com/modules/home.md). ## Requirements As a feature, `settings` requires the router role, whichever module provides it. The screen has no state of its own, since each entry keeps the state of its setting, so `settings` works with any module that manages state or with none. Whichever module provides the settings screen, its route shows the screen, and the screen shows every entry once, one below the other, in a list that scrolls. SMF's CI checks this in running apps with the role; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it `smf create` asks which module provides the settings screen, and offers None as well. The module provides a role, so it is not among the features to pick. To choose it without the question, here with a start screen and tabs at the bottom: ```bash smf create my_app -m home,settings,bottom_tabs ``` No module of this app has a setting, so its screen shows the note. With `material_theme` or `gen_l10n` in `-m` too, it shows the group. # `sign_in` Source: https://doc.saymyframe.com/modules/sign-in | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_sign_in`](https://pub.dev/packages/smf_sign_in) | feature | none | a router, sign-in, a settings screen, a state manager | `-m sign_in` | `sign_in` is the screens of sign-in. On three of them a user signs in to an account with an email address and a password, creates an account, and asks for the message that resets a password. The sign-in and the sign-up also have a button for each way to sign in that another module adds, such as [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) or [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md). The fourth is the screen of the account, where the user signs out or deletes the account, and the settings screen gets an entry that leads to it. The module keeps no accounts. It requires a module that provides sign-in, such as [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md), and reaches it only through `appSession`, the session of the app. So the screens are the same whichever module that is. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md) describes the session and the sign-in mode of the app. ## The screens | Screen | Path | What it has | | --- | --- | --- | | Sign-in | `/sign_in` | A field for the email address and one for the password, Forgot password?, the button Sign in, and Create account. | | Sign-up | `/sign_in/sign_up` | The same two fields for a new account, the button Create account, and I already have an account. The device may suggest a password and offer to keep it. | | Password reset | `/sign_in/reset_password` | A field for the email address of an account, and the button Send link. Once the message is sent, the screen shows the address that it went to. It says the same whether the address has an account or not, so nobody learns from the app which addresses have one. | The sign-up and the password reset are routes below the sign-in, so each shows over it and its back button leads there. ![The sign-in in the light theme, in English: the cell Ma 5 among the cells of a table, the title Sign in with the line Choose how to sign in to your account. below it, the white buttons Continue with Google and Continue with Apple, then or, the fields Email and Password, Forgot password? below the password field, the button Sign in, and Create account in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png) ![The sign-up: a back button, the title Create account with the line Choose how to create your account. below it, the buttons Continue with Google and Continue with Apple, then or, the fields Email and Password, the button Create account, and I already have an account in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_up.png) ![The password reset: a back button, the title Reset password, a line that says a link to set a new password will be sent, the field Email, and the button Send link.](https://doc.saymyframe.com/demo/0.8/app_reset_password.png) These are the screens of an app with [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md), whose buttons the sign-in and the sign-up show above the form; see [other ways to sign in](#other-ways-to-sign-in). Each screen shows the cell of the app, with the symbol that SMF makes from its name, `Ma` for `my_app`, next to the cells of a table that light up one after another. Below it are a title, a line of text and the form. A field has its label above it, and the password field has a button that shows the password. The button that submits is as wide as the form. ![The sign-in in the dark theme, in Ukrainian: the title Π’Ρ…Ρ–Π΄, the white buttons ΠŸΡ€ΠΎΠ΄ΠΎΠ²ΠΆΠΈΡ‚ΠΈ Π· Google and ΠŸΡ€ΠΎΠ΄ΠΎΠ²ΠΆΠΈΡ‚ΠΈ Π· Apple, the fields Π•Π»Π΅ΠΊΡ‚Ρ€ΠΎΠ½Π½Π° ΠΏΠΎΡˆΡ‚Π° and ΠŸΠ°Ρ€ΠΎΠ»ΡŒ, the light button Π£Π²Ρ–ΠΉΡ‚ΠΈ, and Π‘Ρ‚Π²ΠΎΡ€ΠΈΡ‚ΠΈ Π°ΠΊΠ°ΡƒΠ½Ρ‚ in green below it.](https://doc.saymyframe.com/demo/0.8/app_sign_in_dark_uk.png) ![The sign-in after a tap on Sign in with ada as the address and no password: both fields have a red line around them, with Enter a valid email address. below the first and Enter a password. below the second.](https://doc.saymyframe.com/demo/0.8/app_sign_in_mistakes.png) | | | | --- | --- | | While a call is on its way | The button that submits spins, and the form takes no input. A field takes no typing, though one that has the focus keeps it, and the actions of the screen take neither a tap nor a key. | | A failure | It shows above the button, in a text of its own for each reason, such as a wrong password or no connection. | | Colors and fonts | The fields, the buttons and the cards are those of the theme of the app, in its light and in its dark mode. The buttons of the [other ways to sign in](#other-ways-to-sign-in) are the exception: they are white with a black label and icon in both modes. The screens give a field no color, border or padding of their own, so for another look of the fields, change [the theme](https://doc.saymyframe.com/modules/material-theme.md#change-the-look). The cells of the picture take their colors from the theme too. | | The second way on | The action that leads to the other screen, Create account on the sign-in and I already have an account on the sign-up, is a text button of the theme in the accent of the color scheme, `colorScheme.secondary`. | | Motion | The parts of a screen rise in one after another, once. On a device that asks for less motion they are there at once, and a busy button is disabled and keeps its label. | | Large text | A screen scrolls when it is too small for what it shows, as with the keyboard open or with a large text size on a small phone. A title grows only by half. A title and the label of a button break between their words and never inside one. The letters in the cell keep their size, since they are part of a picture. | | Screen readers | A screen reader announces the title as a header, each field by its label, and a failure when it appears. | ## Other ways to sign in A module of a way to sign in, such as `google_sign_in` or `apple_sign_in`, gives the auth role its label, its icon and the platforms that it works on, and the role lists it in `appSignInMethods`; see [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). The module adds nothing to this feature for it. The sign-in and the sign-up show a button for each way that works on the platform of the app, from `signInMethodsHere()`: - The buttons are above the form, in the order of the modules, with "or" between them and the form. With buttons, the line of text below the title asks how to sign in: "Choose how to sign in to your account." on the sign-in, and "Choose how to create your account." on the sign-up. An app without such a module shows the form alone. - Each button is as wide as the form and as tall as the button that submits. Its label has the text style of that button in the medium weight. - The button is white with a grey hairline, and its label and icon are black, in the light theme and in the dark one. The brand guidelines of identity providers allow these colors for a custom button on any background, and a logo in its own colors, as the "G" of Google, stays on white. The icon is 20 logical pixels and keeps its size at a large text size. - A screen reader reads each button as one button with its label. ![The sign-in in the dark theme, in English: the buttons Continue with Google and Continue with Apple stay white with a black label and icon on the dark screen, above or and the dark fields Email and Password.](https://doc.saymyframe.com/demo/0.8/app_sign_in_dark.png) A tap asks the way to sign in for a credential, as with the sheet of its identity provider, and gives it to `appSession.signInWith`. An anonymous user keeps the id. While the call is on its way, the button spins and nothing else on the screen takes a tap. A failure shows below the buttons, in the texts of the reasons of a failure, which have one for `credentialInUse` and one for `accountExistsWithOtherMethod` too. When the user closes the sheet, the screen is as it was before the tap. The state of both variants calls `continueWithMethod()` of `sign_in_state.dart`, which awaits `credential()` of the way to sign in and gives the credential to the session. ## The account The screen of the account is at `/sign_in/account`. It shows the email address of the account that the user is signed in to, the button Sign out, and the action Delete account. Delete account is a text button in the color that the theme has for an error. It asks first, in a sheet over the page: the sheet says that the deletion cannot be undone, and has the buttons Delete and Cancel. The screen closes the sheet before it deletes the account. A provider of sign-in may refuse to delete an account whose user signed in long ago. The screen then stays, with a text that tells the user to sign out and sign in again. Some ways to sign in, such as Sign in with Apple, ask the user again before a deletion, so that the provider of sign-in can revoke their tokens. When the provider cannot revoke them, it fails with `notConfigured`, and the screen says "Your account cannot be deleted right now. Try again later." When the user confirms with another account, it fails with `invalidCredentials`, and the screen says "That is a different account. Confirm the deletion with the account you are signed in to." The texts of a sign-in would not tell the user what happened. A user who closes the sheet of the identity provider deletes nothing. The settings screen of the app has an entry for the account, a row with the title Account. Below the title it shows the email address of the account, or Not signed in. A tap on it opens the screen of the account over the settings screen. ![The settings screen in the light theme, in English: one card with the row Account, which shows ada.lovelace@example.com and an arrow, the row Subscription with Not active, then the row Language, the entry Theme, the row Notifications and the row Restore purchases. Below is the tab bar with Settings selected.](https://doc.saymyframe.com/demo/0.8/app_settings_account.png) ![The screen of the account: a back button, the title Account, the line You are signed in to this account:, a card with ada.lovelace@example.com, the button Sign out, and Delete account in red below it.](https://doc.saymyframe.com/demo/0.8/app_account.png) ![The sheet that asks before a deletion, over the dimmed screen of the account: the title Delete your account?, a line that says the deletion cannot be undone, a red button Delete, and Cancel.](https://doc.saymyframe.com/demo/0.8/app_account_delete.png) The route of that screen needs an account. So for a user without one, in an app that everyone may use, the router opens the sign-in over the settings screen first, and shows the screen of the account once the user is signed in. In an app that signs in anonymous users, such a user creates the account on the sign-up and keeps everything that the anonymous user had. ### Where the entry is within reach The entry is within reach where the settings screen is. A module that provides the main navigation of the app, such as [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md), shows the settings screen among its destinations. In an app without a main navigation, no screen leads to the settings screen, and `smf create` warns of that unless the app starts on it. A screen of yours then opens it, or opens the account directly: ```dart context.nav.settings.settings().push() ``` ```dart context.nav.signIn.account().push() ``` ## What shows the screens The screens neither close themselves nor navigate once the user is signed in or out. The module declares two [guards of the routes](https://doc.saymyframe.com/concepts/guards.md), and the router shows the sign-in and leaves it by what they say. These are the guards of an app with the module, as the router role lists them: ```dart title="lib/core/router/app_router.dart" final List routeGuards = [ RouteGuard( 'sign_in.gate', allows: guard0.signInAllowsApp(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, ), RouteGuard( 'sign_in.hasAccount', allows: guard0.signInHasAccount(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, routes: const {'sign_in.account'}, ), ]; ``` | Guard | What it reads | What the router does while it does not allow | | --- | --- | --- | | `sign_in.gate` | `appSession.allowsApp` | It shows the sign-in in place of every other screen. | | `sign_in.hasAccount` | `appSession.hasAccount` | For a request for a route that needs an account, such as the screen of the account, it opens the sign-in over the page that the user is on. The rest of the app stays open, and back returns to that page. | Which of the two keeps a user out is up to the [sign-in mode](https://doc.saymyframe.com/guides/sign-in.md#the-mode) of the app, which `smf create` asks for. The code of the module is the same in every mode. | Mode | What the user sees | | --- | --- | | `required` | The sign-in in place of every screen, until the user is signed in to an account. After a sign-out, the sign-in again. | | `guest`, `anonymous` | The app. The sign-in opens over a page when the user asks for a route that needs an account, or when a screen of the app opens it. After a sign-out on the screen of the account, the router closes that page and the user is on the page below it. | - Once the user is signed in to an account, both guards allow, and the router leaves the sign-in. From then on a navigation to one of the three routes, such as a link, shows the screen that the app starts on. - After a sign-out in an app that needs an account, the next user starts on the screen that the app starts on, wherever the last user was. Neither guard brings the user back. - Both guards have the stage `identity`. In an app with a guard of a first launch, such as that of [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md), that one comes first, whichever order the modules were named in. - A link to one of the three routes shows its screen while the user has no account. In an app that everyone may use, the router shows that screen over the screen that the app starts on, so that back leads into the app. In an app that everyone may use, a screen of yours may also offer to sign in. Open the sign-in with `push()`, so that back leads back: ```dart context.nav.signIn.signIn().push() ``` In an app that needs an account, no code navigates to the sign-in: the gate shows it. ## What it adds to the app The module generates its files in `lib/features/sign_in/`. The look of the screens is the same in every app: | File | What it holds | | --- | --- | | `sign_in_view.dart`, `sign_up_view.dart`, `reset_password_view.dart` | `SignInView`, `SignUpView` and `ResetPasswordView`. A view is a plain Flutter widget: it keeps its form, gets the state of its call, and takes callbacks for what the user asks for. | | `account_view.dart` | `AccountView`, the look of the screen of the account, `confirmDeleteAccount()`, which asks in the sheet, and `deletionFailureText()`, the texts of a deletion that failed. | | `account_setting_row.dart` | `AccountSettingRow`, the row of the entry on the settings screen. | | `sign_in_page.dart` | `AuthPage`, the frame of a screen: the cell, the title, the line of text, and the entrance. | | `sign_in_widgets.dart` | The fields, the button that submits, `OtherScreenAction` for the way to the other screen, `DestructiveAction` for what cannot be undone, and `FailureMessage`. `SignInMethods` and `SignInMethodButton` are the buttons of the ways to sign in, and `signInMethodsHere()` lists the ways that work on the platform. Also `authFailureText()`, which has a text for every reason of a failure, and `WholeWords`, the text of a title or of the label of a button, which keeps its words whole. | | `sign_in_state.dart` | `AuthActionState`, `ResetPasswordState` and `AccountState`, the values of the state of a screen, and `continueWithMethod()`, which signs in with a way to sign in, for the state of the sign-in and of the sign-up. | | `sign_in_guards.dart` | `signInAllowsApp()` and `signInHasAccount()`, the functions of the two guards. | What keeps the state of a screen depends on the module that manages state in the app, so the module has a variant for each: | | With [`bloc`](https://doc.saymyframe.com/modules/bloc.md) | With [`riverpod`](https://doc.saymyframe.com/modules/riverpod.md) | | --- | --- | --- | | The state of each screen | A cubit: `SignInCubit`, `SignUpCubit`, `ResetPasswordCubit` and `AccountCubit`, each in a file of its name, such as `sign_in_cubit.dart`. | A provider that lasts as long as its screen: `signInProvider`, `signUpProvider`, `resetPasswordProvider` and `accountProvider`, each with its `Notifier` in a file such as `sign_in_notifier.dart`. | | Where the state gets the session | `sign_in_composition.dart` creates the cubits with `appSession`. | `appSessionProvider` in `session_provider.dart`. | | Who uses the app, for a widget | `SessionCubit` in `session_cubit.dart`, which the module puts around the root of the app. | `sessionProvider` in `session_provider.dart`. | | Two pages of one screen open at once | Each has a cubit of its own. | A provider is one for the app, so both show the same state. | The screens are `SignInScreen`, `SignUpScreen`, `ResetPasswordScreen` and `AccountScreen`, in `sign_in_screen.dart`, `sign_up_screen.dart`, `reset_password_screen.dart` and `account_screen.dart` in both variants. `AccountSetting` in `account_setting.dart` is the entry of the settings screen. The module gives the roles of the app what they need to show the screens: | Role | What the module gives it | | --- | --- | | Router | The routes `sign_in.signIn`, `sign_in.signUp` and `sign_in.resetPassword`, the route `sign_in.account`, which asks for the condition `AuthRole.account`, and the two guards. None of the routes is a destination, and the app cannot start on them. | | Settings screen | The entry `AccountSetting`. | | Localization | Its 49 texts, in English and in Ukrainian. In an app without a module that provides the localization, the screens show them in English. | | App entry | With `bloc`, the `BlocProvider` of the `SessionCubit` around the root of the app. | The module adds the package of the state manager to the app, in the version that the module of that state manager asks for, and no other package. It registers nothing in a DI container and needs none. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "Sign-in": where the screens are and what shows them, which files are the look and which the state, where a failure gets its text, what a widget test minds while a call is on its way, and, by the variant, where the state of a screen is. ## Look and state A screen only gives its view the state. This is the screen of the sign-in with `bloc`: ```dart title="lib/features/sign_in/sign_in_screen.dart" class SignInScreen extends StatelessWidget { /// Creates the screen. const SignInScreen({super.key}); @override Widget build(BuildContext context) => BlocProvider( create: (_) => createSignInCubit(), child: BlocBuilder( builder: (context, state) => SignInView( busy: state.busy, failure: state.failure, onSubmit: (email, password) => context.read().signIn( email: email, password: password, ), onCreateAccount: () => context.nav.signIn.signUp().push(), onForgotPassword: () => context.nav.signIn.resetPassword().push(), ), ), ); } ``` With `riverpod`, the same screen watches a provider, and `SignInView` and the other files of the look are the same: ```dart title="lib/features/sign_in/sign_in_screen.dart" class SignInScreen extends ConsumerWidget { /// Creates the screen. const SignInScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final state = ref.watch(signInProvider); return SignInView( busy: state.busy, failure: state.failure, onSubmit: (email, password) => ref .read(signInProvider.notifier) .signIn(email: email, password: password), onCreateAccount: () => context.nav.signIn.signUp().push(), onForgotPassword: () => context.nav.signIn.resetPassword().push(), ); } } ``` Neither screen navigates once the user is signed in, and the state does not tell the screen that the sign-in succeeded. The state signs in through `appSession`: ```dart title="lib/features/sign_in/sign_in_cubit.dart" Future signIn({required String email, required String password}) async { if (state.busy) return; _calling = true; emit(const AuthActionState(busy: true)); try { await _session.signIn(email: email, password: password); } on AuthFailure catch (failure) { _calling = false; // The user may have left the screen while the call was on its way. if (!isClosed) emit(AuthActionState(failure: failure)); return; } _calling = false; _follow(); } ``` | What happened | The state of the screen | | --- | --- | | A call is on its way. | Busy. It takes no second call. | | The call failed. | Not busy, with the failure. | | A sign-in or a sign-up succeeded. | Busy for as long as the session has the account: the user is signed in then, and the router takes the screen away. When the session has no account again before that, as when code of the app signs the user out at once, the form is back. | | A sign-out or a deletion succeeded, on the screen of the account. | Busy for as long as the session has no account. The screen is back when the session has one again. | The sign-up calls `appSession.signUp()` in every mode of the app. What an anonymous user gets is up to the session, which gives that user the account. ## Who uses the app, in a widget The module also gives the widgets of the app the session, so that a widget rebuilds when the user signs in or out. Both ways give an `AppSession`: nobody, an anonymous user, or the user of an account with its email address. With `bloc`, the root of the app provides a `SessionCubit`, which follows `appSession`: ```dart title="lib/main.dart" runApp(BlocProvider(create: (_) => createSessionCubit(), child: const App())); ``` ```dart final session = context.watch().state; ``` With `riverpod`, a widget reads `sessionProvider`: ```dart final session = ref.watch(sessionProvider); ``` The entry of the settings screen reads the session this way: ```dart title="lib/features/sign_in/account_setting.dart" @override Widget build(BuildContext context) { final session = context.watch().state; return AccountSettingRow( signedIn: session is AccountSession, email: session is AccountSession ? session.email : null, onTap: () => context.nav.signIn.account().push(), ); } ``` ## Make the screens yours - For another look of a field, a button or a card, change the theme of the app. The files of the feature give a field no color, border or padding. - The texts are texts of the app. With a module that provides the localization, change them where that module keeps the texts; see [Languages](https://doc.saymyframe.com/guides/languages.md). Every reason of a failure has a text of its own, in `authFailureText()` of `sign_in_widgets.dart`. - When sign-in is not set up at the provider, the user reads only that sign-in is unavailable. What is wrong is in the `developerHint` of the failure, which `FailureMessage` shows below the text in debug mode only. - The title of a page and the label of each button are a `WholeWords` and not a `Text`. Use it for the label of a button that you add to the feature too. - Keep the screens from closing themselves and from navigating after a sign-in or a sign-out. The router does both when the guards change; see [what a screen does](https://doc.saymyframe.com/concepts/guards.md#what-a-screen-does). ## In tests | A test of | Does this | | --- | --- | | the state of a screen, with `bloc` | It creates the cubit with an `AppSessionController` of its own, since a cubit takes the session through its constructor. | | the state of a screen, with `riverpod` | It overrides `appSessionProvider` with an `AppSessionController` of its own. | | a way to sign in on the sign-in or the sign-up | `continueWith()` of the state takes any `SignInMethod`, so the test gives it one whose `credential` it scripts, such as one that returns `null` as a closed sheet does. | | a screen while its call is on its way | It shows frames with `pump()`. The button that submits spins for as long as the call takes, so `pumpAndSettle()` returns only once the call has ended. | | the app, started in real time, as with `tester.runAsync()` | It starts the app once in its file. A page starts its entrance when it is first built, and a second start in the same file fails an assertion of Flutter in that animation. | In the mode `required`, a test that starts the app to look at another screen sees the sign-in unless an account is signed in. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#in-tests) shows how a test gives the app an account before it starts, and how it scripts what the provider answers. ## Choosing it `smf create` asks which features the app has. To choose this one without the question, here with a start screen, BLoC and tabs at the bottom: ```bash smf create my_app -m home,sign_in,bloc,bottom_tabs ``` The feature requires a router, a module that provides sign-in, a settings screen and a module that manages state. `smf create` adds each when only one module provides it: ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding go_router: the only provider of the router role, which home requires. Adding firebase_auth: the only provider of the authentication role, which sign_in requires. Adding firebase_core: a dependency of firebase_auth. Adding settings: the only provider of the settings screen role, which sign_in requires. ``` Two modules manage state, so the run asks which one, or takes it from `-m`. A run without a terminal stops without one: ```text Several modules provide the state management role, which sign_in requires: bloc, riverpod. Add one of them to -m. ``` The tabs of that app lead to the start screen and to the settings screen, where the entry of the account is. The app signs in with Firebase Authentication, so it needs a Firebase project before it runs; see [Firebase](https://doc.saymyframe.com/guides/firebase.md). # `paywall` Source: https://doc.saymyframe.com/modules/paywall | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_paywall`](https://pub.dev/packages/smf_paywall) | feature | none | purchases, values in `.env`, a router, a state manager | `-m paywall` | `paywall` is the screen that sells the premium access of the app, and the screen that shows it to a user who has it. The paywall shows the plans of the current offer, each with the price that the store gives, and buys the plan that the user selects. The screen of the subscription shows the plan of the user, when it renews or ends, and the way to the page of the store where the user manages it. The module keeps no purchases. It requires a module that provides the purchases role, such as [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md), and reaches it only through `appPurchases`, so the screens are the same whichever module that is; see [Purchases](https://doc.saymyframe.com/guides/purchases.md). In an app with a settings screen, it adds a row that leads to the screen of the subscription. In an app with an onboarding, it adds a step that offers premium access. ## The screens | Screen | Route | Path | What it shows | | --- | --- | --- | --- | | `PaywallScreen` | `paywall.paywall` | `/paywall` | The plans of the current offer and the button that buys the selected one, with what the stores ask a paywall to show. | | `SubscriptionScreen` | `paywall.subscription` | `/paywall/subscription` | The plan of the user, when it renews or ends, or that the access is for good, and a button to the page of the store where the user manages the plan. | From the top, the paywall shows: - a close button, outside what scrolls, whenever a page below is there to go back to; - a card in the colours of Say My Frame, with the app as a cell of the periodic table and `Premium` above its name. The symbol and the number in the cell come from the name of the app, as on the card of the [start screen](https://doc.saymyframe.com/modules/home.md). On the right of the card the cells of a table light up one after another, and the last one shows the icon of premium access; - three benefits, each with a check: "Every feature of the app, without limits", "New features as soon as they arrive" and "Support for the work on the app"; - a card for each plan, in the order of the provider of purchases. A card shows the name of the plan, such as Yearly, its price with its period, such as `$29.99 / year`, and its free trial or lower price at first, such as `1 week free`. A yearly plan that costs less than twelve months of a monthly plan in the same currency has the badge Best value. The paywall selects the first yearly plan, or else the first plan. Grey cards stand in while the plans load; - the button that buys the selected plan: Start free trial for a plan with a free trial, Buy for a plan paid once, and Subscribe for any other plan. Below it, for a plan with an intro offer, what the plan costs after it, such as `1 week free, then $29.99 / year`; - the terms of the store of the platform, and the links Restore purchases, Terms of Use and Privacy Policy; - in a debug build, a note for you, which names the keys of `.env` that are empty and what the provider of purchases says is missing, such as its key. A tap on a key copies it. On a phone with room for it, the button and what follows it stay in sight at the bottom while the plans scroll. On a small phone, or with a large text size, they scroll with the rest, so that the plans keep their room. ![The paywall over the settings screen, in the light theme, in English: a close button, the dark green card with the cell Ma 5, Premium and My App, three benefits with checks, the selected plan Yearly with the badge Best value, $29.99 / year and 1 week free, the plan Monthly with $4.99 / month, and at the bottom the button Start free trial with 1 week free, then $29.99 / year below it.](https://doc.saymyframe.com/demo/0.8/app_paywall.png) ![The same paywall in the dark theme, in Ukrainian: the benefits, the plans Π©ΠΎΡ€ΠΎΠΊΡƒ with the badge ΠΠ°ΠΉΠ²ΠΈΠ³Ρ–Π΄Π½Ρ–ΡˆΠ΅ and Щомісяця, and the light button Π‘ΠΏΡ€ΠΎΠ±ΡƒΠ²Π°Ρ‚ΠΈ Π±Π΅Π·ΠΊΠΎΡˆΡ‚ΠΎΠ²Π½ΠΎ.](https://doc.saymyframe.com/demo/0.8/app_paywall_dark_uk.png) When the plans do not load, the paywall says that they are not available right now and offers Try again, and a debug build shows the hint of the provider in its note. A call that fails shows a text of the app for its reason above the button, such as "No connection. Check the internet and try again.", with the `developerHint` below it in a debug build. A payment that waits for an approval, such as one that a parent approves, says so, and the access arrives later without another call. A restore that finds nothing says "No purchases to restore." The screen of the subscription shows the same card with the badge Unlocked, a thank you, the plan and the date on which it renews, ends or ends its free trial, or Lifetime access for a plan paid once. Its button, Manage subscription, opens `manageUrl`, the page of the store where the user manages or cancels the plan, with "Cancel anytime in the store where you subscribed." below it. It has no restore: the paywall and the row of the purchases role on the settings screen restore. ![The screen of the subscription after the purchase of the yearly plan: a back button, the title Subscription, Thank you for your support. Premium is unlocked., the card with the badge Unlocked, the plan Yearly and the date on which its trial ends, and the button Manage subscription with Cancel anytime in the store where you subscribed. below it.](https://doc.saymyframe.com/demo/0.8/app_subscription.png) ## Nothing navigates after a purchase The route of the screen of the subscription asks for the condition `PurchasesRole.premium`. The module declares the guard `paywall.hasPremium`, which stands for that condition: its function, `paywallHasPremium()` of `lib/features/paywall/paywall_guards.dart`, returns `appPurchases.hasPremium`, and its target is the paywall. See [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md). So no screen of the paywall closes itself or navigates after a purchase or a restore: 1. A request for a route that needs premium access, from a user without it, opens the paywall over the page that the user is on. The request waits. 2. The user buys a plan, or restores one. The access changes. 3. The router closes the paywall and shows what was asked for: a `push()` shows the route over the page and completes with the value of its page. The close button and back drop the request, and its `push()` completes with `null`. When the access ends, as when a subscription expires, the router closes a page that needs it. To sell from a button of your own, navigate to a route that needs premium access: ```dart await context.nav.paywall.subscription().push(); ``` To keep a screen of your own for users with premium access, list `PurchasesRole.premium` in the `conditions` of its route in a module of yours, or add the full name of its route to the `routes` of `paywall.hasPremium` in `routeGuards` of `lib/core/router/app_router.dart`. The routes below such a route need the access too. Code may also push `/paywall` itself for a user without the access, and the router closes it once the user has it. Do not push `/paywall` for a user with premium access: the flow of the guard is over then, so the router shows the screen that the app starts on. The guard has the stage `identity`, since premium access depends on who the user is, and it brings the user back once it allows again. In an app with [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md), the onboarding comes first. In an app with [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), the router asks the gate of the sign-in before this guard; see [Guards of routes](https://doc.saymyframe.com/concepts/guards.md#the-order-of-the-guards). ## The row of the settings screen In an app with a [settings screen](https://doc.saymyframe.com/modules/settings.md), the module gives it `SubscriptionSetting`: the row Subscription, with Active or Not active below its title. A tap asks for the screen of the subscription, so for a user without premium access the router opens the paywall over the settings screen first. The purchases role gives the same screen the row Restore purchases. In an app without a settings screen, open the screen of the subscription from a screen of yours with `context.nav.paywall.subscription().push()`, so that the user finds where to cancel. ## The step of the onboarding In an app with an onboarding, such as [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md), the module gives the onboarding screen role the step `paywall.offer`. It has the stage `offer`, so the onboarding shows it after the steps that ask for permissions, such as the one of the notifications. The onboarding shows the step while the user has no premium access, and a new onboarding leaves it out once the user has it. | | | | --- | --- | | Icon | `Icons.workspace_premium_outlined` | | Title | Unlock premium | | Text | Get every feature of the app, and the new ones as they arrive. | | Button | See plans | | Second button | Not now, which goes on without the paywall | The page shows no price: the prices are on the paywall. See Plans calls `showPaywall()` of `lib/features/paywall/paywall_step.dart`, which pushes `PaywallScreen` on the navigator at the root of the app, over the onboarding. While the onboarding is on, a guard of the routes may keep the router from showing `/paywall`, so the paywall there is a route of its own, without a page of the router. The router does not close such a route, so `showPaywall()` closes it itself once the user has premium access, also from below a dialog over it. The onboarding goes on to the next page once the paywall is closed, whether by the close button, by back or after a purchase. This is the one place where code of the module, not the router, closes the paywall. ## Whose purchase it is In an app with sign-in, a user may buy before signing in, such as from the step of the onboarding in an app that nobody uses without an account. A sign-up keeps the purchase in the new account. A sign-in to an account that exists already leaves the purchase with the user of the device until the user restores it. See [Purchases](https://doc.saymyframe.com/guides/purchases.md#whose-purchases-they-are). ## What the stores ask of a paywall The App Store and Google Play ask a screen that sells a subscription to show certain things. The paywall shows them: | The stores ask for | The paywall shows | | --- | --- | | The name of the plan, its period and what the user gets | The name of each plan, its period, and the three benefits | | The full price of each period, shown more clearly than any other price | The price that the store gives, the largest text of its card. A yearly plan is never shown by its price per month. | | For a free trial or a lower price at first, how long it lasts and the price after it | The intro offer on the card, and what the plan costs after it right below the button | | That the plan renews until the user cancels, and how to cancel | The terms of the store below the button: on iOS that the payment is charged to the Apple Account and that the user cancels at least 24 hours before the period ends, in the settings of the App Store; on Android that the user cancels anytime in Google Play, under Payments & subscriptions | | A way to restore purchases | The link Restore purchases | | Links to the terms of use and the privacy policy | The links Terms of Use and Privacy Policy, from `.env` | | A visible way to close the screen without buying | The close button, which stays in sight at the top whenever a page is below the paywall. A paywall that `go()` shows alone has none, so push `/paywall` rather than go to it. | A plan paid once says "One-time payment. No subscription." in place of the terms of renewal. ## Values in .env The module gives the role of the values in `.env` two keys: | Key | Getter | What goes there | | --- | --- | --- | | `PAYWALL_TERMS_URL` | `AppEnv.paywallTermsUrl` | The address of your terms of use | | `PAYWALL_PRIVACY_URL` | `AppEnv.paywallPrivacyUrl` | The address of your privacy policy | The App Store asks a paywall to link to both. While a value is empty, or is no web address with `https` or `http` and a host, the paywall leaves its link out. The exception is the terms of use on iOS, which then lead to the [standard license agreement of Apple](https://www.apple.com/legal/internet-services/itunes/dev/stdeula/). A debug build names the empty keys in its note for you. Publishing the pages and filling in the keys is a step by hand of the app, with a [click-by-click guide](https://doc.saymyframe.com/setup/paywall-legal-pages.md). An address with an anchor, such as `https://example.com/terms#refunds`, goes into double quotes, since `#` after a plain value starts a comment; see [Values in .env](https://doc.saymyframe.com/guides/env.md#write-a-value). The links open outside the app, in the browser, through `url_launcher`. ## What it adds to the app The look of the screens is the same in every app, in `lib/features/paywall/`: | File | What it holds | | --- | --- | | `paywall_view.dart` | `PaywallView`, the look of the paywall. | | `subscription_view.dart` | `SubscriptionView`, the look of the screen of the subscription. | | `paywall_widgets.dart`, `paywall_card.dart` | The widgets of both, among them `PaywallWords`, a text that keeps its words whole, and the card in the colours of Say My Frame. | | `paywall_state.dart` | `PaywallState`, the state of the paywall: the plans or why they did not load, the selected plan, the call on its way and what the last call ended with. Also which plan is selected first and which is the best value. | | `paywall_texts.dart` | The words that depend on a plan: its name, the period after its price, its intro offer, the label of the button, the terms of the store, and the text of each failure. | | `paywall_links.dart` | The addresses of the terms of use and of the privacy policy, from `.env`, and `openPaywallLink()`. | | `paywall_guards.dart` | `paywallHasPremium()`, the function of the guard. | | `subscription_setting_row.dart`, in an app with a settings screen | The look of the row Subscription. | | `paywall_step.dart`, in an app with an onboarding | `paywallStepShows()` and `showPaywall()`, the functions of the step. | The views are plain Flutter widgets: a view gets the state and callbacks, and imports nothing that manages state. What keeps the state is a variant for each state manager: | | With `bloc` | With `riverpod` | | --- | --- | --- | | The paywall | `PaywallCubit` in `paywall_cubit.dart`, which `PaywallScreen` provides | `paywallProvider` of `paywall_notifier.dart`, which lasts as long as the paywall | | The screen of the subscription | `SubscriptionCubit` in `subscription_cubit.dart` | `premiumProvider` | | The access of the user, for any widget | `PremiumCubit` of `premium_cubit.dart`, around the root of the app: `context.watch().state` | `premiumProvider` of `purchases_provider.dart`: `ref.watch(premiumProvider)` | | The purchases of the app | `paywall_composition.dart` creates the cubits with `appPurchases` | `appPurchasesProvider` of `purchases_provider.dart`, which a test overrides, and `paywallLinkOpenerProvider` there | | The row of the settings screen | `subscription_setting.dart`, with `PremiumCubit` | `subscription_setting.dart`, with `premiumProvider` | The module adds `url_launcher: ^6.3.2` to the dependencies, and the package of the state manager with the constraint `any`, whose version the module of the state manager gives. It adds no asset: the card is drawn in code. The module gives the roles of the app what they need: | Role | What the module gives it | | --- | --- | | Router | The routes `paywall.paywall` and `paywall.subscription`, and the guard `paywall.hasPremium` of the stage `identity`, which stands for `PurchasesRole.premium`. | | Values in .env | `PAYWALL_TERMS_URL` and `PAYWALL_PRIVACY_URL`. | | Settings screen | `SubscriptionSetting`, in an app with a settings screen. | | Onboarding screen | The step `paywall.offer`, in an app with an onboarding. | | Localization | Its 65 texts of the screens, the three of the row in an app with a settings screen, and the four of the step in an app with an onboarding, in English and in Ukrainian. | In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "Paywall": where its screens are and what shows and closes them, how to sell from a button, which files are the look and which the state, where the plans get their words and a failure its text, what the links need in `.env`, whose a purchase before a sign-in is, and what a widget test minds while a call is on its way. By the state manager of the app, it adds where the state of a screen is and how a widget reads the access, and in an app with an onboarding, how the step shows the paywall and who closes it. The README of the app gets the section "Paywall". ## The texts The texts of the screens are in English and in Ukrainian. In an app with a module that provides the localization, such as [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md), they are texts of the app and follow its language. Their names start with `paywall`, such as `paywallBenefitAll`. An app without such a module shows them in English. A text of the app has no parameters, so the paywall puts the words of a plan together from closed sets, with the price that the store gives: | | The paywall has words for | Anything else | | --- | --- | --- | | The period of a plan | every week, every 1, 2, 3 or 6 months, every year, and a plan paid once | The title of the product in the store as its name, and its price without a period | | The length of an intro offer | 3 days, 1 or 2 weeks, 1, 2, 3 or 6 months, 1 year | Free trial or Introductory price, without its length | These are the periods and the free trials of the App Store. Google Play also has periods such as every 4 weeks, which get the title of the product. To make the texts yours: - The benefits are the texts `benefitAll`, `benefitNew` and `benefitSupport` of the module. Change them to what premium access gives in your app. With `gen_l10n`, they are `paywallBenefitAll`, `paywallBenefitNew` and `paywallBenefitSupport` in `lib/l10n/app_en.arb` and in the file of each other language, and `flutter gen-l10n` generates the code after a change; see [Languages](https://doc.saymyframe.com/guides/languages.md#add-a-text). Without a module of the localization, they are English texts in `paywall_view.dart`. - The texts of the step, `stepTitle`, `stepText`, `stepAction` and `stepLater`, change the same way. - The words of a plan and the text of each failure are put together in `paywall_texts.dart`. `failureTextOf()` there has a text for every reason of a failure, so the app does not compile once the purchases role has a reason without one. ## Large text, motion and screen readers On a small phone with a large text size: - The texts of the screens, such as the benefits, the plans, the label of the button and the lines below it, break between their words and never inside one. `PaywallWords` measures the longest word of a text, and where that word would not fit the width, as on a narrow phone with a large text size, the text is only as large as that word allows. A no-break space keeps two words together, as in a price and its period. - A price grows at most by half with the text size of the device, stays on one line with its period, and stays the largest text of its card. The name of the app on the card, the title of the screen of the subscription and the small labels, such as `Premium` and Best value, also grow at most by half. - The letters and the number in the cell of the card keep their size, since they are part of the picture. - On a phone of 320 by 480 points with the text at three times its size, the close button of a paywall over a page stays in sight at the top and at the end, and the paywall scrolls to its links, above the inset at the bottom of the screen. On a device that asks for less motion, the parts of the screens and the cards of the plans are in their places in the first frame, and a button that is busy is disabled with its label rather than spinning. A screen reader reads the name of the app with `Premium` as a header, each plan with its name, its price, its intro offer and its badge, and a failure as it comes, since the failure is in a live region. ## In tests A widget test of the screens gives `appPurchases.start()` a service of its own, which scripts the offer, what a call answers and the access; see [Purchases](https://doc.saymyframe.com/guides/purchases.md#in-tests). The button spins while a purchase is on its way and after one that gave premium access, until the router closes the paywall. So a test that waits with `pumpAndSettle()` returns only once the router closed it, and until then it shows frames with `pump()`. The guard keeps a user without premium access from the screen of the subscription. SMF's CI checks the module in every app with it, through the provider of purchases and its mocks: a request for the screen of the subscription opens the paywall over the page, the close button drops the request, and once the user bought a plan the router closes the paywall and shows the screen of the subscription. It checks the cards and the texts of the plans in each language of the app, the text of each failure, the links from `.env`, the screen of the subscription for each kind of plan, the row of the settings screen, and the paywall on a small phone with a large text size, in both themes and with less motion. In an app with an onboarding, it checks that the step shows the paywall over the onboarding, that the close button, back and a purchase close it, and that the onboarding then goes on. See [Contributing](https://doc.saymyframe.com/contributing.md#app-tests). The mocks of the module buy the first plan through `appPurchases` before the app starts, so the tests of the other modules of an app with the paywall start with premium access, and the guard allows. ## What the module does not do - It shows the plans of the current offer alone. Which plans that are, and in which order, is set at the provider of purchases, such as in the default offering of RevenueCat. - It changes no plan of a user who has one. The screen of the subscription leads to the page of the store, where the user changes or cancels the plan. - It shows no price per month for a plan of a longer period, which Google Play does not allow as the main price. - It asks for no sign-in: anyone may buy, and [whose the purchase is](#whose-purchase-it-is) follows the sign-in of the app. ## Choosing it `smf create` asks which features the app has. To choose this one without the question, with BLoC: ```bash smf create my_app -m paywall,bloc ``` The module requires the purchases role and the values of `.env`, and as a feature it requires a router. `smf create` adds each when only one module provides it: ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding revenuecat: the only provider of the purchases role, which paywall requires. Adding dart_define: the only provider of the env role, which paywall requires. Adding go_router: the only provider of the router role, which paywall requires. ``` The screens keep their state with the state manager of the app, and two modules provide one, so a run without a terminal stops until `-m` names one: ```text Several modules provide the state management role, which paywall requires: bloc, riverpod. Add one of them to -m. ``` With a start screen, tabs, a settings screen and an onboarding, the paywall has its row and its step: ```bash smf create my_app -m home,onboarding,settings,bottom_tabs,paywall,bloc ``` # `bloc` Source: https://doc.saymyframe.com/modules/bloc | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_bloc`](https://pub.dev/packages/smf_bloc) | infrastructure | State management | nothing | `-m bloc` | `bloc` manages the state of screens with [BLoC](https://bloclibrary.dev), through [flutter_bloc](https://pub.dev/packages/flutter_bloc) 9. ## What it adds to the app The module adds `flutter_bloc: ^9.1.1` to the dependencies and no code, since BLoC needs neither a widget around the app nor start-up code. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "State management". The state of a screen is a `Cubit` in the directory of its feature. The screen provides it with a `BlocProvider` and passes the state on to a view that imports no `flutter_bloc`. State that several screens read gets a `BlocProvider` around the root widget in `lib/main.dart`. After an `await`, a `Cubit` checks `isClosed` before it calls `emit()`. And a widget talks only to a `Cubit`, never to a service or a DI container. ## Features with state A feature that keeps state supports BLoC through a variant keyed by the id of this module, `bloc`. The variant brings the Cubits or Blocs of the feature's screens and provides them where the screens need them. Usually the feature's composition file creates them, with the services they need. The variant depends on `flutter_bloc` with the constraint `any`, so the version comes from this module. See [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md). Among the built-in features, [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) has such a variant: - Each of its screens has a cubit in a file next to it, such as `SignInCubit` in `lib/features/sign_in/sign_in_cubit.dart`. The screen provides its cubit with a `BlocProvider` and builds its view from the state with a `BlocBuilder`. The view is a plain Flutter widget that imports nothing of `flutter_bloc`. - `lib/features/sign_in/sign_in_composition.dart` creates the cubits. A cubit takes what it needs through its constructor, here the session of the app, so a test creates one with a session of its own. - State that several screens read has its `BlocProvider` around the root widget, in `runApp()`. The module puts its `SessionCubit` there, and a widget reads who uses the app with `context.watch().state`. - A cubit checks `isClosed` after an `await`, since the user may have left the screen while the call was on its way. `home`, `onboarding` and `settings` keep no state in a state manager, so they work the same with `bloc` and without it. ## Choosing it `smf create` asks which module manages the state of the app, and offers [`riverpod`](https://doc.saymyframe.com/modules/riverpod.md) and None as well. To choose it without the question: ```bash smf create my_app -m bloc ``` An app has at most one module that manages its state. # `riverpod` Source: https://doc.saymyframe.com/modules/riverpod | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_riverpod`](https://pub.dev/packages/smf_riverpod) | infrastructure | State management | nothing | `-m riverpod` | `riverpod` manages the state of screens with [Riverpod](https://riverpod.dev) 3, through [flutter_riverpod](https://pub.dev/packages/flutter_riverpod), without code generation. ## What it adds to the app The module adds `flutter_riverpod: ^3.4.3` to the dependencies, and a `ProviderScope` around the root widget in `lib/main.dart`: ```dart runApp(ProviderScope(child: const App())); ``` In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "State management". The state of a screen is a `NotifierProvider.autoDispose` in the directory of its feature, written by hand. The screen is a `ConsumerWidget` that passes the state on to a view that imports no `flutter_riverpod`. State that several screens read is a provider without `autoDispose`. After an `await`, a `Notifier` checks `ref.mounted` before it sets `state`, and it reads what the call needs from `ref` before the `await`. A widget talks only to providers, never to a service or a DI container, and the `ProviderScope` stays above every widget that reads one. ## Features with state A feature that keeps state supports Riverpod through a variant keyed by the id of this module, `riverpod`. The variant brings the providers of the feature's screens. A provider that needs a service of the DI container gets it in the feature's composition file, through a bridge such as `Provider((_) => resolve())`. The variant depends on `flutter_riverpod` with the constraint `any`, so the version comes from this module. See [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md). Among the built-in features, [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) has such a variant: - Each of its screens has a provider in a file next to it, with its `Notifier`, such as `signInProvider` in `lib/features/sign_in/sign_in_notifier.dart`. It is a `NotifierProvider.autoDispose`, so it lasts as long as its screen. The screen is a `ConsumerWidget` that watches the provider and gives its view the state. The view is a plain Flutter widget that imports nothing of `flutter_riverpod`. - State that several screens read is a provider without `autoDispose`. `sessionProvider` in `lib/features/sign_in/session_provider.dart` is one, and a widget reads who uses the app with `ref.watch(sessionProvider)`. - The notifiers reach the session of the app through `appSessionProvider`, which a test overrides with a session of its own. - A notifier reads what it needs from `ref` before an `await`, and checks `ref.mounted` after it, since the user may have left the screen while the call was on its way. - A provider is one for the app, so two pages of one screen that are open at once show the same state. `home`, `onboarding` and `settings` keep no state in a state manager, so they work the same with `riverpod` and without it. ## The `ProviderScope` and other wrappers The `ProviderScope` has to be above every widget that reads a provider. Other modules can wrap the root widget too, and their wrappers come in the order of their modules: a module comes after the providers of the roles it requires and after the modules it depends on. A module can use Riverpod only through its variant for `riverpod`, which makes it require the state management role, or by depending on this module. Either way it comes after `riverpod`, so its wrapper always goes inside the `ProviderScope`. ## Choosing it `smf create` asks which module manages the state of the app, and offers [`bloc`](https://doc.saymyframe.com/modules/bloc.md) and None as well. To choose it without the question: ```bash smf create my_app -m riverpod ``` An app has at most one module that manages its state. # `material_theme` Source: https://doc.saymyframe.com/modules/material-theme | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_material_theme`](https://pub.dev/packages/smf_material_theme) | infrastructure | Theme | preferences | `-m material_theme` | `material_theme` gives the app a light and a dark Material 3 theme. Both have the colors of one palette, the text styles of one font and the same look of the components, such as cards, buttons, text fields and sheets, so they differ only in their colors. The app shows the theme that the user selects, and follows the device until then. ![The settings screen of an app with the module in the light theme: near white surfaces, a card with a hairline around it, and the selected segment and the selected tab in green.](https://doc.saymyframe.com/demo/0.8/app_5_settings.png) ![The same screen in the dark theme: near black surfaces, with the same shapes and the same font.](https://doc.saymyframe.com/demo/0.8/app_6_settings_dark.png) ## What it adds to the app | In the app | What it is | | --- | --- | | `lib/core/theme/app_theme.dart` | The two themes. Edit this file to change the look of the app. | | `assets/fonts/geist/Geist-Regular.ttf`, `Geist-Medium.ttf` and `Geist-SemiBold.ttf` next to it | The font of the themes, [Geist](https://github.com/vercel/geist-font), in the weights 400, 500 and 600. It has Latin and Cyrillic letters. | | `assets/fonts/geist/OFL.txt` | The license of the font, the SIL Open Font License. | The module declares the family of the font in `pubspec.yaml`, and its license among the assets of the app, so that each copy of the app has the license with the font. In an app without other assets, the `flutter` section is: ```yaml title="pubspec.yaml" flutter: uses-material-design: true assets: - "assets/fonts/geist/OFL.txt" fonts: - family: "Geist" fonts: - asset: "assets/fonts/geist/Geist-Regular.ttf" weight: 400 - asset: "assets/fonts/geist/Geist-Medium.ttf" weight: 500 - asset: "assets/fonts/geist/Geist-SemiBold.ttf" weight: 600 ``` The files of the font are part of the app, so the app loads no font from the network. The themes are those of the material library of Flutter, so the module adds no package to the app. Whichever module provides it, the theme role adds the theme mode: - `lib/core/theme/theme_mode.dart` with `appThemeMode`, which keeps the mode that the user selected, saves each choice in the preferences and restores it when the app starts; - the `theme`, the `darkTheme` and the `themeMode` of the root `MaterialApp`, which takes the two themes from the functions of `app_theme.dart`; - in an app with a settings screen, the entry Theme, in which the user selects System, Light or Dark. [Theme](https://doc.saymyframe.com/guides/theme.md) describes the mode and how code reads and changes it. The mode is saved in the preferences, so an app with this module has a module that provides them. `smf create` adds [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md) by itself while it is the only one that does. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the theme role tells under "Theme" where the look is and how code changes the mode. The module adds how `_themeOf` creates both themes, where their colors and their font are, where a text field takes its look from, and what a change of the file must keep. ## The file of the themes `lib/core/theme/app_theme.dart` has three constants for colors, the family of the font, the two functions that the theme role requires, and three functions that build what they return: | In the file | What it is | | --- | --- | | `seedColor` | A green, the accent of the light theme. It is also the color from which `ColorScheme.fromSeed` gets the colors that `_schemeOf` does not set itself, such as those of an error. | | `_deepGreen`, `_cream` | The primary pair. The deep green is the primary color of the light theme and the color of what stands on the primary color of the dark one. The cream is the other way round. | | `_fontFamily` | The family of the font, as `pubspec.yaml` declares it. | | `createLightTheme(context)`, `createDarkTheme(context)` | The light and the dark theme of the app. Each returns `_themeOf` of its brightness and leaves its context alone. | | `_schemeOf(brightness)` | The colors of a theme. | | `_textThemeOf(scheme)` | The text styles, in the font and in the colors of the scheme. | | `_themeOf(brightness)` | The `ThemeData` of a theme: its colors, its font, its text styles and the look of its components. | This is the start of the file, without the functions that build the themes: ```dart title="lib/core/theme/app_theme.dart" import 'package:flutter/cupertino.dart' show CupertinoPageTransitionsBuilder; import 'package:flutter/material.dart'; /// The accent of the app, and the colour that `ColorScheme.fromSeed` derives /// the colours from that [_schemeOf] does not set itself, such as those of /// an error. The colours of the app are in [_schemeOf]: change them there /// to give the app another look. const Color seedColor = Color(0xFF15803D); /// The deep green that the themes pair with [seedColor]: the primary colour /// of the light theme, and the colour of what stands on the primary colour /// of the dark one. const Color _deepGreen = Color(0xFF0F3326); /// The cream that goes with [_deepGreen]: the primary colour of the dark /// theme, and the colour of what stands on the primary colour of the light /// one. const Color _cream = Color(0xFFF1F1E8); /// The font of the app: the family that `pubspec.yaml` declares with the /// files in `assets/fonts/geist/`, in the weights 400, 500 and 600. A text /// of another weight gets the nearest of them. For another font, add its /// files, declare its family in `pubspec.yaml` and name it here. const String _fontFamily = 'Geist'; /// The light theme of the app. /// /// The root of the app calls it each time it builds, so a change of this /// file shows on a hot reload. [context] is the context of the root, above /// its `MaterialApp`: it has neither the theme nor the localizations of the /// app. ThemeData createLightTheme(BuildContext context) => _themeOf(Brightness.light); /// The dark theme of the app; see [createLightTheme]. ThemeData createDarkTheme(BuildContext context) => _themeOf(Brightness.dark); ``` ### The colors `_schemeOf` starts from the scheme that `ColorScheme.fromSeed` gives for `seedColor` and sets most colors itself, for each brightness. This excerpt leaves out most of them: ```dart title="lib/core/theme/app_theme.dart" ColorScheme _schemeOf(Brightness brightness) { final seeded = ColorScheme.fromSeed( seedColor: seedColor, brightness: brightness, dynamicSchemeVariant: DynamicSchemeVariant.fidelity, ); return switch (brightness) { Brightness.light => seeded.copyWith( primary: _deepGreen, onPrimary: _cream, // ... secondary: seedColor, // ... surface: const Color(0xFFFAFAF9), // ... ), Brightness.dark => seeded.copyWith( primary: _cream, onPrimary: _deepGreen, // ... secondary: const Color(0xFF4ADE80), // ... surface: const Color(0xFF0A0A0A), // ... ), }; } ``` | Colors of the scheme | What they are | | --- | --- | | `primary`, `onPrimary` | The deep green with the cream on it in the light theme, and the cream with the deep green on it in the dark one. | | `secondary` | The accent, a green: `seedColor` in the light theme and a lighter green in the dark one. The themes mark with it what is selected, such as the selected destination of a navigation bar. | | `tertiary` | An amber. | | `surface` and the surface containers | Neutral surfaces: near white in the light theme and near black in the dark one. `surfaceTint` is transparent, so a surface takes no tint of the primary color. | | `outline`, `outlineVariant` | The borders. `outlineVariant` is the hairline of the themes: around a card, around a segmented button, around a text field and of a divider. | Each of the first three has its container and the color of what stands on it, such as `secondaryContainer` and `onSecondaryContainer`. ### The text styles `_textThemeOf` takes the text styles of Material 3 in the font of the app and sets their weight and spacing: | Styles | Weight | Spacing | | --- | --- | --- | | `display…`, `headline…`, `title…` | 600 | Tight letters, tighter for a larger style. | | `body…` | 400 | Lines 1.4 to 1.5 times the size of the text. | | `labelLarge` | 600 | | | `labelMedium`, `labelSmall` | 500 | | ### The components `_themeOf` gives the `ThemeData` the scheme, the font and the text styles, makes `surface` the background of a `Scaffold`, and sets the look of the components: | In `_themeOf` | The look | | --- | --- | | `appBarTheme` | An app bar in the color of the surface, flat also over content that scrolls under it, with its title at the start in `titleLarge`. | | `navigationBarTheme` | A flat navigation bar in the color of the surface, with the icon and the label of the selected destination in the accent, and the others in `onSurfaceVariant`. The bar of [`bottom_tabs`](https://doc.saymyframe.com/modules/bottom-tabs.md#change-the-look-of-the-bar) takes its colors from here too. | | `cardTheme` | A flat card without a margin, with a hairline around it and corners of 20. | | `filledButtonTheme` | A filled button at least 60 high, with corners of 18. | | `textButtonTheme` | A text button in `onSurfaceVariant`. | | `segmentedButtonTheme` | Segments at least 44 high inside a hairline, with the selected one in the container of the accent. | | `inputDecorationTheme` | A filled text field with corners of 16 and a hairline around it. The line takes the primary color with the focus and the color of an error with a mistake. The text of a mistake takes up to five lines, and an icon in a field is in `onSurfaceVariant`. | | `listTileTheme` | A list tile with its title in `bodyLarge`. | | `dividerTheme` | A hairline that takes no more room than its own thickness. | | `bottomSheetTheme` | A sheet with a drag handle and top corners of 28. | | `dialogTheme` | A dialog with corners of 24. | | `snackBarTheme` | A floating snack bar in the inverse of the surface, with corners of 14. | | `pageTransitionsTheme` | The transition between two pages: `FadeForwardsPageTransitionsBuilder` on Android, and that of Cupertino on iOS. | These are the text fields and the buttons on the sign-in of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), at rest and with a mistake in each field. The two white buttons of the other ways to sign in keep their colors in both themes, as their brands ask: ![The sign-in of an app with the module in the light theme: the buttons Continue with Google and Continue with Apple, two filled text fields with rounded corners and a hairline around them, a filled button as wide as the form, and two text buttons.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png) ![The same form with two mistakes: the line around each field and the text below it are in the color of an error.](https://doc.saymyframe.com/demo/0.8/app_sign_in_mistakes.png) ## Change the look - For other colors, change them in `_schemeOf`, for the light and for the dark theme. Keep the color of what stands on a color readable on it, such as `onPrimary` on `primary`. A change of `seedColor` alone changes the accent of the light theme and the colors that `_schemeOf` does not set. - For other text styles, change `_textThemeOf`. - What both themes share goes into the `ThemeData` of `_themeOf`, such as the theme of a component. For rounder cards, for one, change the radius in its `cardTheme`: ```dart title="lib/core/theme/app_theme.dart" cardTheme: CardThemeData( elevation: 0, margin: EdgeInsets.zero, color: scheme.surfaceContainerLow, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), side: hairline, ), ), ``` - A text field takes its border, its fill and its padding from the `inputDecorationTheme` of `_themeOf`, in both themes. So a `TextField` of a screen needs none of its own. Give a field a decoration only for what that field alone has, such as its hint or an icon. The fields of the screens of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) are such fields: they have only the button that shows the password and the lines of a mistake, and a change of `inputDecorationTheme` changes them. - For what differs between the two themes, use the `brightness` that `_themeOf` gets. - Keep `brightness: brightness` in the color scheme, so that `createLightTheme` returns a light theme and `createDarkTheme` a dark one. Keep both functions and their `BuildContext` parameter too, since the root of the app calls them. The root calls the two functions each time it builds, so a change of the file shows on a hot reload. ### Another font 1. Add the files of the font to the app, such as in a directory of their own in `assets/fonts/`. 2. Declare its family in `pubspec.yaml`, with a file for each weight, as the family `Geist` is declared. 3. Name the family in `_fontFamily`. The themes ask for the weights 400, 500 and 600. A text of a weight that the family does not declare gets the nearest one that it does. Keep `assets/fonts/geist/OFL.txt` among the assets while the app has the files of Geist. Once the app uses another font, remove the directory `assets/fonts/geist/` together with its lines in `pubspec.yaml`. ## Choosing it `smf create` asks which module provides the theme of the app, and offers None as well. To choose this one without the question, here with a start screen, a settings screen and tabs at the bottom: ```bash smf create my_app -m material_theme,home,settings,bottom_tabs ``` The run adds the modules that these need, and says why: ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding shared_preferences: the only provider of the preferences role, which material_theme requires. Adding go_router: the only provider of the router role, which home requires. ``` # `launcher_icons` Source: https://doc.saymyframe.com/modules/launcher-icons | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_launcher_icons`](https://pub.dev/packages/smf_launcher_icons) | infrastructure | App icon | nothing | `-m launcher_icons` | `launcher_icons` makes the icon of the app with [flutter_launcher_icons](https://pub.dev/packages/flutter_launcher_icons): an opaque icon on iOS and an adaptive icon with a themed variant on Android, in place of the logo of Flutter. All [flavors](https://doc.saymyframe.com/guides/flavors.md) of the app share the icon. To replace the images, see [App icon and splash screen](https://doc.saymyframe.com/guides/app-icon-and-splash.md). ## What it adds to the app | In the app | What it is | | --- | --- | | `flutter_launcher_icons: ^0.14.4` in the dev dependencies | The tool. No code of the app imports it. | | `assets/branding/icon.png` | 1024 by 1024 and opaque, for iOS and older versions of Android. It shows the mark of Say My Frame in cream on green. | | `assets/branding/icon_foreground.png` | 1024 by 1024, the same mark on a transparent background, for the adaptive icon of Android | | `flutter_launcher_icons.yaml` | How the tool makes the icon, with the colour `#0F3326` behind the mark on Android, and the second image as the themed icon too | | `tool/update_app_icon.dart` | The script that runs the tool, and that you run again after a change | | The section "Launcher icons" of the README | What the images show, and the command | Whichever module provides it, the role adds the section "App icon" of the README. The app does not bundle the images. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the role names the sources under "App icon". The module adds the command, and that an agent neither runs the tool itself nor adds a file for a flavor. ## After generation The module runs `dart tool/update_app_icon.dart` once the app has its packages. A run in a terminal asks first, with Enter for yes: ```text ? Making the app icon from assets/branding (dart tool/update_app_icon.dart), for launcher_icons. Run it now? (Y/n) ``` A run without a terminal runs it too. When the tool fails, you still get the app, with the logo of Flutter, a warning and the command to run later. Run the script again after you change an image or `flutter_launcher_icons.yaml`, and commit what changed under `android/` and `ios/`: ```bash dart tool/update_app_icon.dart ``` ## Why a script flutter_launcher_icons 0.14.4 writes the name of the icon into every build setting of the Xcode project whose name has `ASSETCATALOG`. One of those settings, `ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS`, takes `YES` or `NO`. The script gives that setting its value back, or `YES` after a run of the tool alone. So use the script rather than `dart run flutter_launcher_icons`. ## Choosing it `smf create` asks which module provides the app icon, and the answer may be none. To choose it without the question: ```bash smf create my_app -m launcher_icons ``` # `native_splash` Source: https://doc.saymyframe.com/modules/native-splash | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_native_splash`](https://pub.dev/packages/smf_native_splash) | infrastructure | Splash screen | nothing | `-m native_splash` | `native_splash` makes the screen that the system shows while the app starts with [flutter_native_splash](https://pub.dev/packages/flutter_native_splash), in place of the white screen of `flutter create`. All [flavors](https://doc.saymyframe.com/guides/flavors.md) of the app share the screen. To replace the images, see [App icon and splash screen](https://doc.saymyframe.com/guides/app-icon-and-splash.md). ## What it adds to the app | In the app | What it is | | --- | --- | | `flutter_native_splash: ^2.4.8` in the dev dependencies | The tool. No code of the app imports it. | | `assets/branding/splash_light.png` | 1152 by 1152 on a transparent background, the mark of Say My Frame in green, for the light mode of the device | | `assets/branding/splash_dark.png` | 1152 by 1152 on a transparent background, the same mark in cream, for the dark mode | | `flutter_native_splash.yaml` | How the tool makes the screen, with cream, `#F1F1E8`, behind the mark in the light mode and green, `#0F3326`, in the dark mode, and the same again under `android_12` | | The section "Native splash" of the README | What the images show, where the colours are, and the command | Whichever module provides it, the role adds the section "Splash screen" of the README. The app does not bundle the images. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the role names the sources under "Splash screen". The module adds the command and what it rewrites. ## After generation The module runs the tool once the app has its packages. A run in a terminal asks first, with Enter for yes: ```text ? Making the splash screen from assets/branding (dart run flutter_native_splash:create), for native_splash. Run it now? (Y/n) ``` A run without a terminal runs it too. When the tool fails, you still get the app, with a white launch screen, a warning and the command to run later. Run it again after you change an image or `flutter_native_splash.yaml`, and commit what changed under `android/` and `ios/`: ```bash dart run flutter_native_splash:create ``` The command rewrites `ios/Runner/Info.plist` with one more level of indentation. Keep the mark of an image inside a circle of two thirds of its width, since Android 12 and later cut the rest. Keep `android_min_sdk` out of `flutter_native_splash.yaml`: with it, the tool leaves the launch background of Android below 12 as it is, and the screen there has no image. A file `flutter_native_splash-.yaml` does not give a flavor its own screen on iOS: the tool writes one, and the app keeps showing the screen of `flutter_native_splash.yaml`. ## Choosing it `smf create` asks which module provides the splash screen, and the answer may be none. To choose it without the question: ```bash smf create my_app -m native_splash ``` # `gen_l10n` Source: https://doc.saymyframe.com/modules/gen-l10n | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_gen_l10n`](https://pub.dev/packages/smf_gen_l10n) | infrastructure | Localization | preferences | `-m gen_l10n` | `gen_l10n` keeps the texts of the app in ARB files, one for each language. [gen-l10n](https://docs.flutter.dev/ui/internationalization), the generator of localizations in the Flutter SDK, turns them into the code that reads them. The app shows its texts in the language of the device, or in the one that the user chose, among the languages that the texts are in. ## What it adds to the app | File | What it holds | | --- | --- | | `l10n.yaml` | The options of gen-l10n. | | `lib/l10n/app_en.arb` | Every text of the app in English. | | `lib/l10n/app_.arb` | The translations into another language of the app, one file for each. | | `lib/core/l10n/l10n.dart` | `context.l10n`, the texts of the app in the language of a `BuildContext`. | The module also adds `generate: true` to the `flutter` section of `pubspec.yaml` and the `intl` package to the dependencies, and gives the root `MaterialApp` the delegate of the texts, `AppLocalizations.delegate`. With these, `flutter pub get` generates the `AppLocalizations` class in `lib/l10n`, in `app_localizations.dart` and a file for each language next to it. SMF does not write that code. `smf create` runs `flutter pub get` in the new app, so the app has the class when the run ends. Whichever module provides it, the localization role adds `lib/core/l10n/app_locale.dart` with the languages of the app, `appLocales`, and the language that the user chose, `appLocale`, which the app remembers. The role also gives the root `MaterialApp` its `locale`, its `supportedLocales` and the delegates of Flutter's own texts, adds `flutter_localizations` to the dependencies, and names the languages of the app in `ios/Runner/Info.plist`. In an app with a settings screen, it adds the entry Language, in which the user chooses the language. [Languages](https://doc.saymyframe.com/guides/languages.md) describes all of this, and [Texts and languages](https://doc.saymyframe.com/concepts/localization.md) how the texts of the modules get into the app. The choice of the user is saved in the preferences, so an app with this module has a module that provides them. `smf create` adds [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md) by itself while it is the only one that does. The README of the app gets a section "Texts" from the module and a section "Languages" from the role, with the steps of this page. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the role tells under "Localization" how code reads a text and where the languages are, and the module adds where the texts are, how to add one, and which files gen-l10n writes itself. ## The texts The modules and the roles of the app give their texts to the localization role, each in English and in the languages that its owner has it in. `smf create` writes them into the ARB files, each under the name of its getter. An app that no route starts has the two texts of the [fallback start screen](https://doc.saymyframe.com/modules/flutter-core.md#its-texts-and-the-languages-of-the-app) of `flutter_core`. In an app with this module alone, which no route starts, they are the whole file of Ukrainian: ```json title="lib/l10n/app_uk.arb" { "@@locale": "uk", "flutterCoreFallbackHint": "Π‘Ρ‚Π°Ρ€Ρ‚ΠΎΠ²ΠΎΠ³ΠΎ Π΅ΠΊΡ€Π°Π½Π° Ρ‰Π΅ Π½Π΅ΠΌΠ°Ρ”. Π”ΠΎΠ΄Π°ΠΉΡ‚Π΅ Ρ„Ρ–Ρ‡Ρƒ Π· ΠΌΠ°Ρ€ΡˆΡ€ΡƒΡ‚ΠΎΠΌ Π°Π±ΠΎ Π·Π°ΠΌΡ–Π½Ρ–Ρ‚ΡŒ Ρ†Π΅ΠΉ Π΅ΠΊΡ€Π°Π½.", "flutterCoreFallbackCopied": "Π‘ΠΊΠΎΠΏΡ–ΠΉΠΎΠ²Π°Π½ΠΎ" } ``` The texts of the other modules of the app are in the file too, in the order of the modules. After the texts of the modules come those that the roles of the app add themselves, such as the texts of the entry of the language. The file of another language has only the texts that are translated into it. A text that it lacks reads in English there. Code reads a text through `context.l10n`, with `lib/core/l10n/l10n.dart` imported, where the context is one below the root of the app: ```dart title="lib/core/l10n/l10n.dart" /// The texts of the app in the language of a context: `context.l10n`. extension AppTexts on BuildContext { /// The texts of the app in the language of this context, which is below /// the root of the app. /// /// gen-l10n of Flutter generates [AppLocalizations] from the ARB files in /// `lib/l10n`: run `flutter gen-l10n` after every change of those files. AppLocalizations get l10n => AppLocalizations.of(this); } ``` ## Add a text Add the text to `lib/l10n/app_en.arb` under a name of its own in lowerCamelCase, and its translations under the same name to the files of the other languages: ```json title="lib/l10n/app_en.arb" { "@@locale": "en", "cartTitle": "Your cart" } ``` Then run `flutter gen-l10n`, which generates the getter, and read the text: ```dart import 'package:my_app/core/l10n/l10n.dart'; Text(context.l10n.cartTitle) ``` Run `flutter gen-l10n` after every change of the ARB files. In a fresh clone of the app, `flutter pub get` generates the files that it writes, so you can commit `lib/l10n/app_localizations*.dart` or leave them out of the repository. Do not edit them. ## Add a language The texts of a new language go into a file of their own. For German: 1. Add `lib/l10n/app_de.arb` with `"@@locale": "de"` and the translations. 2. Run `flutter gen-l10n`. The language then goes into the list of the languages of the app and two more places, which are the same with every module that provides the localization. [Languages](https://doc.saymyframe.com/guides/languages.md#add-a-language) has those steps. ## The options of gen-l10n ```yaml title="l10n.yaml" arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart nullable-getter: false use-escaping: false ``` `nullable-getter: false` makes `AppLocalizations.of(context)` return the texts and not a nullable value, so `context.l10n` needs no `!`. `use-escaping: false` turns the escapes of gen-l10n off, so write an apostrophe in a text once. ## Choosing the languages The app gets every language that a text of its modules and roles is in, with English first. `--locales` narrows and orders them, as in `--locales en,uk`. See [Languages](https://doc.saymyframe.com/guides/languages.md#choosing-the-languages). ## For module authors A module gives its texts to the localization role and never to this module; see [Texts](https://doc.saymyframe.com/extending/texts.md). The class that gen-l10n generates has members of its own: `localeName`, `of`, `delegate`, `localizationsDelegates` and `supportedLocales`. `smf create` reports a text whose getter would have one of these names. ## Choosing it `smf create` asks which module provides the localization of the app, and offers None as well. Without such a module, the modules show their texts in English. To choose this one without the question: ```bash smf create my_app -m gen_l10n ``` This app has no feature, so it starts on the fallback start screen of `flutter_core`, whose texts it shows in English or in Ukrainian, as the device prefers. # `get_it` Source: https://doc.saymyframe.com/modules/get-it | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_get_it`](https://pub.dev/packages/smf_get_it) | infrastructure | Dependency injection | nothing | `-m get_it` | `get_it` provides dependency injection with [get_it](https://pub.dev/packages/get_it) 9. The other modules of the app declare the services they generate, and this module registers them in get_it. ## What it adds to the app The module adds `get_it: ^9.3.0` to the dependencies and generates `lib/core/di/dependencies.dart` with three functions. `createServiceLocator()` returns a service locator whose `resolve` finds the services in the global instance of get_it, `GetIt.instance`. `registerDependencies()` registers the services, and `bootstrap()` awaits it before the first frame. `resetDependencies()` resets get_it with `GetIt.instance.reset()`, for tests that register the services again. Whichever module provides it, the dependency injection role adds `lib/core/di/service_locator.dart` with the `ServiceLocator` interface and the function `resolve()`, and calls `registerDependencies()` in the DI phase of `bootstrap()`. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the dependency injection role describes the services under "Dependency injection". The module adds how `registerDependencies()` registers a service in get_it, and that no other file in `lib/` imports the package. ## How services are registered A module declares each service by its type, the function that creates it, the services the function takes, and how long the service lives. `registerDependencies()` picks the get_it call that fits: | A module declares | `registerDependencies()` calls | | --- | --- | | a singleton | `registerSingleton` | | a singleton that waits for services that are created asynchronously or wait themselves | `registerSingletonWithDependencies` with `dependsOn` | | a singleton created asynchronously | `registerSingletonAsync`, with `dependsOn` if it waits | | a lazy singleton | `registerLazySingleton` | | a factory | `registerFactory` | | a name for one of several services of a type | `instanceName`, and `InitDependency` to wait for it | | a function that disposes of a service | `dispose` | The factory function of each service gets the services it declares from get_it. get_it creates a singleton while it registers it, so every service is registered after the services it takes or waits for. A singleton also waits, without declaring it, for the services it takes that are created asynchronously or wait themselves, directly or through lazy singletons and factories. When some services are created asynchronously, `registerDependencies()` completes once all of them are ready. When `resetDependencies()` resets get_it, get_it disposes of the services it created, each with its `dispose` function, in the reverse order of their registration, so each service goes before the services it takes. A lazy singleton that nothing resolved is neither created nor disposed of. Then get_it removes every service, so that `registerDependencies()` can register them again. `dependencies.dart` imports the file of every type and function it names with a prefix of its own, so the names of different modules never clash. ## Using the services Only the composition file of a feature, `lib/features//_composition.dart`, takes services from the container with `resolve`, to create what the screens of the feature need, such as a Cubit. Everything else gets its services as parameters of its factory function. See [Services and state](https://doc.saymyframe.com/guides/services.md). ## Choosing it `smf create` asks which module provides dependency injection and offers None as well. When a module you chose needs dependency injection and `get_it` is the only module that provides it, `smf create` adds `get_it` by itself. To choose it without the question: ```bash smf create my_app -m get_it ``` # `event_bus` Source: https://doc.saymyframe.com/modules/event-bus | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_event_bus`](https://pub.dev/packages/smf_event_bus) | infrastructure | Events | nothing | `-m event_bus` | `event_bus` lets parts of the app that do not know each other, such as two features, exchange events through one service. The service is built on the [event_bus](https://pub.dev/packages/event_bus) package. ## What it adds to the app The module adds `event_bus: ^2.0.1` to the dependencies, and `lib/core/events/event_bus_communication_service.dart` with the implementation of the service on an `EventBus`. Whichever module provides it, the events role adds `lib/core/events/communication_service.dart` with: - `AppEvent`, the base class of the events, such as `final class ItemAdded extends AppEvent`; - the `CommunicationService` interface, where `fire(event)` sends an event and `on()` is the stream of the events of type `T`; - `createCommunicationService()`, which returns the service of the app. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the events role describes the service under "Events", and the module adds when a listener gets an event. ## How events are delivered - An event goes to everyone listening to its type, or to a type it extends or implements, so `on()` gets every event. - Listeners get an event after the code that fires it has completed, not during `fire`. - A listener gets the events fired after it starts listening. Whichever module provides the events role, a listener of a type gets each event of that type once, in the order the events were fired, and a listener of an unrelated type gets none. SMF's CI checks this in every app with the role in [the matrix of the built-in modules](https://doc.saymyframe.com/contributing.md#generated-apps). ## Getting the service The service is created on first use, without waiting, so the app starts as fast as it would without it. With a module of dependency injection, the events role registers the service in the container as a lazy singleton, and a feature takes it with `resolve` in its composition file. Without a container, the code of the app gets it from `createCommunicationService()`, which always returns the same service. Don't create a second one with `createEventBusCommunicationService()`, because the listeners of one service do not get the events fired into another. See [Services and state](https://doc.saymyframe.com/guides/services.md#events). ## Choosing it `smf create` asks which module provides the events of the app, and offers None as well. To choose it without the question: ```bash smf create my_app -m event_bus ``` # `shared_preferences` Source: https://doc.saymyframe.com/modules/shared-preferences | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_shared_preferences`](https://pub.dev/packages/smf_shared_preferences) | infrastructure | Preferences | nothing | `-m shared_preferences` | `shared_preferences` lets the app remember its settings between its launches, such as the theme mode or a hint that the user dismissed. It keeps them with the [shared_preferences](https://pub.dev/packages/shared_preferences) package. :::warning Nothing in the preferences is encrypted, and a backup of the device carries them. Never store a token, a password, an API key or an encryption key there. A secret belongs in the secure storage of the platform, the Keychain on iOS and the Keystore on Android. ::: ## What it adds to the app The module adds `shared_preferences: ^2.5.5` to the dependencies, and `lib/core/preferences/shared_app_preferences.dart` with the preferences on `SharedPreferencesWithCache`. The package keeps the values in DataStore on Android and in `UserDefaults` on iOS, and reads them into memory when the app starts. It also keeps the Android side of the package at 2.5.2 or later: ```yaml title="pubspec.yaml" shared_preferences_android: "^2.5.2" ``` With `shared_preferences_android` 2.5.0 and 2.5.1, a release build of the app fails to open the preferences on Android, so `bootstrap()` fails and the app never shows its first frame. Debug and profile builds work, and so does iOS. Those versions call their Kotlin code through JNI and find Kotlin classes by their names, which R8 renames in a release build, and neither they nor `package:jni` ship rules that keep them. 2.5.2 ships the rules, but `shared_preferences` alone still allows the two versions before it, so the module names 2.5.2 as the lowest. [The post about the shared_preferences release build crash](https://saymyframe.com/blog/shared-preferences-android-release-build-crash) has the details, and the upstream issue is [flutter/flutter#194649](https://github.com/flutter/flutter/issues/194649). The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app says why the constraint is there, and asks them to check that a release build starts on Android before they change it. Check the same before you change it yourself. Whichever module provides it, the preferences role adds `lib/core/preferences/app_preferences.dart` with: - the `AppPreferences` interface, which has a read and a write for a `String`, a `bool`, an `int`, a `double` and a `List`, such as `getBool(key)` and `setBool(key, value)`, and `remove(key)`; - `initPreferences()`, which opens the preferences and gives them to the code of the app that keeps settings there. `bootstrap()` awaits it in its platform phase, before the services of the app and before the first frame; - `createAppPreferences()`, which returns the preferences that `initPreferences()` opened. [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md) shows how the code of the app remembers a setting with them. ## Reads and writes A read is synchronous and never throws. It returns `null` when its key has no value of the type it asks for. This module reads a number only as the type that it was saved as: `getDouble` returns `null` for a key with an `int`, and `getInt` returns `null` for a key with a `double`, even a whole number such as `18.0`. So save and read a setting as one type. A write completes once the value is saved. The preferences keep a copy of a list they are given, and a read returns a copy of it, so a later change of either list changes nothing that is saved. A write puts its value into memory before it saves it. If the platform refuses the save, the write fails. The reads of this run return the value all the same. The next launch reads what was saved before the write, or nothing if the key had no value. Android refuses a text that starts with the prefix that the shared_preferences package marks a list with. ## Getting the preferences `bootstrap()` opens the preferences. The code of a module gets them right then, through a function that the module gives the preferences role. With a module of dependency injection, the role also registers the preferences in the container as a lazy singleton. A service then takes them as a dependency, and a feature takes them with `resolve` in its composition file. If the preferences cannot be opened, `initPreferences()` fails, and `bootstrap()` with it. ## In tests A test that runs `bootstrap()` first puts the preferences of the package into memory, or opening them throws a `StateError`: ```dart SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); ``` Both names come from the package `shared_preferences_platform_interface`, which the test needs as a dev dependency, each from a library of its own: ```dart import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; ``` The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app tells agents to set this instance too, in its section on the preferences. [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md#in-tests) has a whole test. Whichever module provides the preferences, a value of each type is read back as it was saved, a removed key has no value, and the next start reads what was saved. SMF's CI checks this in running apps with the role, and on devices with the real platform side of this module; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it `smf create` asks which module provides the preferences of the app, and offers None as well. When a module you chose needs preferences, as `material_theme` and `gen_l10n` do, and `shared_preferences` is the only module that provides them, `smf create` adds it by itself. To choose it without the question: ```bash smf create my_app -m shared_preferences ``` # `dart_define` Source: https://doc.saymyframe.com/modules/dart-define | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_dart_define`](https://pub.dev/packages/smf_dart_define) | infrastructure | Values in .env | nothing | `-m dart_define` | Some modules need values that only you have, such as the public key of a service or the address of a page. They name them as keys, and the role of the values in `.env` writes the keys into `.env` at the root of the app, where you fill them in; see [Values in .env](https://doc.saymyframe.com/guides/env.md). `dart_define` gets those values into the app with `--dart-define-from-file`, an option of the `flutter` tool. It adds no package to the app. A command of the `flutter` tool that builds, runs or tests the app reads `.env` when it starts, given `--dart-define-from-file=.env`, and compiles each value into the app as a constant. Nothing is generated after you edit `.env`. The analyzer sees the values as empty, so a fresh clone of the app analyzes and builds before anyone fills in `.env`. ## What it adds to the app | In the app | What it is | | --- | --- | | `lib/core/env/app_env.dart` | `AppEnv`, with a static getter for each key of the app. An app whose modules give no key gets the class without members. | | The section "Run, test and build with .env" of the README | The commands with the argument, the run configurations, when the values are read, and how to add a getter. | Whichever module provides it, the role adds `.env`, with a comment and an empty line for each key, `.env.example`, with the same keys, a line of `.gitignore` that keeps `.env` out of git, the section "Values in .env" of the README, which lists the keys of the app, and a run configuration of VS Code and of Android Studio for each [flavor](https://doc.saymyframe.com/guides/flavors.md), which pass the arguments of the module. A getter reads its value with `String.fromEnvironment` and returns `null` while the value is empty. `KEY=` in `.env` defines an empty value rather than none, so an empty line of `.env` and a missing one look the same to the app. This is a getter of an app with [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md): ```dart title="lib/core/env/app_env.dart" abstract final class AppEnv { /// The public API key of the App Store app in RevenueCat, which starts with /// appl_. static String? get revenuecatAppleKey { const value = String.fromEnvironment('REVENUECAT_APPLE_KEY'); return value.isEmpty ? null : value; } } ``` The value is a constant of the build, so it is there before any code of the app runs, `main()` included, and a test reads it without starting the app. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the role describes `AppEnv` under "Values in .env". The module adds the commands with the argument, the run configurations, the restart after an edit of `.env`, and how the getter of a new key reads its value. ## Run, test and build Give the argument to every command of the `flutter` tool that builds, runs or tests the app: ```bash flutter run --dart-define-from-file=.env flutter test --dart-define-from-file=.env flutter build apk --flavor prod --dart-define-from-file=.env flutter build appbundle --flavor prod --dart-define-from-file=.env flutter build ipa --flavor prod --dart-define-from-file=.env ``` Without it, every getter of `AppEnv` is `null`, as for a `.env` with no values. The last line of `smf create` is still `flutter run`: right after the app is generated every value of `.env` is empty, so the app is the same without the argument. A build without `--flavor` is a release of `dev`, under its id, so a build for a store names its flavor; see [Flavors](https://doc.saymyframe.com/guides/flavors.md#run-and-build-a-flavor). A command reads `.env` only when it starts. After you change `.env`, stop `flutter run` and start it again. Hot reload and hot restart keep the values that the app was built with. The run configurations pass the argument for you: | IDE | What passes it | | --- | --- | | VS Code | `.vscode/launch.json`, with a configuration for each flavor. Run and Debug (F5) starts the one that you select in the Run and Debug view. The one of `dev` is the template of every other launch of a file of the app (`"templateFor": ""`), so the Run and Debug links above `main()` and above a test, and the Testing view, pass the argument too, with the flavor `dev`. | | Android Studio | `.run/.run.xml`, a run configuration for each flavor. A test that you run from Android Studio gets no argument, so run tests from a terminal with the argument. | `.env` stays out of git. A machine that builds the app from a clone, such as a CI runner, needs a `.env` of its own before the build: copy `.env.example` and fill it in, or write it with [`tool/write_env.dart`](https://doc.saymyframe.com/guides/ci.md#values-for-each-environment) from the variables of the job. ## A key of your own Add the key to `.env.example` and `.env`, under a comment that says what goes there, and give `AppEnv` a getter for it, as for the other keys: ```dart static String? get myServiceKey { const value = String.fromEnvironment('MY_SERVICE_KEY'); return value.isEmpty ? null : value; } ``` The getter is the key in lowerCamelCase. Write the name of the key as a literal in `String.fromEnvironment`: the value is read when the app is compiled, so the name has to be a constant. ## What the module does not do - It loads nothing while the app runs. A change of `.env` reaches the app with the next command that builds or runs it. - It reads one file, `.env`, which is not tied to a flavor; see [One file for all flavors](https://doc.saymyframe.com/guides/env.md#one-file-for-all-flavors). - It keeps no secret. Every value is compiled into the app, where anyone who has the app can read it, so `.env` holds only values that may be public. ## In tests `AppEnv` reads constants, so a widget test reads a value without running `main()`. A test gets the values of `.env` only with `flutter test --dart-define-from-file=.env`, and gets `null` from every getter otherwise. Whichever module provides the role, a getter returns the value that `.env` has for its key, and `null` for a key that `.env` leaves empty or lacks. SMF's CI checks this in running apps with the role: the test parses the `.env` of the app, in both forms that a value may take, and compares each key with its getter. With this module, the apps of [`revenuecat`](https://doc.saymyframe.com/modules/revenuecat.md) and of [`paywall`](https://doc.saymyframe.com/modules/paywall.md) run it with values of the tests in `.env`. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it `smf create` adds the module when a module of the app needs values of `.env` and no other module provides them: ```text Adding dart_define: the only provider of the env role, which revenuecat requires. ``` To choose it yourself: ```bash smf create my_app -m dart_define ``` An app with the module and no module that gives it keys gets `.env` without keys and `AppEnv` without getters, ready for keys of your own. # `local_notifications` Source: https://doc.saymyframe.com/modules/local-notifications | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_local_notifications`](https://pub.dev/packages/smf_local_notifications) | infrastructure | Notifications | preferences | `-m local_notifications` | `local_notifications` shows the notifications of the app with the [flutter_local_notifications](https://pub.dev/packages/flutter_local_notifications) package. A notification shows now, or at about a time to come, also when the app is closed by then. The module asks the user for the permission to show them, and tells the app of each tap on a notification, including the tap that launched the app. The code of the app never uses the package. It uses `appNotifications`, which the notifications role generates; see [Notifications](https://doc.saymyframe.com/guides/notifications.md). The role remembers that the app asked for the permission, so it needs preferences, and `smf create` adds [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md) with the module. ## What it adds to the app | In the app | What it is | | --- | --- | | `flutter_local_notifications: ^22.3.2` and `timezone: ^0.11.0` in the dependencies | The package of the notifications, and the time zones that it schedules with. | | `lib/core/notifications/local_notifications_service.dart` | `LocalNotificationsService`, the notifications service of the app on `FlutterLocalNotificationsPlugin`, and `openLocalNotifications()`, which opens it. | | Core library desugaring in `android/app/build.gradle.kts` | What the package needs to build for Android. | | Two receivers and the permission `RECEIVE_BOOT_COMPLETED` in `android/app/src/main/AndroidManifest.xml` | What shows a scheduled notification at its time, also after a restart of the device. | | One line in `ios/Runner/AppDelegate.swift` | It makes the app delegate the delegate of the notification center of iOS. | | The section "flutter_local_notifications" of the README | What the module set up in the native projects, how to schedule to the minute, and what the app does not set up. | Whichever module provides it, the notifications role adds these files: | File | What it holds | | --- | --- | | `lib/core/notifications/app_notifications.dart` | `appNotifications`, through which the code of the app shows, schedules and cancels notifications, asks for the permission and reads the taps; `NotificationPermission`; and `initNotifications()`. | | `lib/core/notifications/notifications_service.dart` | `NotificationsService`, the interface that this module implements, `AppNotification` and `NotificationTap`, and the constants of the channel and of the small icon. | | `android/app/src/main/res/drawable/ic_notification.xml` | The small icon of a notification on Android, a bell that you replace. | | `android/app/src/main/res/raw/notifications_keep.xml` | Keeps that icon in a release build. | | `lib/core/notifications/notifications_setting.dart`, in an app with a [settings screen](https://doc.saymyframe.com/modules/settings.md) | `NotificationsSetting`, the row of the settings screen that shows whether the app may show notifications. A tap asks for the permission, or opens the settings of the system once the app has asked. | | `lib/core/notifications/notifications_step.dart`, in an app with an [onboarding](https://doc.saymyframe.com/modules/onboarding.md) | The functions of the page of the onboarding that asks for the permission. | In its platform phase, `bootstrap()` opens the preferences and then the notifications. This is `bootstrap()` of an app with this module and `shared_preferences`, which comes with it: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await initPreferences(); await initNotifications(); } ``` `initNotifications()` waits for `openLocalNotifications()`, which sets up the plugin, creates the channel of the app on Android and reads the tap that launched the app. It asks the user nothing. So the app knows the permission and the tap that launched it before its first frame. Where the app asks for the permission depends on its other modules: on a page of the onboarding, in the row of the settings screen, or, in an app with neither, nowhere until its code calls `appNotifications.request()`. See [the permission](https://doc.saymyframe.com/guides/notifications.md#the-permission). ![The step of the notifications in the onboarding: a dark green cell with a bell, the title Turn on notifications, the text The app tells you when something needs your attention, even when it is closed., the button Allow notifications, and Not now below it.](https://doc.saymyframe.com/demo/0.8/app_2_onboarding_notifications.png) ![The settings screen in the light theme, with the entry Theme, the row Language and the row Notifications with the value Off.](https://doc.saymyframe.com/demo/0.8/app_5_settings.png) In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the notifications role describes `appNotifications` under "Notifications". The module adds which file is on flutter_local_notifications, how to add a channel, why a scheduled notification uses an inexact alarm, which native files it set up, and what a test that runs `bootstrap()` answers in place of the platform side of the package. The README of the app gets the section "flutter_local_notifications" from the module and the section "Notifications" from the role. ## Native setup The package needs three things in the native projects, and the module adds them through [the sockets of the app entry](https://doc.saymyframe.com/concepts/sockets.md#the-sockets-of-the-app-entry). Keep them: the Android build, the scheduled notifications and the taps on iOS depend on them. For Android, the package needs core library desugaring, and the Android build fails without it. `android/app/build.gradle.kts` turns it on with `isCoreLibraryDesugaringEnabled = true` in `compileOptions`, and adds `coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")` to the dependencies, the version that the package builds with. The manifest declares the two receivers of the package. `ScheduledNotificationReceiver` shows a scheduled notification at its time. `ScheduledNotificationBootReceiver` sets the scheduled notifications again after a restart of the device or an update of the app: ```xml title="android/app/src/main/AndroidManifest.xml" ``` The second receiver hears of a restart through the permission `android.permission.RECEIVE_BOOT_COMPLETED`, which the manifest declares too. On iOS, the app delegate becomes the delegate of the notification center before the launch finishes. Through it, the plugin shows a notification while the app is in the foreground and hears of the taps, including the tap that launched the app: ```swift title="ios/Runner/AppDelegate.swift" override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { UNUserNotificationCenter.current().delegate = self return super.application(application, didFinishLaunchingWithOptions: launchOptions) } ``` ## The channel and the small icon Android shows a notification only in a channel, and the user turns each channel of an app on or off in the settings of the system. Every notification of the app goes to the channel `default` (`notificationChannelId`), which the settings of the system show under the name of the app, such as `My App` for `my_app`. The service creates the channel with a high importance when the app starts. It also shows each notification with a high importance and priority, so Android shows it as a banner, also while the app is in the foreground. These details are `_details` in `local_notifications_service.dart`. Android keeps the importance of a channel from the first time the app created it. For another channel, such as one with another sound, create it with `createNotificationChannel()` of `AndroidFlutterLocalNotificationsPlugin` in `openLocalNotifications()`, and show a notification in it with details of its own. The small icon is `android/app/src/main/res/drawable/ic_notification.xml`, the bell of the Material Design icons. Replace the drawing with the icon of the app, a shape on a transparent background, which Android shows in one color, and keep the name of the file. The code names the icon by its name alone, so the shrinking of the resources in a release build would remove it, and the app could not show a notification. `notifications_keep.xml` keeps it. ## Scheduled notifications `appNotifications.schedule()` reaches `zonedSchedule` of the plugin with an inexact alarm: ```dart title="lib/core/notifications/local_notifications_service.dart" @override Future schedule(AppNotification notification, DateTime at) => _plugin.zonedSchedule( id: notification.id, title: notification.title, body: notification.body, scheduledDate: tz.TZDateTime.from(at, tz.UTC), notificationDetails: _details, androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle, payload: jsonEncode(notification.data), ); ``` An inexact alarm needs no permission, and Android may show the notification a few minutes late. The time goes to the plugin in UTC, so the app needs no database of time zones. The notification shows also when the app is closed by then, and after a restart of the device. To show notifications to the minute: 1. Declare `android.permission.SCHEDULE_EXACT_ALARM` in the manifest. 2. Ask for it with `requestExactAlarmsPermission()` of `AndroidFlutterLocalNotificationsPlugin`. 3. Schedule with `AndroidScheduleMode.exactAllowWhileIdle`. Google Play allows exact alarms only for apps whose main feature needs them, such as an alarm clock or a calendar. That is why the app does not use them, and why the guide for coding agents tells an agent to change the mode only when asked. ## What the service adds to the package The notifications role promises more than the plugin does in a few places, and the service makes up the difference: | What the service does | Why | | --- | --- | | `show()` first cancels the scheduled notification with the same id, if there is one. | Android keeps the alarm of a scheduled notification when a notification with its id is shown, so the scheduled one would show again later. | | When the app may not show notifications and the system showed no question, `request()` opens the notification settings of the app. | Android before 13 has no question. Android 13 and later stop asking after a second no, and iOS after its one question. The plugin then answers at once, and the settings let the user turn the notifications on with one request. | | During a request, the service watches the lifecycle of the app. A request that starts while the app is out of the foreground, such as under the control center of iOS, opens no settings. | The plugin does not tell whether the system showed its question. The question takes the app out of the foreground until the user answers, and an app that is out of it already sees no change. | | A notification carries its `data` in the payload of the plugin, as the JSON of a map. A tap whose payload the app did not write has no data. | The payload of the plugin is a single text. | | On iOS, the plugin asks no question when it opens. | The plugin asks by default. The app asks where the user turns on something that notifies, through `appNotifications.request()`. | On iOS, the app may show notifications while the user allows them, even with the alerts of the app turned off, since iOS then keeps them in the notification center. The service reads the tap that launched the app when it opens, and `appNotifications.launchTap` has it. Each later tap reaches `appNotifications.taps` with the data of the notification; see [Taps](https://doc.saymyframe.com/guides/notifications.md#taps). A notification runs no code of the app when it shows. ## What the app does not set up The app does not set up the actions of a notification, its buttons. They need the receiver `ActionBroadcastReceiver` on Android, and on iOS a callback that registers the plugins for the isolate in which an action runs. The [README of the package](https://pub.dev/packages/flutter_local_notifications) describes both. ## In tests flutter_local_notifications has no platform side for tests. A test that runs `main()` or `bootstrap()` calls `AndroidFlutterLocalNotificationsPlugin.registerWith()` first, since `flutter test` registers no implementation of the plugin for the platform. It then answers the method channel `dexterous.com/flutter/local_notifications` itself, with `setMockMethodCallHandler` of `TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger`. Such a test also puts the preferences into memory; see [`shared_preferences`](https://doc.saymyframe.com/modules/shared-preferences.md#in-tests). The guide for coding agents of the app says the same. A test of a screen needs none of this: it gives `appNotifications.start()` a service of its own, which scripts what a provider answers; see [Notifications](https://doc.saymyframe.com/guides/notifications.md#in-tests). Whichever module provides the notifications, the permission is `notAsked` until the app asks, and one request turns the notifications on. A scheduled notification is listed until it is cancelled or a notification with its id is shown, and the next start of the app still finds it, and the permission that the user gave. SMF's CI checks this in running apps with the role, over a stand-in for the platform side of this module that starts as on a first launch. For this module, it checks what each call of the service sends to the plugin on Android and on iOS: the small icon, and no question on iOS, when the plugin opens; the channel of the app with its name and a high importance; the data of a notification as JSON; the cancel of a scheduled notification whose id is shown; the inexact alarm at its time in UTC; and when a request opens the settings of the system. It also checks the taps and the tap that launched the app. On devices, it checks that the channel of the app on Android has its name and a high importance. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it `smf create` asks which module provides the notifications of the app, and offers None as well. To choose it without the question: ```bash smf create my_app -m local_notifications ``` The notifications role requires preferences, and `smf create` adds the only module that provides them: ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding shared_preferences: the only provider of the preferences role, which local_notifications requires. ``` In a terminal, the question about push messages comes before this one. A provider of push messages, such as [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md), requires the notifications, so with it `smf create` adds this module without a question while it is the only one that provides them. # `firebase_core` Source: https://doc.saymyframe.com/modules/firebase-core | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_firebase_core`](https://pub.dev/packages/smf_firebase_core) | infrastructure | none | nothing | `-m firebase_core` | `firebase_core` sets up [Firebase](https://firebase.google.com/docs/flutter/setup) with [firebase_core](https://pub.dev/packages/firebase_core), which the other Firebase packages of an app build on. [`firebase_crashlytics`](https://doc.saymyframe.com/modules/firebase-crashlytics.md), [`firebase_analytics`](https://doc.saymyframe.com/modules/firebase-analytics.md), [`firebase_messaging`](https://doc.saymyframe.com/modules/firebase-messaging.md) and [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) depend on it, so it comes with them. ## What it adds to the app The module adds `firebase_core: ^4.15.0` to the dependencies, and these files: | In the app | What it is | | --- | --- | | `lib/firebase_options_dev.dart`, `lib/firebase_options_staging.dart`, `lib/firebase_options_prod.dart` | The options of each [flavor](https://doc.saymyframe.com/guides/flavors.md). Until a flavor is configured, its file is a placeholder in the form that flutterfire_cli writes. Each platform throws an `UnsupportedError` that gives the command, so the app compiles but a build of that flavor stops at start-up. | | `lib/firebase_options_of_flavor.dart` | `firebaseOptionsOfFlavor`, which picks the options by `appFlavor`. A release build keeps only the options of its own flavor. | | `tool/configure_firebase.dart` | The script that configures one flavor | In the platform phase of `bootstrap()`, before the services of the app, it initializes Firebase: ```dart await Firebase.initializeApp(options: firebaseOptionsOfFlavor); ``` It also asks for iOS 15.0 or newer, the lowest version that the Firebase SDKs support, which the app has already. It adds a section on Firebase to the README of the app, which tells how to configure a flavor, such as for another Firebase project or on another machine. The [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app gets a section "Firebase" too. It says that the options of a flavor are a placeholder until `tool/configure_firebase.dart` writes them, that an agent runs that script only when asked and does not run `flutterfire configure`, and that a test which runs `main()` or `bootstrap()` starts Firebase. ## The machine Before generation, the module checks what the FlutterFire CLI needs: the Firebase CLI, a login of the Firebase CLI that Google still accepts, flutterfire_cli 1.4.1 or a later 1.x activated globally, and on macOS the Ruby gem xcodeproj 1.23.0 or newer. On other systems it warns that the Xcode project has to be set up on a Mac. A missing tool is a warning with instructions. In a terminal, SMF offers to install the Firebase CLI, to log in (or to log in again when the login has expired) and to activate flutterfire_cli, and asks before each. See [Firebase](https://doc.saymyframe.com/guides/firebase.md#before-generation-the-machine). For the modules that depend on it, the package has one more check, `FirebaseCliVersionCheck`. A module whose command exists only in newer versions of the Firebase CLI puts it among its own checks of the machine, with the lowest version that has the command, as `firebase_auth` does with 15.34.0. The check reads `firebase --version` and tells how to update an older Firebase CLI, which SMF does not update itself. On a machine without the Firebase CLI, the check of `firebase_core` runs first and offers the installation, and the check of the version then reads the version that was installed. See [a check from the module you depend on](https://doc.saymyframe.com/extending/infrastructure-module.md#a-check-from-the-module-you-depend-on). ## After generation Once the app has its packages, the module configures the flavor `dev` in it with the terminal, after asking: ```bash dart tool/configure_firebase.dart dev ``` The FlutterFire CLI asks for the Firebase project and writes the options of the flavor. On macOS the script runs flutterfire once for each Xcode build configuration of the flavor, and once elsewhere. Then it formats the options and runs each Dart file of `tool/firebase_configured/`, in the order of their names. The module publishes the id of this step as `FirebaseCoreModule.configureStep`, so that the modules that depend on it can [continue the step](https://doc.saymyframe.com/extending/infrastructure-module.md#continuing-a-step) with steps of their own. `firebase_auth` continues it with the script that enables the sign-in methods in the project that you chose, which runs right after it succeeds. A module that has to follow every run of flutterfire, for every flavor, puts a file into `tool/firebase_configured/` instead, as `firebase_crashlytics` does. A run without a terminal, a run that skips external setup, and a run that lacks what the script needs print the command to run later instead, followed by the commands of the steps that continue it. Configure the other flavors with the same script, each for a project of its own or for one that they share, and commit what it writes: ```bash dart tool/configure_firebase.dart staging --project= ``` See [One project for each flavor](https://doc.saymyframe.com/guides/firebase.md#one-project-for-each-flavor), which also lists what repeats for each project. ## Choosing it `smf create` asks which infrastructure modules the app has, and offers this one. It also comes with the other Firebase modules. To choose it without the question: ```bash smf create my_app -m firebase_core ``` # `firebase_crashlytics` Source: https://doc.saymyframe.com/modules/firebase-crashlytics | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_firebase_crashlytics`](https://pub.dev/packages/smf_firebase_crashlytics) | infrastructure | Crash reporting | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | `-m firebase_crashlytics` | `firebase_crashlytics` reports errors to [Firebase Crashlytics](https://firebase.google.com/docs/crashlytics) with the [firebase_crashlytics](https://pub.dev/packages/firebase_crashlytics) package: the errors that the app does not handle, and those that its code reports. ## What it adds to the app The module adds `firebase_crashlytics: ^5.4.0` to the dependencies, and `lib/core/crash_reporting/crashlytics_crash_reporter.dart` with the reporter on `FirebaseCrashlytics.instance`. Whichever module provides it, the crash reporting role adds `lib/core/crash_reporting/crash_reporter.dart` with: - the `CrashReporter` interface, where `recordError` and `recordFlutterError` report an error, `log` adds a message to the log sent with the next report, and `setUserId` sets the id of the signed-in user or clears it with `null`; - `createCrashReporter()`, which returns the reporter of the app, a reporter that forwards every call to the reporters of all the modules that provide crash reporting, each on its own, so an app can report to more than one service and a reporter that fails affects no other; - `installCrashReporting()`, which reports as fatal the errors of the main isolate that the app does not handle. In its platform phase, `bootstrap()` initializes Firebase and then calls `installCrashReporting()`. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the crash reporting role describes the reporter under "Crash reporting". The module adds to report through `CrashReporter` and not through `FirebaseCrashlytics.instance`, and says that `tool/configure_firebase.dart` keeps the build phase working for `flutter build ipa`. ## What gets reported and printed - Flutter still presents an error that it catches, such as one in a build, as it does by default, in every mode. The reporter sends the same report that `recordFlutterError` of Crashlytics sends. - Any other uncaught error goes to `recordError`, and in debug mode the engine still prints it. - The reporter itself prints nothing, so an error that the code of the app reports is not printed either. When a call to Crashlytics fails, the reporter of the app prints the failure in debug mode. - `setUserId(null)` clears the id of the user by setting an empty one, as Crashlytics does. The handlers cover the main isolate. For errors of other isolates, see [Services and state](https://doc.saymyframe.com/guides/services.md#crash-reporting). ## Getting the reporter The reporter is created on first use, without waiting. With a module of dependency injection, the role registers it in the container as a lazy singleton, and a feature takes it with `resolve` in its composition file. Without a container, the code of the app calls `createCrashReporter()`. ## Native setup The module generates nothing in the native projects. `tool/configure_firebase.dart` of [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) has flutterfire add what Crashlytics needs to an app that depends on firebase_crashlytics, such as the build phase that uploads the debug symbols on macOS. The phase of flutterfire_cli 1.4.1 does not find the upload script when `flutter build ipa` archives the app. flutterfire writes the phase again in each of its runs, so the module adds `tool/firebase_configured/fix_crashlytics_phase.dart`, which that script runs after each flavor. On macOS it points the phase at the upload script where Flutter puts it, and elsewhere it does nothing. The Crashlytics section of the README of the app gives its command, for when you run `flutterfire configure` yourself. See [Firebase](https://doc.saymyframe.com/guides/firebase.md#crashlytics-and-flutter-build-ipa). The phase looks up the build configuration in `firebase.json`, so on macOS a build of a flavor that is not configured fails there once another flavor is. See [A flavor that is not configured](https://doc.saymyframe.com/guides/firebase.md#a-flavor-that-is-not-configured). ## Choosing it `smf create` asks which modules provide the crash reporting of the app, and the answer may be none. To choose it without the question, name it in `-m`, and `firebase_core` comes with it: ```bash smf create my_app -m firebase_crashlytics ``` # `firebase_analytics` Source: https://doc.saymyframe.com/modules/firebase-analytics | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_firebase_analytics`](https://pub.dev/packages/smf_firebase_analytics) | infrastructure | Analytics | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | `-m firebase_analytics` | `firebase_analytics` records what the users of the app do, and the screens they see, in [Google Analytics for Firebase](https://firebase.google.com/docs/analytics) with the [firebase_analytics](https://pub.dev/packages/firebase_analytics) package. ## What it adds to the app The module adds `firebase_analytics: ^12.6.0` to the dependencies, and `lib/core/analytics/firebase_analytics_service.dart` with the service on `FirebaseAnalytics.instance`. In an app with a router, that file also has `logFirebaseScreenView`, the listener of the screen. Whichever module provides it, the analytics role adds `lib/core/analytics/analytics_service.dart` with: - the `AnalyticsService` interface: `logEvent` logs an event with its parameters, `logSignIn` and `logSignUp` log that the user signed in or signed up, `setUserId` and `setUserProperty` describe the user and clear what they set with `null`, and `setAnalyticsCollectionEnabled` turns the collection of analytics data on or off; - `createAnalyticsService()`, which returns the analytics service of the app, a service that forwards every call to the services of all the modules that provide analytics. It calls each of them on its own and gives each its own copy of the parameters, so a service that fails, or that changes the parameters, affects no other. An event goes to `logEvent` of Firebase Analytics. A sign-in and a sign-up become its standard `login` and `sign_up` events, with the method in their `method` parameter. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the analytics role describes the service under "Analytics". In an app with a router, the module adds that screen views need no code. ## Screen views When the app has a router, the module gives it `logFirebaseScreenView`, a listener of the screen the user sees. The router calls it once for each change of that screen, as [the router role promises](https://doc.saymyframe.com/extending/role-provider.md#following-the-router): the first screen, a page that a navigation shows or that shows again, the page of the tab the user switches to, and the page on top when it shows another location. For each call, the listener logs a `screen_view` event: - The `screen_name` is the full name of the route, such as `home.home`. The fallback start screen of an app with no route to start on is logged as `/`. The error screen of the router is not logged, because the location it could not show may hold anything, such as a token of a link. - Only the pages of the router count. Pages that the app shows with a navigator directly, such as with `Navigator.push`, and dialogs are not logged. - Nothing waits for a screen view, so an error of the platform in logging one is printed rather than left to the handler of uncaught errors, which a module of crash reporting would report. Without a router, the module records only what the app logs itself. ## Getting the service The service is created on first use, without waiting, so the app starts as fast as it would without it. With a module of dependency injection, the role registers it in the container as a lazy singleton, and a feature takes it with `resolve` in its composition file. Without a container, the code of the app calls `createAnalyticsService()`. ## Native setup The module adds nothing to the native projects. Firebase Analytics needs no setup of its own in the app besides the setup of Firebase, which [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) runs after generation. ## Google Analytics in the project The events of the app reach Google Analytics only once the Firebase project is linked to it, and a project that `flutterfire configure` creates is not. Until then, the app logs its events, but they show up nowhere. So every app of the module lists the step by hand `firebase_analytics.google_analytics`, which turns on Google Analytics in the project, unless it is on already. The link belongs to the project, so repeat this in each Firebase project of your flavors. The README of the app has it under "Finish the setup", and the run ends with the link to its guide. The [click-by-click guide](https://doc.saymyframe.com/setup/firebase-analytics-google-analytics.md) shows each screen. ## Choosing it `smf create` asks which modules provide the analytics of the app, and the answer may be none. To choose it without the question, name it in `-m`, and `firebase_core` comes with it: ```bash smf create my_app -m firebase_analytics ``` # `firebase_messaging` Source: https://doc.saymyframe.com/modules/firebase-messaging | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_firebase_messaging`](https://pub.dev/packages/smf_firebase_messaging) | infrastructure | Push messages | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md), notifications | `-m firebase_messaging` | `firebase_messaging` receives push messages with [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging), through the [firebase_messaging](https://pub.dev/packages/firebase_messaging) package. The app gets the address of the device for its backend, receives the messages that the backend sends there, and hears of the taps on them, including the tap that launched the app. The code of the app never uses the package. It uses `appPush`, which the push role generates; see [Push messages](https://doc.saymyframe.com/guides/notifications.md#push-messages). The role shows a message that arrives in the foreground as a notification of the app, so it needs a module of notifications, and `smf create` adds [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) with this module. ## What it adds to the app | In the app | What it is | | --- | --- | | `firebase_messaging: ^16.7.0` in the dependencies | The package of Firebase Cloud Messaging. 16.7 is the version that works with firebase_core 4, which the Firebase modules share. | | `lib/core/push/firebase_push_service.dart` | `FirebasePushService`, the push service of the app on `FirebaseMessaging.instance`, and `createFirebasePushService()`, which creates it. | | Two `` entries in `android/app/src/main/AndroidManifest.xml` | The channel and the small icon of a message that Android shows in the background. | | The section "Firebase Cloud Messaging" of the README | The key of the Apple Push Notification service, a test message, what the module set up for Android and iOS, and messages in the background. | | The step by hand `firebase_messaging.apns_key` | The upload of the APNs key to the Firebase project; see [the APNs key](#the-apns-key). | Whichever module provides it, the push role adds: | In the app | What it is | | --- | --- | | `lib/core/push/app_push.dart` | `appPush`, through which the code of the app reads the address of the device, the messages and the taps, and `initPush()`. | | `lib/core/push/push_service.dart` | `PushService`, the interface that this module implements, and `PushMessage`. | | The entitlement `aps-environment` with the value `development` in `ios/Runner/Runner.entitlements` | It lets the iOS app receive push messages. Only a paid Apple Developer team signs it, so the role also lists the step by hand `app_entry.ios_app_id`. | | `remote-notification` among the `UIBackgroundModes` of `ios/Runner/Info.plist` | It lets iOS wake the app for a message that arrives in the background. | In its platform phase, `bootstrap()` initializes Firebase, opens the preferences and the notifications, and then starts the push messages. This is `bootstrap()` of an app with this module and the modules that come with it: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await Firebase.initializeApp(options: firebaseOptionsOfFlavor); await initPreferences(); await initNotifications(); await initPush(); } ``` The service is created without waiting, and asks the user nothing. `appPush` asks it for the address without waiting for the answer, so the first frame never waits for the network. The message whose tap launched the app is known once `bootstrap()` is over. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the push role describes `appPush` under "Push messages". The module adds which file is on firebase_messaging, where the address comes from and why the service waits for it on iOS, why it sets the presentation options of iOS, that the app never calls `requestPermission()` of the package, what the manifest names for Android, and what a test that runs `bootstrap()` answers in place of the platform side of the package. The README of the app gets the section "Firebase Cloud Messaging" from the module and the section "Push messages" from the role. ## The address of the device The address in `appPush.address` is the registration token of Firebase Cloud Messaging on the device, from `getToken()`. A new token comes on `onTokenRefresh`, and `appPush.address` follows it. Send each new address to your backend, which sends the messages there; see [Push messages](https://doc.saymyframe.com/guides/notifications.md#push-messages). The address is `null` while Firebase gives no token. Android has none without Google Play services or a network, and iOS has none before the device has a token of the Apple Push Notification service (APNs). In debug mode, the app prints why it has no address yet, and then each new address: ```text The address of this device for push messages: ``` ### The wait on iOS iOS gives the device its APNs token a while after the app started, or never, as for a build that is not signed for push messages. Firebase gives no registration token before that, and when the APNs token comes, firebase_messaging tells the app nothing. So while `appPush` listens for new addresses, which it does from its start, the service asks iOS for the APNs token, a read without the network. It waits half a second before the first try and twice as long before each next one, up to eight seconds, for at most two minutes in all. Once iOS has the token, the service tells of the registration token. After two minutes it stops, and `appPush` asks again each time the user comes back to the app while it has no address. Only a build signed with the entitlement `aps-environment` gets an APNs token. The iOS simulator on a Mac gets one, one on a macOS virtual machine never does, and on an iPhone the signing needs a team of the paid Apple Developer Program; see [Push messages](https://doc.saymyframe.com/guides/notifications.md#push-messages). ## Messages in the foreground and in the background A message that arrives while the app is in the foreground reaches `appPush.messages`. Who shows a message with a title or a body depends on the platform: | | Android | iOS | | --- | --- | --- | | In the foreground | `appPush` shows it as a notification of the app, through `appNotifications`. | The system shows it, with the presentation options of the service. | | In the background, or while the app is closed | The system shows it, in the channel and with the icon that the manifest names. | The system shows it. | Either way, the user has to allow the notifications of the app, and a tap on the message reaches `appPush.taps`, not `appNotifications.taps`. `PushMessage.data` is a `Map`. A value of the data that is not a string, which iOS may give, becomes its JSON. ### Presentation options on iOS On iOS, firebase_messaging answers the system for every notification that arrives while the app is in the foreground, the notifications that the app shows itself with `appNotifications` too. Its presentation options are empty by default, and with them iOS would show none of these notifications in the foreground. So `createFirebasePushService()` sets them to an alert, a badge and a sound when the app starts: ```dart title="lib/core/push/firebase_push_service.dart" PushService createFirebasePushService() { final service = FirebasePushService(FirebaseMessaging.instance); if (service.platformShowsInForeground) { unawaited( FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, ), ); } return service; } ``` `platformShowsInForeground` is true on iOS only. Keep the call, or the local notifications of the app stop showing in the foreground too. ### Messages in the background The app runs no code for a message that arrives in the background. A message with data and no title or body reaches the app only while it is in the foreground. To handle a message in the background, register a top-level function with `FirebaseMessaging.onBackgroundMessage()` in `main()`. It runs in an isolate of its own, without what `bootstrap()` sets up. Images in a message do not show on iOS, which needs an extension of the app for them. ## The permission The service never asks for the permission to show notifications, and the code of the app does not call `requestPermission()` of the package either. The permission belongs to `appNotifications.request()` of the notifications role, and a message shows as a notification only once the user has allowed the notifications of the app. See [the permission](https://doc.saymyframe.com/guides/notifications.md#the-permission). ## The channel and the icon on Android The manifest names the channel and the small icon of the notifications of the app as those of Firebase Cloud Messaging: ```xml title="android/app/src/main/AndroidManifest.xml" ``` Android shows a message that arrives in the background with them: in the channel `default`, which the module of notifications creates when the app starts, and with the small icon `ic_notification` of the notifications role. If you change the channel or the icon of the notifications, change these two lines too; see [the channel and the small icon](https://doc.saymyframe.com/modules/local-notifications.md#the-channel-and-the-small-icon). ## The APNs key Firebase sends messages to iOS through APNs, with an APNs key of your team, which you upload to the Firebase project by hand, once. A key sends only to the apps of its team, so the App ID of the app has to be registered in that team, with Push Notifications. The key matters only for sending: the iOS app gets its address without it, but Firebase cannot send to that address. [Cloud Messaging](https://doc.saymyframe.com/guides/firebase.md#cloud-messaging) has the steps, and how to send the device a test message from the Firebase console or a server. The README of the app lists the upload of the key and the App ID among the steps that you do by hand, under "Finish the setup", and the click-by-click guides of [the key](https://doc.saymyframe.com/setup/firebase-messaging-apns-key.md) and of [the App ID](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md) show each screen. ## In tests A test that runs `main()` or `bootstrap()` starts Firebase with the options of the flavor of the test, `dev`, which needs a mock of its platform side. firebase_messaging has no platform side for tests either, so such a test answers the method channel `plugins.flutter.io/firebase_messaging` itself, with `setMockMethodCallHandler` of `TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger`. It also needs what a test of the notifications needs; see [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md#in-tests). A test of a screen needs none of this: it gives `appPush.start()` a service of its own, which scripts what a provider answers; see [Notifications](https://doc.saymyframe.com/guides/notifications.md#in-tests). Whichever module provides the push messages, the address is `null` until the service gives one and stays the same at the next start, each message in the foreground reaches `appPush.messages` once, a tap on a message reaches `appPush.taps` and not `appNotifications.taps`, and the provider never asks for the permission. SMF's CI checks this in running apps with the role. For this module, over a stand-in for the platform side that answers the messages of the plugin, it checks what the service sends to Firebase on Android and on iOS: the presentation options on iOS; never `requestPermission`; the registration token as the address; the first address on iOS once the device gets its APNs token; and the messages, the taps, the new tokens and the message that launched the app, with a value of the data that is not a string as its JSON. On devices, it checks that the address of the app, once it has one, is the registration token that the Firebase SDK has. On an Android emulator, it also sends the app with every module a push message from the Firebase project of CI, which has to reach `appPush.messages` with the title and the text that it was sent with. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) and [starting the apps](https://doc.saymyframe.com/contributing.md#starting-the-apps). ## Choosing it `smf create` asks which module provides the push messages of the app, and offers None as well. That question comes before the one about the notifications. To choose the module without the question: ```bash smf create my_app -m firebase_messaging ``` Firebase, the notifications and the preferences come with it, and `smf create` asks no question about the notifications or the preferences while one module provides each: ```text Adding firebase_core: a dependency of firebase_messaging. Adding flutter_core: the only provider of the app entry role, which every app needs. Adding local_notifications: the only provider of the notifications role, which firebase_messaging requires. Adding shared_preferences: the only provider of the preferences role, which local_notifications requires. ``` After generation, `firebase_core` asks whether to configure the flavor `dev`, as for every app with Firebase; see [Firebase](https://doc.saymyframe.com/guides/firebase.md). The module runs no command of its own: you upload the APNs key yourself, and the run ends with the link to the guide of that [step by hand](https://doc.saymyframe.com/guides/smf-create.md#steps-by-hand). # `firebase_auth` Source: https://doc.saymyframe.com/modules/firebase-auth | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_firebase_auth`](https://pub.dev/packages/smf_firebase_auth) | infrastructure | Authentication | [`firebase_core`](https://doc.saymyframe.com/modules/firebase-core.md) | `-m firebase_auth` | `firebase_auth` signs the users of the app in with [Firebase Authentication](https://firebase.google.com/docs/auth), through the [firebase_auth](https://pub.dev/packages/firebase_auth) package: with an email address and a password, as anonymous users, and with the credentials of the ways to sign in of Google and Apple that [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) add. The module brings the service and no screens. The screens of sign-in are the feature [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), which requires a module such as this one. The code of the app signs in, up and out through `appSession`, which the auth role generates; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md). ## What it adds to the app | In the app | What it is | | --- | --- | | `firebase_auth: ^6.7.0` in the dependencies | The package of Firebase Authentication. | | `lib/core/auth/firebase_auth_service.dart` | `FirebaseAuthService`, the sign-in service of the app on `FirebaseAuth.instance`. | | `tool/enable_firebase_sign_in.dart` | The script that enables the ways to sign in in the Firebase project, and sets up what Google needs. | | The section "Firebase Authentication" of the README | How the ways to sign in are enabled, with the script and in the Firebase console, and in an app with Google or Apple what the script sets up for them and what is left to you. | | Steps by hand, in an app with Apple or Google | What no command sets up for these ways to sign in; see [Google and Apple](#google-and-apple). | Whichever module provides it, the auth role adds four files in `lib/core/auth/`: | File | What it holds | | --- | --- | | `app_session.dart` | `appSession`, which tells who uses the app and through which code signs in, up and out, `authMode`, the mode of the app, and `initAuth()`. | | `auth_service.dart` | `AuthService`, the interface that this module implements, and `AuthFailure` with its reasons. | | `guest_data.dart` | `takeGuestData()`, which you edit: what an anonymous user has when they sign in to an account that exists already. | | `sign_in_methods.dart` | `appSignInMethods`, the ways to sign in with an identity provider of the app, such as Google; see [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). | In its platform phase, `bootstrap()` initializes Firebase and then starts the session. This is `bootstrap()` of an app with this module alone: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await Firebase.initializeApp(options: firebaseOptionsOfFlavor); await initAuth(); } ``` Firebase keeps the user on the device and hands that user over when it is initialized. So the service is created without waiting and has the user at once, and the app knows who is signed in before its first frame. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the auth role describes the session under "Authentication". The module adds which file is on Firebase Authentication, where a code of Firebase gets its reason, that the ways to sign in are enabled in the Firebase project, and that an agent runs the script that enables them only when asked. In an app with Google, it adds what the script does for Google, and with Apple, that Apple is enabled in the Firebase console with a private key that never goes into the app. ## Enable the ways to sign in The ways to sign in are enabled in the Firebase project, not in the code: - Email/Password, in every mode of the app; - Anonymous, when the [mode](https://doc.saymyframe.com/guides/sign-in.md#the-mode) of the app is `anonymous`; - Google and Apple, for the [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in) of the app. The script of the app enables those of them that the app needs, all of them except Apple, with the [Firebase CLI](https://firebase.google.com/docs/cli) 15.34.0 or later: ```bash dart tool/enable_firebase_sign_in.dart ``` In a terminal, `smf create` offers to run it right after `dart tool/configure_firebase.dart dev` configured the app. The question has a notice of what the script does for a way to sign in of Google, which changes the Firebase project and files of the app. A step cannot tell which ways to sign in the app has, so the question is the same in every app. The Firebase console enables the methods without the script, under [Authentication > Sign-in method](https://console.firebase.google.com/project/_/authentication/providers) of the project that the app is configured for. The script reads the project from `firebase.json` and the mode from `authMode` of the app, and never disables a method. It changes no file of the app but those that Google needs. A run covers one project, so where flavors have projects of their own, run it with `--project ` for each. Run it again after you changed the mode to `anonymous`. [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication) describes the question, what the script does and its arguments, such as `--project ` and `--account `. Until the ways to sign in are enabled, signing in and signing up fail with the reason `notConfigured`, and the `developerHint` of the failure tells both ways: ```text AuthFailure: notConfigured (Sign-in is not enabled in the Firebase project my-project (Firebase answered operation-not-allowed). To fix it, run `dart tool/enable_firebase_sign_in.dart` in the directory of the app, or enable Email/Password, and Anonymous for an app that signs in anonymous users, in the Firebase console under Authentication > Sign-in method: https://console.firebase.google.com/project/my-project/authentication/providers) ``` In the mode `anonymous`, the app also starts without a user until Anonymous is enabled. Before it generates the app, SMF checks the machine for a Firebase CLI that enables the methods without adding a web app to the project, as "Firebase CLI 15.34.0 or later". The check only warns. With an older Firebase CLI, the run tells how to update it and prints the command of the script for later. The script asks the Firebase CLI for its version too, and stops with what to do when it is older. ## Google and Apple The service takes the credentials of the ways to sign in of Google and Apple. `signInWith` and `linkWith` give Firebase a credential of Google with its ID token, and one of Apple with its ID token, its raw nonce and the name of the user. `AuthUser.issuers`, and so `AccountSession.issuers`, comes from the identities that Firebase lists for the user. The `validate` hook of the provider reports a way to sign in of another identity provider, since Firebase would not take its credential, and a way to sign in whose needs the script cannot set up for its identity provider. The problem names the module of that way to sign in, so `smf create` leaves that module out of the app with a warning and generates the rest, and with `--strict` it stops instead; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). | What the service does | Why | | --- | --- | | When Firebase refuses to link a credential, because its identity or its email address belongs to another user, the service keeps what Firebase gave back for that credential object, and a sign-in with the identical object uses it once. A credential of Apple can be taken only once. | `appSession` signs in to the account that has the identity with the same object. | | A link that Firebase refuses fails with `credentialInUse` for an identity that another user has, and with `accountExistsWithOtherMethod` for an email address that has an account. | The same codes of Firebase mean `emailInUse` for a link with a password. | | `deleteAccount` with a fresh credential signs the user in again with it, then revokes the tokens of Apple with the authorization code of the credential, on iOS and macOS, and then deletes the user and signs out. A credential of Google revokes nothing. | The App Store asks an app with Sign in with Apple to revoke its tokens when the user deletes the account. | | A revocation that fails keeps the account and fails with `notConfigured`, unless the answer is no matter of the setup: no network, too many attempts, a disabled user, or a session that has ended. | Firebase revokes the tokens of Apple with the key of Apple that you set in the console, and a missing key is a mistake of the setup. | | A confirmation with the credential of another user fails with `invalidCredentials`, and so does one of an identity that has no user. For the latter the service reloads the user first: a user whom the server deleted is signed out, and the call fails with `recentSignInRequired`. | Firebase answers the first with `user-mismatch` and the second with `user-not-found`, which for another call means a session that has ended. | | A credential of Apple without a raw nonce, and on iOS and macOS a fresh one without an authorization code, fails with `notConfigured` before Firebase is asked. | Firebase needs the nonce, and a deletion without the code would skip the revocation. | Google needs more of the Firebase project than an enabled method: the SHA of the keys of the Android app, its clients in the Firebase files of the app, and the URL scheme of the iOS app. The script of the app sets these up for the project that `firebase.json` names, and gives Google the name of the app and the email address of the account of the Firebase CLI for its consent screen. The SHA of a release, of the upload key and of the app signing key of Google Play, is yours to add. No command of the Firebase CLI enables Apple, so the script tells what to set in the Firebase console, where the deletion of an account that signs in with Apple also needs the Services ID and the key of Apple. [Firebase](https://doc.saymyframe.com/guides/firebase.md#google) has each step. What no command does, the module lists among the steps by hand of the app, by its ways to sign in: `firebase_auth.apple_provider` and `firebase_auth.apple_revocation` for Apple, and `firebase_auth.google_release_sha` for a way to sign in that needs the certificate of the Android app, such as Google. The README of the app lists them under "Finish the setup", and the run ends with the link to their guide. The click-by-click guides show each screen: [the Apple provider](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md), [the Apple key](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md) and [the SHA of a release](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md). Until a way to sign in is enabled, signing in with it fails with `notConfigured`. The hint names the way, and for Google the script too: ```text AuthFailure: notConfigured (Sign-in with Google is not enabled in the Firebase project my-project (Firebase answered operation-not-allowed). To fix it, run `dart tool/enable_firebase_sign_in.dart` in the directory of the app, or enable Google in the Firebase console under Authentication > Sign-in method: https://console.firebase.google.com/project/my-project/authentication/providers) ``` ## The reasons of a failure A call of `appSession` fails only with an `AuthFailure`, whose `reason` the app shows a text for. The service gives each code of Firebase its reason, in `_failureOf()` of its file: | Reason | Codes of Firebase | | --- | --- | | `invalidCredentials` | `invalid-credential`, `invalid-login-credentials`, `wrong-password`, `user-not-found`, `missing-or-invalid-nonce`, `user-mismatch` | | `emailInUse` | `email-already-in-use` and `credential-already-in-use`, outside a link of a credential | | `credentialInUse` | `credential-already-in-use` in a link of a credential | | `accountExistsWithOtherMethod` | `account-exists-with-different-credential`, and `email-already-in-use` in a link of a credential | | `weakPassword` | `weak-password`, `password-does-not-meet-requirements` | | `invalidEmail` | `invalid-email`, `missing-email` | | `userDisabled` | `user-disabled` | | `tooManyAttempts` | `too-many-requests` | | `network` | `network-request-failed` | | `recentSignInRequired` | `requires-recent-login` | | `notConfigured` | `operation-not-allowed`, `admin-restricted-operation`, and any code whose message has `CONFIGURATION_NOT_FOUND` | | `unknown` | Any other code. The `developerHint` has the code and the message of Firebase on one line. | Two cases need more than the code: - Firebase tells of a project in which Authentication was never set up only in a message: that of an unknown error on Android, and that of an internal error on iOS, where the message is the description of the error over many lines. The service finds `CONFIGURATION_NOT_FOUND` there and answers `notConfigured`. The hint names the code and `CONFIGURATION_NOT_FOUND`, and leaves the description out. - On iOS and macOS, Firebase may answer for such a project with an internal error whose message says no more. Nothing tells it from another internal error, so the service answers `notConfigured` there too, with a hint that says that it may be another error. A code that the service does not know becomes `unknown`. To give it a reason, add it to `_failureOf()`. ## What the service adds to the package The auth role promises more than the package does in a few places, and the service makes up the difference: | What the service does | Why | | --- | --- | | An empty address or password fails before Firebase is asked. An empty address is `invalidEmail`. An empty password is `invalidCredentials` in a sign-in, and `weakPassword` in a sign-up. | Android refuses an empty text with a code that has no reason, and iOS answers an empty password as a wrong one. | | A user has no address when Firebase has an empty one. | Android has an empty address, not none, for an anonymous user whom it kept on the device. | | It signs out after it deleted a user. | The package keeps a deleted user as its current one until the platform tells it of the sign-out. | | A call for the user who is signed in, such as the deletion of the account, signs that user out first when the session of the user has ended on the server, and fails with `recentSignInRequired`. Firebase answers such a call with `user-token-expired`, `invalid-user-token`, `user-not-found` or `no-current-user`. | A session ends on the server when the account is deleted, or its password changed, on another device. | | A password reset completes when Firebase answers `user-not-found`. | A project without the protection against the enumeration of email addresses tells that an address has no account, and the app should not. | | It tells of the user after each of its calls and when Firebase tells of a change, each time with the user that it has when a listener hears of it. | A listener then never hears of a user who is not the current one any more. | The service is the same in every mode of the app. ## The message of a password reset Firebase sends the message with which a user sets a new password from a template of the project: [Authentication > Templates](https://console.firebase.google.com/project/_/authentication/emails) in the Firebase console. The module uses the localization role. In an app with it, the service gives Firebase the language that the app is in before it asks for the message: the language that the user chose, or the one that the device prefers among those of the app. ```dart title="lib/core/auth/firebase_auth_service.dart" // The message is in the language that the app is in. await _auth.setLanguageCode( (appLocale.value ?? basicLocaleListResolution( WidgetsBinding.instance.platformDispatcher.locales, appLocales, )) .languageCode, ); ``` In an app without the role, the service sets no language. ## Anonymous users In the mode `anonymous`, the app signs in an anonymous user when it starts, and signing up gives that same user the account. While an anonymous user is signed in, Firebase answers a further anonymous sign-in with that user and creates no other. When an anonymous user signs in to an account that exists already, the anonymous user stays in the Firebase project, and nobody can sign in as that user again. A project that is upgraded to Firebase Authentication with Identity Platform can delete anonymous users that are older than 30 days automatically; see [Automatic clean-up](https://firebase.google.com/docs/auth/android/anonymous-auth#auto-cleanup) in the documentation of Firebase. What the app itself keeps under the id of the anonymous user moves as `takeGuestData()` says; see [the data of a guest](https://doc.saymyframe.com/guides/sign-in.md#the-data-of-a-guest). ## In tests A test that runs `main()` or `bootstrap()` starts Firebase with the options of the flavor of the test, `dev`, which needs a mock of its platform side, and the firebase_auth plugin brings no mock of its own platform side for tests. A test of a screen needs neither: it gives `appSession.start()` a service of its own; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#in-tests). SMF's CI checks the service on the real firebase_auth package, over a stand-in for its platform side that answers the messages of the plugin: what each call sends to Firebase, the reason for each code as Android and iOS send it, and the user whom a start finds on the device. The stand-in takes the test tokens of the ways to sign in of Google and Apple, takes a token with a nonce once, and answers a refused link with a credential of its own, so the test of the ways to sign in of the auth role runs on this module too. On devices it checks that the session of the app has the user that the plugin has. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it `smf create` asks which module provides the authentication of the app, and offers None as well. With a provider chosen, it then asks who may use the app without an account. To choose both without the questions: ```bash smf create my_app -m firebase_auth --auth-mode guest ``` `firebase_core` comes with the module: ```text Adding firebase_core: a dependency of firebase_auth. Adding flutter_core: the only provider of the app entry role, which every app needs. ``` The feature [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) requires the role that this module provides, so `-m sign_in` brings the module too while it is the only one that provides sign-in. After generation, `firebase_core` asks whether to configure the flavor `dev`, as for every app with Firebase, and this module then asks whether to enable the ways to sign in; see [Firebase](https://doc.saymyframe.com/guides/firebase.md). [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) require the role too, so each brings this module while it is the only one that provides sign-in. # `google_sign_in` Source: https://doc.saymyframe.com/modules/google-sign-in | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_google_sign_in`](https://pub.dev/packages/smf_google_sign_in) | infrastructure | none | a provider of the authentication, such as [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | `-m google_sign_in` | `google_sign_in` lets the users of the app sign in with their Google account on Android and iOS, through the [google_sign_in](https://pub.dev/packages/google_sign_in) package. It is a way to sign in next to the email address and the password: the module asks Google for a credential, and the module that provides the authentication signs the user in with it. The module has no screen. A screen of sign-in, such as those of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), shows its button, and code of your own can use it too. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in) describes the ways to sign in of an app and what `appSession` does with their credentials. ## What it adds to the app | In the app | What it is | | --- | --- | | `google_sign_in: ^7.2.0` in the dependencies | The package of Google sign-in. | | `lib/core/google_sign_in/google_sign_in.dart` | `googleCredential()`, which asks Google for a credential, and `GoogleSignInIcon`, the icon of its button. | | `lib/core/google_sign_in/assets/google_logo.png`, and a file of the same name in `2.0x/` and `3.0x/` next to it | The "G" of Google, an image of 18 logical pixels, with a file for the screens with two and with three pixels for a logical pixel. `pubspec.yaml` declares the first one among the assets, and Flutter finds the others next to it. | | The section "Google sign-in" of the README | What Google needs of the Google project and of the app, where google_sign_in reads the ids of the clients of Google, what to check when the button fails, and that the logo stays as it is. | The module gives the auth role its way to sign in. Whichever module provides the role, the role lists it in `appSignInMethods` of `lib/core/auth/sign_in_methods.dart`. In an app with this module alone: ```dart title="lib/core/auth/sign_in_methods.dart" const List appSignInMethods = [ SignInMethod( label: _googleSignInLabel, icon: method0.GoogleSignInIcon(), platforms: {TargetPlatform.android, TargetPlatform.iOS}, credential: method0.googleCredential, issuer: 'https://accounts.google.com', ), ]; ``` | | The way to sign in with Google | | --- | --- | | Label | Continue with Google, the text that the branding guidelines of Google give such a button, and ΠŸΡ€ΠΎΠ΄ΠΎΠ²ΠΆΠΈΡ‚ΠΈ Π· Google in Ukrainian. In an app without a module that provides the localization, the label is in English. | | Icon | `GoogleSignInIcon`, the "G" of Google in its own colors. | | Platforms | Android and iOS. A screen of sign-in shows its button on no other. | | Issuer | `https://accounts.google.com`. `AccountSession.issuers` names Google by it. | | For the App Store | A login service of a third party; see [the App Store](#the-app-store). | | What it needs of the backend | Google knows the Android app by the SHA-1 of the keys that sign it, and the app needs an iOS client and the server client of Google; see [what Google needs](#what-google-needs). | | Deleting an account | Asks Google nothing: `revokesOnDeletion` is `false`. | In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "Google sign-in": which file asks Google and how it starts the package, which errors become which reason, what the icon shows, and what a test replaces to sign in with Google. ## Signing in with it `googleCredential()` shows the sheet of Google sign-in and returns the ID token of the Google account that the user chose, as an `IdTokenCredential` of the issuer of Google, without a raw nonce or an authorization code. A screen of sign-in calls it as `credential()` of the way to sign in, from its state, and gives the credential to `appSession.signInWith`. Here `method` is the way to sign in from `appSignInMethods`: ```dart final credential = await method.credential(); if (credential == null) return; // The user closed the sheet of Google. await appSession.signInWith(credential); ``` Call it from the state of a screen, never within a call of `appSession`. An anonymous user who signs in with Google gets the identity and keeps the id, or signs in to the account that has it already; see [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). The first call starts google_sign_in with `GoogleSignIn.instance.initialize()`. It does so once, and without the ids of the clients of Google, so the package reads them from the files of the app; see [what Google needs](#what-google-needs). | What Google answers | What `googleCredential()` does | | --- | --- | | The user closed the sheet, `canceled` | It returns `null`. That is no failure: the screen goes back to how it was. | | `canceled` with `Account reauth failed` in its description | It fails with `notConfigured`. Credential Manager answers so on Android after the user picked an account, when Google does not know the SHA-1 of the key that signed the app, and also when the device cannot reach Google. | | `clientConfigurationError` or `providerConfigurationError` | It fails with `notConfigured`. | | `unknownError` with the code `28444` in its description | It fails with `notConfigured`. Credential Manager answers so on Android when Google does not take the server client of the app as a web client of the Google project. | | Any other error, or an account without an ID token | It fails with `unknown`, with the error in the `developerHint`. | The `developerHint` of `notConfigured` has what Google answered and names the section of the README: ```text AuthFailure: notConfigured (Google sign-in is not set up for the app (). See the section "Google sign-in" of the README of the app.) ``` ## What Google needs The Google project of the app has to know the app, and the app has to know the clients of Google: | | What Google needs | | --- | --- | | Android | Google knows the app by the name of its package and the SHA-1 of each key that signs it: the debug key of each machine that builds the app, the upload key, and the app signing key of Google Play. | | iOS | The app needs the id of its iOS client of Google, and the reversed id of that client as a URL scheme in `CFBundleURLTypes` of `ios/Runner/Info.plist`. Through it the sheet of Google returns to the app. | | Both | Google issues the ID token to the server client, the web client of the Google project. The backend of the provider of the authentication checks the token against it. | google_sign_in reads the ids from the files of the app: on iOS `CLIENT_ID` of `GoogleService-Info.plist`, or `GIDClientID` of `ios/Runner/Info.plist`, and on Android the string resource `default_web_client_id`. The module passes it none. To use ids of your own, pass them to `initialize()` in `googleCredential()`. The module states these needs to the provider of the authentication, which sets them up or tells in its section of the README how to. With `firebase_auth`, the script of the app does most of it. `smf create` offers to run it after `dart tool/configure_firebase.dart dev`, and you can run it later: ```bash dart tool/enable_firebase_sign_in.dart ``` The script enables Google in the Firebase project, with the name of the app and the email address of the account of the Firebase CLI for the consent screen of Google. For the apps that `firebase.json` names in the project of the run, it also registers the SHA-1 and SHA-256 of the Android debug key of the machine that runs it, downloads their Firebase files again once they have the clients of Google, and writes the URL scheme of each iOS app into `ios/Runner/Info.plist`. The flavors share that file, so it lists a scheme for each iOS app that the script ran for. Each project of your flavors needs a run of its own. Every machine has a debug key of its own, so run the script on each machine that builds the app for debugging. A release is signed with other keys: add the SHA-1 and SHA-256 of the upload key and of the app signing key of Google Play to the Android app in the Firebase project. [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#google-and-apple) describes the script and the command for those keys. With `firebase_auth`, these keys are a step by hand of the app, under "Finish the setup" of its README, and the [click-by-click guide](https://doc.saymyframe.com/setup/firebase-auth-google-release-sha.md) shows where to find them and where to add them. Until Google sign-in is set up, signing in with Google fails with `notConfigured`. On iOS, one mistake shows differently: the Google Sign-In SDK stops the app when the app has no iOS client of Google or not its URL scheme. google_sign_in does not catch the exception that the SDK throws then. Set both up before you try the button on iOS. On Android, when the setup is the cause, the `developerHint` has one of these two answers of Credential Manager: - `[16] Account reauth failed.`, after the user picked an account: Google does not know the SHA-1 of the key that signed this build of the app. Register the SHA-1 of that key; for a release, that is the upload key or the app signing key of Google Play. A device that cannot reach Google gets the same answer. - `[28444] Developer console is not set up correctly.`: Google does not take the server client of the app as a web client of the Google project, as when `initialize()` gets the id of the Android client as its `serverClientId`. Use the id of the web client. ## The button ![The sign-in of sign_in in the light theme: the title Sign in with the line Choose how to sign in to your account. below it, the white buttons Continue with Google, with the colored G, and Continue with Apple, with the Apple logo, then or and the form for an email address and a password.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png) ![The same sign-in in the dark theme: the two buttons stay white, with a black label and icon.](https://doc.saymyframe.com/demo/0.8/app_sign_in_dark.png) `GoogleSignInIcon` shows the "G" from the assets of the app, at the size of the `IconTheme` around it. It leaves the name of Google to the label of the button, so a screen reader does not read the image. The image is the colored "G" of the [Google Sign-In SDK for iOS](https://github.com/google/GoogleSignIn-iOS) 10.0.0: the files `google.png`, `google@2x.png` and `google@3x.png` of its resources, under the Apache License 2.0. Google and the Google "G" logo are trademarks of Google LLC. The [branding guidelines of Sign in with Google](https://developers.google.com/identity/branding-guidelines) ask a custom button to show that logo in its own colors, on a light background, without a change. Keep the image as it is. [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#other-ways-to-sign-in) shows the button above the form of the sign-in and of the sign-up. It draws the button white with a grey hairline, with the label and the icon in black, in the light theme and in the dark one, so the "G" stays on white. The icon is 20 logical pixels and keeps that size at a large text size. ## The App Store For the App Store, Google sign-in is a login service of a third party. App Store Review Guideline 4.8 asks an app on iOS that offers one to offer an equivalent way to sign in too: one that asks for no more than the name and the email address of the user and lets the user keep the address private. Sign in with Apple is such a way, and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) adds it: ```bash smf create my_app -m google_sign_in,apple_sign_in ``` Without such a way to sign in, `smf create` gives the warning `auth.no_equivalent_sign_in`, and the section "Sign-in" of the README of the app says that the review may reject the app. With `--strict`, the warning stops the run with exit code 1 before anything is generated, and the run names it: ```text warning [role:auth] auth.no_equivalent_sign_in: The app offers Continue with Google on iOS, a login service of a third party, but no way to sign in that the App Store takes as an equivalent: one that asks for no more than the name and the email address of the user and lets the user keep the address private (App Store Review Guideline 4.8). (Add such a way to sign in on iOS, such as Sign in with Apple.) ``` Add `apple_sign_in` to `-m`, and the warning goes away. An app that does not go to the App Store can live with the warning: a run without `--strict` prints it and generates the app; see [Lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). ## In tests A test that calls `googleCredential()`, as a tap on the button does, replaces the platform side of google_sign_in. The package asks `GoogleSignInPlatform.instance` of [google_sign_in_platform_interface](https://pub.dev/packages/google_sign_in_platform_interface), which the app does not depend on as generated, so the test adds it as a dev dependency. Before the first call of `googleCredential()`, the test sets that instance to a subclass of `GoogleSignInPlatform` that answers `init` and `authenticate`: the app starts the package once in a test file. SMF's CI tests the module in every app with it, in each mode of the auth role, on the real google_sign_in package over such a stand-in, which answers for one Google account. Its ID tokens are test tokens: JSON Web Tokens without a signature whose payload has the issuer of Google, the account and its email address. They have no nonce, since the app starts the package without one, and the mocks of the provider of the authentication take them. The test checks that the package starts once and without ids, the credential, the outcome of each answer of Google, that the app lists the way to sign in on Android and iOS, and that the logo loads with its file for each density. The test of the ways to sign in of the auth role then signs in with the credential on `firebase_auth`. Nobody can sign in on a device, so the start check of CI has no probe for the module. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it After the features, `smf create` asks "Infrastructure: which do you want?" and offers the module there: ```text google_sign_in β€” Google sign-in on Android and iOS with google_sign_in ``` The module requires sign-in, and `firebase_auth` is the only module that provides it, so it comes without a question, and `firebase_core` with it: ```text Adding firebase_auth: the only provider of the authentication role, which google_sign_in requires. Adding firebase_core: a dependency of firebase_auth. ``` The run then asks who may use the app without an account, as for every app with sign-in. To choose the modules without the questions, here with the screens of sign-in, BLoC, tabs at the bottom and Sign in with Apple: ```bash smf create my_app -m home,sign_in,bloc,bottom_tabs,google_sign_in,apple_sign_in ``` After generation, `firebase_core` asks whether to configure the flavor `dev`, and `firebase_auth` then asks whether to run the script that enables the ways to sign in and sets up Google; see [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication). # `apple_sign_in` Source: https://doc.saymyframe.com/modules/apple-sign-in | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_apple_sign_in`](https://pub.dev/packages/smf_apple_sign_in) | infrastructure | none | a provider of the authentication, such as [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md) | `-m apple_sign_in` | `apple_sign_in` lets the users of the app sign in with their Apple Account on iOS, with [Sign in with Apple](https://developer.apple.com/sign-in-with-apple/) through the [sign_in_with_apple](https://pub.dev/packages/sign_in_with_apple) package. It is a way to sign in next to the email address and the password: the module asks Apple for a credential, and the module that provides the authentication signs the user in with it. On Android the app has no Sign in with Apple. The module has no screen. A screen of sign-in, such as those of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md), shows its button, and code of your own can use it too. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in) describes the ways to sign in of an app and what `appSession` does with their credentials. ## What it adds to the app | In the app | What it is | | --- | --- | | `sign_in_with_apple: ^8.2.0` and `crypto: ^3.0.7` in the dependencies | The package of Sign in with Apple, and the package that hashes the nonce of a request. | | `lib/core/apple_sign_in/apple_sign_in.dart` | `appleCredential()`, which asks Apple for a credential, and `AppleSignInIcon`, the icon of its button. | | `com.apple.developer.applesignin` in `ios/Runner/Runner.entitlements` | The entitlement of the capability Sign in with Apple, with the step by hand `app_entry.ios_app_id`; see [the capability](#the-capability). | | The section "Sign in with Apple" of the README | What the capability needs of the team that signs the app, what Apple gives only at the first sign-in, what a deletion asks of Apple and of the backend, and that App Review checks the logo of the button. | The module signs the iOS app with the entitlement through a socket of the app entry, whichever module provides the app entry; see [the sockets of the app entry](https://doc.saymyframe.com/concepts/sockets.md#the-sockets-of-the-app-entry): ```xml title="ios/Runner/Runner.entitlements" com.apple.developer.applesignin Default ``` The module gives the auth role its way to sign in. Whichever module provides the role, the role lists it in `appSignInMethods` of `lib/core/auth/sign_in_methods.dart`. In an app with this module alone: ```dart title="lib/core/auth/sign_in_methods.dart" const List appSignInMethods = [ SignInMethod( label: _appleSignInLabel, icon: method0.AppleSignInIcon(), platforms: {TargetPlatform.iOS}, credential: method0.appleCredential, issuer: 'https://appleid.apple.com', revokesOnDeletion: true, ), ]; ``` | | The way to sign in with Apple | | --- | --- | | Label | Continue with Apple, one of the titles that Apple allows a custom button of Sign in with Apple, and ΠŸΡ€ΠΎΠ΄ΠΎΠ²ΠΆΠΈΡ‚ΠΈ Π· Apple in Ukrainian. In an app without a module that provides the localization, the label is in English. | | Icon | `AppleSignInIcon`, the Apple logo of the Material icons, `Icons.apple`, in the color of the label; see [the button](#the-button). | | Platforms | iOS. A screen of sign-in shows its button on no other. | | Issuer | `https://appleid.apple.com`. `AccountSession.issuers` names Apple by it. | | For the App Store | The equivalent of a login service of a third party; see [the App Store](#the-app-store). | | What it needs of the backend | Nothing that the module states. Deleting an account needs a key of Apple at the provider of the authentication; see [deleting an account](#deleting-an-account). | | Deleting an account | Asks Apple again first: `revokesOnDeletion` is `true`. | In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the module writes the section "Sign in with Apple": which file asks Apple and what it returns, that Apple gives the name only at the first sign-in, which errors become which reason, the entitlement, and what a test sets to sign in with Apple. ## Signing in with it `appleCredential()` shows the sheet of Sign in with Apple. It asks for the email address and the full name of the user, with the SHA-256 hash of a new random nonce of `generateNonce()`, which Apple writes into the ID token. It returns an `IdTokenCredential` of the issuer of Apple with: - the ID token of Apple; - the raw nonce itself, against which the provider of the authentication checks the token; - the authorization code of the request, with which the provider can revoke the tokens that Apple gave the app; - the given name and the family name of the user. A screen of sign-in calls it as `credential()` of the way to sign in, from its state, and gives the credential to `appSession.signInWith`. Here `method` is the way to sign in from `appSignInMethods`: ```dart final credential = await method.credential(); if (credential == null) return; // The user closed the sheet of Apple. await appSession.signInWith(credential); ``` Call it from the state of a screen, never within a call of `appSession`. An anonymous user who signs in with Apple gets the identity and keeps the id, or signs in to the account that has it already; see [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in). Apple gives the name of the user only the first time that the user signs in to the app. The credential has it then, and a later one has none, so do not expect it there. The user may also hide the email address. The account then gets an address of the private relay of Apple, which forwards messages to the user. | What happens | What `appleCredential()` does | | --- | --- | | The app runs on a platform other than iOS | It fails with `notConfigured` without asking Apple. On Android, the hint is `Sign in with Apple works on iOS only, and the app runs on android.` | | The user closed the sheet, `canceled` | It returns `null`. That is no failure: the screen goes back to how it was. | | Apple answers with an unknown error, `unknown` | It fails with `notConfigured`. Apple answers so when the app is not signed with the capability, and may do so on a device without an Apple Account. | | Any other error, or a credential without an identity token | It fails with `unknown`, with the error in the `developerHint`. | The `developerHint` of the unknown error names the capability and the section of the README: ```text AuthFailure: notConfigured (Apple answered with an unknown error (). It does so when the app is not signed with the capability Sign in with Apple, which needs a team of the paid Apple Developer Program, and may do so on a device without an Apple Account. See the section "Sign in with Apple" of the README of the app.) ``` The provider of the authentication has to take Apple too. With `firebase_auth`, Apple is enabled in the Firebase console, under Authentication > Sign-in method, since the Firebase CLI cannot enable it. Until then, signing in with Apple fails with `notConfigured`, and the hint tells how to enable it. ## The capability Sign in with Apple is a capability of the app. The key `com.apple.developer.applesignin` in `ios/Runner/Runner.entitlements` asks for it, and every build configuration of the Runner target signs with that file. The App ID of the app needs the capability too: when Xcode manages the signing of the app, it adds the capability to the App ID. Signing with the capability needs a team of the paid Apple Developer Program. So the app lists the step by hand `app_entry.ios_app_id`, in which you sign the app once in Xcode with your paid team, which registers the App ID with the capability. The README of the app has it under "Finish the setup", and the [click-by-click guide](https://doc.saymyframe.com/setup/app-entry-ios-app-id.md) shows each screen. A free personal team cannot sign the app for an iPhone. To run the app there, remove the key from `ios/Runner/Runner.entitlements`. Signing in with Apple then fails with `notConfigured`, as in any app without the capability. ## Deleting an account App Store Review Guideline 5.1.1(v) asks an app with Sign in with Apple to revoke the tokens that Apple gave it when the user deletes the account. So on iOS, for an account that signs in with Apple, `appSession.deleteAccount()` first calls `appleCredential()` itself, and the sheet of Apple shows again. The provider of the authentication then signs the user in again with the new credential, revokes the tokens of Apple with its authorization code, and deletes the account. If the user closes the sheet, nothing is deleted, and that is no failure. The backend needs a key of Apple to revoke the tokens. With `firebase_auth`, the settings of the Apple provider in the Firebase console take the Services ID and the OAuth code flow configuration: your Apple team ID, and the Key ID and the private key of a key for Sign in with Apple. The private key is a secret: enter it in the console yourself, and never put it into the app or its repository. Until they are set, deleting an account that signs in with Apple fails with `notConfigured`, and the account stays. See [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#google-and-apple). Adding Apple in the Firebase console and entering the key there are steps by hand of an app with `firebase_auth`, and the click-by-click guides of [the provider](https://doc.saymyframe.com/setup/firebase-auth-apple-provider.md) and of [the key](https://doc.saymyframe.com/setup/firebase-auth-apple-revocation.md) show each screen. The screen of the account of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) has a text of its own for such a failure. It has one too for a confirmation with another Apple Account, which the provider refuses with `invalidCredentials`, deleting nothing. ## The button ![The sign-in of sign_in in the light theme: the title Sign in with the line Choose how to sign in to your account. below it, the white buttons Continue with Google, with the colored G, and Continue with Apple, with the Apple logo, then or and the form for an email address and a password.](https://doc.saymyframe.com/demo/0.8/app_sign_in.png) ![The same sign-in in the dark theme: the two buttons stay white, with a black label and icon.](https://doc.saymyframe.com/demo/0.8/app_sign_in_dark.png) `AppleSignInIcon` is `Icon(Icons.apple)`, the Apple logo of the Material icons. It takes the color and the size of the `IconTheme` around it, so it has the color of the label of its button. SMF does not ship the logo artwork of Apple, whose license does not allow it. Apple asks a custom button of Sign in with Apple to use the logo artwork of [Apple Design Resources](https://developer.apple.com/design/resources/), and App Review checks every such button. Before you submit the app, download that logo and show it in `AppleSignInIcon` of `lib/core/apple_sign_in/apple_sign_in.dart`. In this sketch the logo is an image of your own, which `pubspec.yaml` declares among the assets of the app, at the size of the icons of the button: ```dart title="lib/core/apple_sign_in/apple_sign_in.dart" class AppleSignInIcon extends StatelessWidget { const AppleSignInIcon({super.key}); @override Widget build(BuildContext context) { final size = IconTheme.of(context).size; // The label of the button names Apple. return Image.asset( 'assets/apple_logo.png', width: size, height: size, excludeFromSemantics: true, ); } } ``` Keep the constructor `const` and without arguments: the list of the ways to sign in creates the icon as a constant. [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md#other-ways-to-sign-in) shows the button above the form of the sign-in and of the sign-up, on iOS only. It draws the button white with a grey hairline, with the label and the icon in black, in the light theme and in the dark one. The icon is 20 logical pixels and keeps that size at a large text size. ## The App Store App Store Review Guideline 4.8 asks an app on iOS that offers a login service of a third party, such as Google sign-in, to offer an equivalent way to sign in too: one that asks for no more than the name and the email address of the user and lets the user keep the address private. The App Store takes Sign in with Apple as such a way. An app with [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and without this module gets the warning `auth.no_equivalent_sign_in` from `smf create`, which stops a run with `--strict`. With this module next to it, the warning goes away: ```bash smf create my_app -m google_sign_in,apple_sign_in ``` See [the App Store](https://doc.saymyframe.com/modules/google-sign-in.md#the-app-store) of `google_sign_in`, and [Lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). ## In tests `appleCredential()` asks Apple only while `debugDefaultTargetPlatformOverride` is `TargetPlatform.iOS`, so a test that calls it, as a tap on the button does, sets that first. The package asks the platform on the method channel `com.aboutyou.dart_packages.sign_in_with_apple`. A test answers its method `performAuthorizationRequest` with a map whose `type` is `appleid`, with `identityToken`, `authorizationCode`, `givenName` and `familyName`. SMF's CI tests the module in every app with it, in each mode of the auth role, on the real sign_in_with_apple package. A stand-in answers its method channel as the plugin does on iOS, for one user of Apple. Each request gets an ID token and a new authorization code, and only the first request of a test file gets the name and the email address, as at the first sign-in in an app. The ID tokens are test tokens: JSON Web Tokens without a signature whose payload has the issuer of Apple, the user, the address of the private relay, and the nonce of the request, which is the SHA-256 hash of the raw nonce, as Apple writes it. The mocks of the provider of the authentication take such tokens. The test checks the request with a new raw nonce each time, the credential, the name at the first sign-in only, the outcome of each answer of Apple, the failure on every platform but iOS, that the app lists the way to sign in on iOS with `revokesOnDeletion`, and the color and the size of the icon. The test of the ways to sign in of the auth role then signs in with the credential on `firebase_auth`, and deletes the account after the session asked for a new credential. Nobody can sign in on a device, so the start check of CI has no probe for the module. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it After the features, `smf create` asks "Infrastructure: which do you want?" and offers the module there: ```text apple_sign_in β€” Sign in with Apple on iOS with sign_in_with_apple ``` The module requires sign-in, and `firebase_auth` is the only module that provides it, so it comes without a question, and `firebase_core` with it: ```text Adding firebase_auth: the only provider of the authentication role, which apple_sign_in requires. Adding firebase_core: a dependency of firebase_auth. ``` The run then asks who may use the app without an account, as for every app with sign-in. To choose the modules without the questions, here with the screens of sign-in, BLoC and tabs at the bottom: ```bash smf create my_app -m home,sign_in,bloc,bottom_tabs,apple_sign_in ``` After generation, `firebase_core` asks whether to configure the flavor `dev`, and `firebase_auth` then asks whether to run the script that enables the ways to sign in. The script cannot enable Apple, which you enable in the Firebase console with the key of Apple; see [deleting an account](#deleting-an-account) and [Firebase](https://doc.saymyframe.com/guides/firebase.md#sign-in-methods-of-firebase-authentication). The run ends with the link to the guide of these [steps by hand](https://doc.saymyframe.com/guides/smf-create.md#steps-by-hand) and of the App ID. # `dio` Source: https://doc.saymyframe.com/modules/dio | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_dio`](https://pub.dev/packages/smf_dio) | infrastructure | REST API | Values in .env | `-m dio` | `dio` sends the requests of `appRest`, the REST client of the app, with [dio](https://pub.dev/packages/dio). The code of the app calls `appRest.get('notes')` and knows nothing of the package. What the client guarantees, such as its failures, its repeats and where the token of the user goes, comes from the role and holds with every provider; see [REST API](https://doc.saymyframe.com/guides/rest.md). The role reads the address of the API from `REST_BASE_URL` in `.env`, so the module brings [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) while that module is the only provider of the values in `.env`. The role uses the authentication: in an app with it, the client adds the token of the user. ## What it adds to the app | In the app | What it is | | --- | --- | | `dio: ^5.11.1` in the dependencies | The package. In `lib/`, only the file below imports it. | | `lib/core/rest/dio_rest_transport.dart` | `DioRestTransport`, which implements `RestTransport` of the role on one `Dio`, and `createDio()`, which creates that `Dio` at the first request | | The section "dio" of the README | What an interceptor may do, and what another adapter needs | Whichever module provides it, the role adds `lib/core/rest/app_rest.dart`, `lib/core/rest/rest_transport.dart`, `lib/core/rest/session_tokens.dart` in an app with sign-in, the key `REST_BASE_URL`, the section "REST API" of the README, two test files and the permission `android.permission.INTERNET`. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the role describes the client under "REST API". The module adds where the transport is, where an interceptor goes and what it may do. ## An interceptor `createDio()` is where an interceptor goes, such as one of a tracing service: ```dart Dio createDio() => Dio()..interceptors.add(TracingInterceptor()); ``` - An interceptor that logs leaves out the header `authorization` and the query of the address, where a token or a key may be. - None repeats a request or follows a redirect. `appRest` does both, since it knows which header may go where. - What `createDio()` adds to a request goes to every address, also after a redirect and to a full address such as a presigned upload. So a credential goes through the token of the session or `headers:` of the call. Several `set-cookie` values cannot be told apart in the `headers` of a response, since a value of that header may have a comma. An API with cookies reads them in an interceptor. ## How it sends The app has one `Dio`, which keeps a connection open while requests follow within seconds, so those requests need no new TLS handshake. It sends each exchange as it is, with no header of `Dio` and no timeout of its own: the client stops each exchange itself. Dio sends over `dart:io`, which reaches an `http://` address with no key in the Android manifest or in `Info.plist`. Another adapter, such as one of [native_dio_adapter](https://pub.dev/packages/native_dio_adapter) for the stack of the platform, goes into `httpClientAdapter` in `createDio()`. It then needs those keys for an `http://` address. A stop ends the call at once. It closes the connection too, unless the connection is still being made. A TLS handshake on its way cannot be ended on `dart:io`, and since the module shares one `HttpClient`, neither can a TCP connect on its way: the socket closes once the system ends it. `HttpClient` decodes a `content-encoding` of exactly `gzip`, and the module then leaves out that header and its `content-length`. A body in any other coding keeps its bytes and those headers. ## In tests `RestTestServer` of `test/core/rest/rest_test_server.dart`, which the role generates, is a local server for the tests of the app; see [REST API](https://doc.saymyframe.com/guides/rest.md#in-tests). `dio` has no platform side, so a test needs no mocks. The module keeps a test for what only it does, on the real package: that an exchange reaches `Dio` as it is, that a reply keeps its status and headers, how each error of `Dio` becomes a failure of the role, and what a stop leaves behind on a socket. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it `smf create` asks which module provides the REST API, and the answer may be none. To choose it without the question: ```bash smf create my_app -m dio ``` # `revenuecat` Source: https://doc.saymyframe.com/modules/revenuecat | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_revenuecat`](https://pub.dev/packages/smf_revenuecat) | infrastructure | Purchases | values in `.env`, such as [`dart_define`](https://doc.saymyframe.com/modules/dart-define.md) | `-m revenuecat` | `revenuecat` sells the premium access of the app with [RevenueCat](https://www.revenuecat.com), through the [purchases_flutter](https://pub.dev/packages/purchases_flutter) package. The user buys a plan of the default offering of a RevenueCat project, such as a monthly or a yearly subscription or a payment once, and restores it on another device. The app knows whether the user has premium access before its first frame. The code of the app never uses the package. It uses `appPurchases`, which the purchases role generates; see [Purchases](https://doc.saymyframe.com/guides/purchases.md). To show the plans to the user, add [`paywall`](https://doc.saymyframe.com/modules/paywall.md), which brings this module with it. ## What it adds to the app | In the app | What it is | | --- | --- | | `purchases_flutter: ^10.18.0` in the dependencies | The SDK of RevenueCat. | | `lib/core/purchases/revenuecat_purchases_service.dart` | `RevenueCatPurchasesService`, the purchases service of the app on `Purchases`; `createRevenueCatPurchasesService()`, which creates it; and `revenueCatKey()`, which chooses the API key for the platform and the build. | | Three keys in `.env` | `REVENUECAT_APPLE_KEY`, `REVENUECAT_GOOGLE_KEY` and `REVENUECAT_TEST_KEY`, the public API keys of RevenueCat, through the role of the values in `.env`. | | The section "RevenueCat" of the README | The way to a first purchase in the Test Store of RevenueCat, what a release needs, which key a build takes, and what the app does without a key. | Whichever module provides it, the purchases role adds these files: | File | What it holds | | --- | --- | | `lib/core/purchases/app_purchases.dart` | `appPurchases`, through which the code of the app reads the access of the user, gets the plans, buys and restores, and `initPurchases()`. It exports the types of the answers, so the code of the app imports this file alone. | | `lib/core/purchases/purchases_service.dart` | `PurchasesService`, the interface that this module implements, with `AppAccess`, `Plan`, `IntroOffer`, `BillingPeriod` and `PurchasesFailure`. | | `lib/core/purchases/restore_purchases_setting.dart`, in an app with a [settings screen](https://doc.saymyframe.com/modules/settings.md) | `RestorePurchasesSetting`, the row of the settings screen that restores purchases and tells what it found. | `bootstrap()` awaits `initPurchases()` in its platform phase, which creates the service and starts `appPurchases` with it. This is `bootstrap()` of an app with this module and `dart_define`, which comes with it: ```dart title="lib/bootstrap.dart" Future bootstrap() async { await initPurchases(); } ``` In an app with sign-in, `initAuth()` comes first, so the purchases belong to the user who is signed in; see [Purchases](https://doc.saymyframe.com/guides/purchases.md#whose-purchases-they-are). The module needs nothing in the native projects. The Billing Library of Google Play declares its permission itself, and the In-App Purchase capability of iOS has no entitlement. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the purchases role describes `appPurchases` under "Purchases". The module adds which file is on purchases_flutter, that the premium access is the entitlement `premium`, which key a build takes and why that rule stays, that nothing calls RevenueCat before it is configured, how a grant made on the RevenueCat dashboard reaches the app, and what a test answers in place of the platform side of the package. ## The premium access in RevenueCat The premium access of the app is the entitlement `premium` in RevenueCat. Every product of the current offering unlocks it, so attach each product to `premium`. A plan of the app is a package of the current offering, which the RevenueCat dashboard calls the default offering, and the id of a `Plan` is the identifier of its package. The app shows the plans in the order of the offering. | In RevenueCat | In the app | | --- | --- | | The entitlement `premium`, active | `PremiumAccess`, with `expiresAt` from its expiration date (`null` for a payment once), `renews`, `inTrial` and the `manageUrl` of the customer | | No active `premium` | `NoAccess` | | A package of the current offering | A `Plan`, with the price, the period and the intro offer of its product in the store | | No current offering, or one without packages | `plans()` fails with `notConfigured`, and its hint tells what to make in RevenueCat | The steps by hand of the module set this up; see [Finish the setup](#finish-the-setup). ## The API keys RevenueCat has a public API key for each app of a project: the App Store app, the Play Store app, and the Test Store, a store of RevenueCat itself in which you buy without an account at Apple or Google. They go into `.env`: ```bash title=".env" REVENUECAT_APPLE_KEY=appl_... REVENUECAT_GOOGLE_KEY=goog_... REVENUECAT_TEST_KEY=test_... ``` `revenueCatKey()` chooses the key that a build configures RevenueCat with: | Build | Key | | --- | --- | | A debug build, with `REVENUECAT_TEST_KEY` filled in | `REVENUECAT_TEST_KEY`, the Test Store | | A debug build without it, and every profile or release build | `REVENUECAT_APPLE_KEY` on iOS, `REVENUECAT_GOOGLE_KEY` on Android | A profile or release build never takes the key of the Test Store: RevenueCat stops such a build on purpose. So to try the sandbox of a store in a debug build, leave `REVENUECAT_TEST_KEY` empty. The keys are public. Each is compiled into the app, where anyone can read it, as with every value of `.env`. A secret API key of RevenueCat, which starts with `sk_`, never goes into the app, and `revenueCatKey()` refuses one. While the key that a build takes has no value, the app runs without purchases. It never calls RevenueCat, `appPurchases.value` stays `NoAccess`, every call fails with the reason `notConfigured`, and a debug build prints which key to fill in. The same goes for a secret key, a Test Store key in a profile or release build, and a platform other than Android and iOS. ## What the service adds to the package The purchases role promises more than purchases_flutter does in a few places, and the service makes up the difference: | What the service does | Why | | --- | --- | | It configures RevenueCat when it is created, and calls nothing else of RevenueCat before that has completed. Without a key, it calls nothing at all. | iOS stops an app that calls RevenueCat before it is configured. | | A configuration that fails, also for want of the platform side of the plugin (`MissingPluginException`), leaves the service not configured, and every call fails with `notConfigured` and a hint. | The app starts and runs without purchases rather than crash. | | `identify` logs a user of the app in with `logIn`, and logs out for the user of the device. A log out of an anonymous user, which RevenueCat fails with the code 22, counts as done. | The role says whose the purchases are, and the user of the device is the anonymous user of RevenueCat. | | It reads the code of an error with `int.tryParse`. | An error of the plugin itself has a code that is no number, as on Android before the first configuration. | | A purchase that RevenueCat gives no active entitlement `premium` for fails with `notConfigured`, with a hint that names the product. | Every plan gives premium access, so such a product is not attached to `premium` yet. A restore gives the access once it is. | | On iOS, a plan has its intro offer only when iOS says that the user may take it. | A user who had a trial of the group gets no second one, and the paywall would promise one. | | On Android, a plan has the title of its product without the name of the app. | Google Play appends the name of the app to the title. | | The access of a plan that renews takes its period from the offerings, which it waits for at most a second. | The customer info of RevenueCat has no period. The offerings come at once from what the device keeps, so the wait only ends a read that would wait for the network: the access then has no period, and a later access has it. | Each error of RevenueCat becomes a reason of the role: | Reason | Codes of RevenueCat | | --- | --- | | `pending` | `paymentPendingError` | | `network` | `networkError`, `offlineConnectionError`, `productRequestTimeout`, `apiEndpointBlocked` | | `alreadyOwned` | `productAlreadyPurchasedError`, `receiptAlreadyInUseError`, `receiptInUseByOtherSubscriberError`, `purchaseBelongsToOtherUser` | | `notAllowed` | `purchaseNotAllowedError` | | `unavailable` | `productNotAvailableForPurchaseError`, `purchaseInvalidError`, `ineligibleError` | | `notConfigured` | `configurationError`, `invalidCredentialsError`, `invalidAppleSubscriptionKeyError`, `insufficientPermissionsError` | | `storeProblem` | `storeProblemError`, `invalidReceiptError`, `missingReceiptFileError`, `unexpectedBackendResponseError`, `unknownBackendError`, `customerInfoError`, `systemInfoError`, `signatureVerificationFailed`, `testStoreSimulatedPurchaseError` | | `unknown` | Any other code, and an error that is not of RevenueCat | A cancel is no failure: `appPurchases.purchase()` completes with `false`. The `developerHint` of a failure has the code and the message of RevenueCat. For an API key that RevenueCat refuses, it names the key of `.env` to fix. RevenueCat answers from a cache of the customer info. An entitlement that you grant on the RevenueCat dashboard, or with its API, reaches the app once the cache is emptied with `Purchases.invalidateCustomerInfoCache()` and the customer info is read again, or once the SDK refreshes it itself. `appPurchases` asks for the access again each time the user comes back to the app. ## Finish the setup Right after `smf create` the keys are empty, so the app runs without purchases. To buy a plan in a debug build with nothing but a RevenueCat account: 1. Create a project in RevenueCat. A new project has a Test Store with products. 2. Create the entitlement `premium` and attach the products to it. 3. Add the packages of those products to an offering, and make it the default one. 4. Copy the public API key of the Test Store, which starts with `test_`, into `REVENUECAT_TEST_KEY` in `.env`. 5. Run the app with `flutter run --dart-define-from-file=.env` and buy a plan. The Test Store shows a dialog of its own, where "Test valid purchase" completes the purchase. For a release, the app sells in the App Store and in Google Play, and RevenueCat checks each purchase with the store. That takes the steps by hand of the app, which the README lists in its section "Finish the setup". The table links to the click-by-click guide of each: | Step | What you do | | --- | --- | | [`purchases.store_agreements`](https://doc.saymyframe.com/setup/purchases-store-agreements.md) | Sign the agreement for paid apps in App Store Connect, and set up a payments profile in Google Play Console. | | [`purchases.store_products`](https://doc.saymyframe.com/setup/purchases-store-products.md) | Create the products of the plans in both stores. | | [`revenuecat.entitlement_and_offering`](https://doc.saymyframe.com/setup/revenuecat-entitlement-and-offering.md) | Create the entitlement `premium` and the default offering with a package for each plan. On Google Play a lifetime plan is a one-time product: give it the type Non-consumable in RevenueCat, or RevenueCat consumes the purchase and the user can buy the plan again. | | [`revenuecat.api_keys`](https://doc.saymyframe.com/setup/revenuecat-api-keys.md) | Add the App Store app and the Play Store app to the project, and copy the public API keys of the three apps into `.env`. | | [`revenuecat.app_store_key`](https://doc.saymyframe.com/setup/revenuecat-app-store-key.md) | Give RevenueCat the In-App Purchase key of App Store Connect, with which it checks the purchases on iOS. | | [`revenuecat.play_service_account`](https://doc.saymyframe.com/setup/revenuecat-play-service-account.md) | Give RevenueCat a service account with access to Google Play, with which it checks the purchases on Android. | The first two are steps of the purchases role, which every provider that sells in the stores needs. An app with [`paywall`](https://doc.saymyframe.com/modules/paywall.md) has one more, for the pages of its terms of use and its privacy policy. ## What the module does not do - It sells the packages of the default offering alone, and the one entitlement `premium`. Other offerings and other entitlements of the project do not reach the app. - It adds no paywall of RevenueCat (`purchases_ui_flutter`). The screens that sell come from [`paywall`](https://doc.saymyframe.com/modules/paywall.md) or from your own code, through `appPurchases`. - It sells on Android and iOS only. - It restores nothing on its own. The app restores where the user asks for it, such as on the paywall or in the row of the settings screen. - It grants nothing from a server. A grant made on the dashboard reaches the app as described above. ## In tests purchases_flutter has no platform side for tests and no platform interface: `Purchases` is a class of static methods over the method channel `purchases_flutter`. A test that runs `main()` or `bootstrap()` answers that channel itself, with `setMockMethodCallHandler` of `TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger`. The listeners and the last customer info of `Purchases` are static, so they last for a whole test file. The guide for coding agents of the app says the same. A test of a screen needs none of this: it gives `appPurchases.start()` a service of its own; see [Purchases](https://doc.saymyframe.com/guides/purchases.md#in-tests). Whichever module provides the purchases, a fresh user who buys a plan has premium access, the access stays at the next start of the app, and the purchases of each user stay apart. SMF's CI checks this in running apps with the role, over a stand-in for RevenueCat, its backend and the store account of a device, which starts as on a first launch. For this module, it checks the key that each build takes and that the app reads the keys from `.env`; that without a key, or without the platform side of the plugin, the service calls nothing and fails every call with a hint; what each call sends to RevenueCat; the reason of each code of RevenueCat; and the plans and the access on Android and on iOS, from a purchase, from the customer info and from the next launch. On a device, it checks that RevenueCat is configured exactly when the app has a key, and that the access and the plans of the app are those that RevenueCat gives. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## Choosing it To choose it without the question of `smf create`: ```bash smf create my_app -m revenuecat ``` The module requires the values of `.env`, and `smf create` adds the only module that provides them: ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding dart_define: the only provider of the env role, which revenuecat requires. ``` [`paywall`](https://doc.saymyframe.com/modules/paywall.md) requires the purchases role, so with it `smf create` adds this module without a question while it is the only one that provides the purchases. # `github_actions` Source: https://doc.saymyframe.com/modules/github-actions | Package | Kind | Provides the role | Needs | Choose with | | --- | --- | --- | --- | --- | | [`smf_github_actions`](https://pub.dev/packages/smf_github_actions) | infrastructure | CI | nothing | `-m github_actions` | `github_actions` writes what the CI role says into a workflow of [GitHub Actions](https://docs.github.com/actions), which runs once you push the app to GitHub. What runs, and how the values of each environment reach a build, is in [CI](https://doc.saymyframe.com/guides/ci.md). ## What it adds to the app | In the app | What it is | | --- | --- | | `.github/workflows/ci.yml` | The workflow, with the jobs `checks` and `build` | | The section "GitHub Actions" of the README | How to start a build, where the values of each environment go and how to stay on one version of Flutter | Whichever module provides it, the role adds the section "Continuous integration" of the README, and in an app with [the values in `.env`](https://doc.saymyframe.com/guides/env.md) the script `tool/write_env.dart`. In the [guide for coding agents](https://doc.saymyframe.com/guides/coding-agents.md) of the app, the role says that CI runs the commands of its section, so an agent keeps them passing. The module adds where the jobs are and how a new key reaches a build. The module adds no package and has no step after generation or by hand. The checks pass on the first push without any setup. ## The workflow | Job | Runs on | Does | | --- | --- | --- | | `checks` | each push to a branch | Sets up Flutter and runs the checks of the role, within 20 minutes | | `build` | `workflow_dispatch`, from the Actions tab or `gh workflow run` | In the GitHub environment that you pick: sets up Java and Flutter, writes `.env` from the variables of that environment, builds the release APK and keeps it as an artifact, within 45 minutes. The upload fails when the file is missing. | Both run on `ubuntu-latest`, and the workflow reads the repository and nothing else (`contents: read`). A new push cancels the run of an older push of its branch, and each environment has a group of its own for its builds. Each key of the app is a line of the step that writes `.env`, such as `REST_BASE_URL: ${{ vars.REST_BASE_URL }}`. No `run:` line has an expression, so a value never becomes a part of the text of a script. Keep it that way in what you add: pass a value through `env:` of the step, and read it as a variable of the shell. Each action is pinned to a full commit, with its tag in a comment, and the app gets no `dependabot.yml`, so what SMF puts into your repository does not change under you. Nothing updates the pins. Change the commit and the tag together to update an action. ## Choosing it `smf create` asks which module provides CI, and the answer may be none. To choose it without the question: ```bash smf create my_app -m github_actions ``` # The module model Source: https://doc.saymyframe.com/concepts/module-model SMF builds an app from modules. To get something done, like routing or dependency injection, a module names a role ("a router", "a DI container"), and whichever module the user picked provides that role. It names another module only when it builds on it, as the Firebase modules build on `firebase_core`, or when it has a variant for one provider of a role. The sections below describe the pieces, and [module independence](https://doc.saymyframe.com/concepts/independence.md) explains why the split matters. ```mermaid flowchart LR home["home
feature"] -- requires --> router(["Router role"]) tabs["bottom_tabs
layout"] -- provides --> layout(["Layout role"]) layout -- requires --> router gorouter["go_router"] -- provides --> router analytics["firebase_analytics"] -- provides --> analyticsRole(["Analytics role"]) analyticsRole -. uses .-> router analytics -- depends on --> core["firebase_core"] ``` Rectangles are modules, and rounded boxes are roles. `home` and `bottom_tabs` need a router, and `go_router` provides it. The analytics role works with a router when the app has one. `firebase_analytics` depends on `firebase_core` directly, because it builds on Firebase itself rather than on a role. ## Modules A module is a Dart class that extends `SmfModule`. It describes itself with a descriptor and returns its contributions to an app, such as files, code for sockets, data for roles and dependencies: ```dart final class HomeModule extends SmfModule { const HomeModule(); static const id = ModuleId('home'); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Start screen with a welcome and the next steps', kind: ModuleKinds.feature, ); @override List contribute(ModuleContext context) => [ BrickContribution(homeBundle), routerRole.data(const RoutesData([/* the route of the screen */])), ]; } ``` `contribute` gets a `ModuleContext` with the name of the app, its organization, its platforms and its platform identifiers. It says nothing about the other modules of the app. Code that depends on other roles goes into contributions that apply only when those roles are present. The descriptor says: | Field | What it means | | --- | --- | | `id` | The id of the module, lower snake_case, as in `-m home`. | | `description` | What the module adds, as the questions of `smf create` show it. | | `kind` | The kind of the module, which decides the rules it follows. | | `providers` | The roles the module provides, one provider object per role. | | `requires` | Roles the module needs. The app gets a provider of each. | | `uses` | Roles the module works with when they are present, and works without. | | `dependsOn` | Modules the module builds on directly, such as `firebase_core` for the Firebase modules. | | `variants` | Alternative contributions for the providers of one role, such as a feature with a BLoC and a Riverpod variant. | | `sockets`, `socketFamilies` | Sockets of the module itself, for the modules that depend on it. | ## Kinds The kind of a module states, as data, the rules its modules follow. The pipeline applies them without knowing any kind. | Kind | Modules | Rules | | --- | --- | --- | | scaffold | `flutter_core` | Provides the app entry role: `main()`, start-up, native projects, `pubspec.yaml`. | | infrastructure | `go_router`, `get_it`, `bloc`, `riverpod`, `material_theme`, `gen_l10n`, `event_bus`, `shared_preferences`, the Firebase modules | Sets up a service or a library. Declares no routes, generates nothing in `lib/features/`, has no variants, and never resolves services itself: it gets them through the factories of its DI registrations. | | feature | `home`, `onboarding`, `settings`, `sign_in` | A module with screens. Requires the router role, declares at least one route, and keeps its files in `lib/features//`. Its optional composition file, `lib/features//_composition.dart`, may resolve services; a feature that does requires the DI role. | | layout | `bottom_tabs` | Provides the layout role, the main navigation. Keeps its files in `lib/core/layout/` and declares no routes. | A kind can also list rules of roles, which only their roles check. The composition file of a feature is a rule of the DI role, which lets a module resolve services only in the composition file that its kind lists. A kind that another package defines can list one of its own. A scaffold provides the app entry role, and a layout the layout role. Beyond that, the kind of a module does not decide which roles it provides: `settings` is a feature, with a route and a screen like any other, and it provides the settings screen role. In the questions of `smf create`, the modules that provide no role are grouped by kind: Features, Infrastructure. ## Roles A role is a replaceable part of an app, described by what it offers to the rest of the app. It has: | Part | Meaning | | --- | --- | | cardinality | Exactly one provider in every app, at most one, or any number. | | requires, uses | Other roles, whose data and presence its hooks can see. | | sockets | Named places in its files where other modules put code. | | interface | The files its own template generates, and the symbols every provider must generate, such as `createAppRouter()` for the router. | | data type | The type in which modules describe what they need from it, such as the routes of a feature. | | options | Options of the command line, such as `--start` of the router. An option whose every value makes another app, such as `--auth-mode` of the auth role, is a mode option: its first value is the default, and every value gets apps in the tests. | | template, rules | Hooks that run during generation, and checks of the modules and of the generated code. | A role is defined once, as a constant, in `smf_contracts` or in any other package. These are the built-in roles: | Role | Id | Providers in an app | Requires | Uses | Data from modules | | --- | --- | --- | --- | --- | --- | | App entry | `app_entry` | exactly one | | Router | none | | Router | `router` | at most one | | Layout | `RoutesData`: routes, [guards](https://doc.saymyframe.com/concepts/guards.md) and the [conditions](https://doc.saymyframe.com/concepts/conditions.md) that routes ask for | | Layout | `layout` | at most one | Router | Localization | none | | Settings screen | `settings_screen` | at most one | Router | | `SettingsData`: the entries of the screen, and its route | | Onboarding screen | `onboarding_screen` | at most one | Router | Localization | `OnboardingData`: the [steps](https://doc.saymyframe.com/extending/onboarding-steps.md) of the onboarding, and its route | | Localization | `localization` | at most one | Preferences | Settings screen | `TextsData`: [texts](https://doc.saymyframe.com/concepts/localization.md) | | State management | `state_management` | at most one | | | none | | Dependency injection | `di` | at most one | | | `DiRegistration`: services | | Events | `events` | at most one | | Dependency injection | `RoleImplementation` | | Preferences | `preferences` | at most one | | Dependency injection | `RoleImplementation` | | Theme | `theme` | at most one | Preferences | Settings screen, Localization | none | | Analytics | `analytics` | any number | | Dependency injection, Router | `RoleImplementation` | | Crash reporting | `crash_reporting` | any number | | Dependency injection | `RoleImplementation` | | Authentication | `auth` | at most one | | Router, Localization | `AuthData`: the `AuthImplementation` of the provider, and the `SignInMethod`s of the [ways to sign in](https://doc.saymyframe.com/guides/sign-in.md#ways-to-sign-in) | | Notifications | `notifications` | at most one | Preferences | Settings screen, Onboarding screen, Localization | `RoleImplementation` | | Push messages | `push` | at most one | Notifications | | `RoleImplementation` | | REST API | `rest` | at most one | Values in .env | Authentication | `RoleImplementation` | | CI | `ci` | at most one | | Values in .env | none | | App icon | `app_icon` | at most one | | | none | | Splash screen | `splash` | at most one | | | none | The app entry is open to every module, so any module may add start-up code or native settings without declaring the role. It uses the router role, so that its provider may contribute the fallback start screen only to an app that no route starts. Its provider builds the root of the app, inside the wrappers that modules add, as a `MaterialApp`, or as a `MaterialApp.router` when the app has a router. So the screens of every module have the Material ancestors they rely on, such as the theme and `MaterialLocalizations`. ### Role templates Much of a role's code does not depend on its provider, so the role generates it itself, through its template. The router role generates the navigation facade from the routes of all features, the DI role generates the `ServiceLocator` interface, and the analytics role generates the `AnalyticsService` interface with a service that forwards every call to all providers. The auth role generates `appSession`, the session of an app with sign-in. The notifications role generates `appNotifications`, with an entry of the settings screen and a step of the onboarding that ask for the permission, and the push role generates `appPush`. The app entry role generates the guide for coding agents of the app. The pipeline treats the template like a module named `role:`, which owns the files it generates. A template contributes like a module. It can put code into the sockets of the roles that its role requires or uses, and give those roles data. The template of the theme role keeps the theme mode that the user selects: it gives the preferences role a function that restores the mode, the settings screen role a row that selects it, and the localization role the texts of that row. So the mode works the same with every module that provides the theme. [How settings work](https://doc.saymyframe.com/concepts/settings.md) follows a setting through these roles. ### Providers A module provides a role with a provider object in its descriptor. A provider may check the role's data against what it supports, as `bottom_tabs` does with its limit of five destinations. It may also render the data into its own files: `go_router` renders the routes into a `GoRouter`, and `get_it` renders the registrations into get_it calls. A module whose files and dependencies alone implement the role, such as `bloc`, uses `RoleProvider.plain`. A provider requires and uses what its role requires and uses, so `bottom_tabs` requires a router because the layout role does. ## How modules relate | Relation | Direction | What it gives | | --- | --- | --- | | provides | module β†’ role | The module implements the role. | | requires | module β†’ role | The app gets a provider of the role, and the module may use its sockets and symbols. | | uses | module β†’ role | The module works with the role when it is present. Its code that refers to the role's symbols goes into contributions that name the role in `when`. In its templates, that code is inside `{{#has_}}` or in a variable whose code depends on the role. Its data for the role and its code for the role's sockets apply only when the role is present anyway. | | depends on | module β†’ module | The module builds on another module directly, and that module comes into the app with it. It may put code into that module's sockets. The id comes from the other module's package, so the dependency is a pub dependency too. | | variants | module β†’ providers of one role | The module has different contributions for each provider, keyed by the provider's id. It requires the role. | Every relation points one way. `firebase_analytics` depends on `firebase_core`, but `firebase_core` knows nothing about it. Whenever a role describes what a module needs, the module requires the role rather than depending on the module that provides it. Two modules can also meet through something that a role publishes. A role can publish a [condition for routes](https://doc.saymyframe.com/concepts/conditions.md), such as an account. A feature asks for it on a route, another module stands for it with a guard, as `sign_in` does, and each knows only the role. ## Variants A module whose code depends on the provider of a role declares variants, one per provider, keyed by the provider's id. A feature with state has a variant for `bloc` and one for `riverpod`, as the built-in `sign_in` has, and the pipeline adds the contributions of the variant for the provider that the app has. A variant brings the package of its provider, such as `flutter_bloc`, with the constraint `any`, so the provider keeps control of the version. A variant only adds contributions and never changes the descriptor. When the app has a provider that the module has no variant for, the module cannot be part of the app. ## Next - [Sockets and contributions](https://doc.saymyframe.com/concepts/sockets.md) shows how modules put code into the app. - [The generation pipeline](https://doc.saymyframe.com/concepts/pipeline.md) shows how the pipeline turns modules into an app. # Sockets and contributions Source: https://doc.saymyframe.com/concepts/sockets A module does not edit files. It returns contributions, plain data that says what it adds, and the pipeline puts them together. Shared files, such as `bootstrap.dart`, have sockets: named places where modules put code without knowing who else does. ## Contributions | Contribution | What it adds | | --- | --- | | `BrickContribution` | Template files, as a [mason](https://pub.dev/packages/mason) bundle, with the variables that the templates read. Every generated file has exactly one owner. | | `SocketContribution` | Code or a value for a socket. | | `RoleData` | Data for a role in the role's own language, such as the routes of a feature for the router. | | `PubspecContribution` | A dependency, an SDK constraint, or a setting of the `flutter:` section of `pubspec.yaml`. | | `CodegenRequest` | A request to run `build_runner` in the new app. | | `Preflight` | Checks of the machine before generation, which can offer to set up what is missing. | | `PostGenStep` | A command to run in the new app, such as `dart tool/configure_firebase.dart dev`. | | `ManualStep` | A step of the setup that only the developer of the app can do, such as uploading a key to the Firebase console. The run ends with a link to its guide; see [steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#steps-by-hand). | Every contribution can have a `when`, a set of roles that must all be present for the contribution to apply. A module lists there the roles it only uses, so code that refers to them is generated only in apps that have them. `firebase_analytics` gives the router its listener of the screen with `when: {routerRole}`. A brick and data of a role can also depend on what a role chose, with `whenChosen`: conditions that a role publishes as constants, such as `RouterRole.noStartRoute`, which holds in an app that no route starts. `flutter_core` contributes its fallback start screen, the test of the screen and its two texts under that condition, so an app that a route starts has none of them. A role chooses after the machine is checked, so such a condition decides only what the pipeline renders: - Validation and `--explain` take a contribution with conditions as one that applies, and report its problems in every app that may have it. - A role whose data depends on what another role chose makes its choice after that role, and gets only the data whose conditions hold. - Once every role has chosen, the contributions whose conditions do not hold leave the app. The render hooks, the templates and the checks of the rendered app do not see them. Only bricks and data of a role take such conditions, because the pipeline needs the other kinds before any role chooses. A brick with conditions holds no tag of a socket, since an app without the brick would lose what the socket got. See [Choices](https://doc.saymyframe.com/extending/new-role.md#choices-and-options). ## Sockets A socket belongs to a role, to a module or to the pipeline. Its template marks it with a tag in three braces that joins `smf_`, the owner and the name of the socket, such as `{{{smf_app_entry__bootstrap_platform}}}`. The pipeline replaces the tag with the rendered contributions. Modules refer to sockets only through typed constants, such as `AppEntryRole.bootstrapPlatform`, so a misspelled socket does not compile. This is `lib/bootstrap.dart` as `flutter_core` writes it, with the tags of the start-up phases: ```dart {{{smf_app_entry__top_level}}} Future bootstrap() async { {{{smf_app_entry__bootstrap_early}}} {{{smf_app_entry__bootstrap_platform}}} {{{smf_app_entry__bootstrap_di}}} {{{smf_app_entry__bootstrap_late}}} } ``` ```mermaid flowchart LR fc["firebase_core"] -- "await Firebase.initializeApp(...)" --> platform crash(["Crash reporting role"]) -- "installCrashReporting()" --> platform di(["DI role"]) -- "await registerDependencies();" --> diPhase subgraph boot ["bootstrap() of flutter_core"] early["early"] platform["platform"] diPhase["DI"] late["late"] end ``` The kind of a socket decides what it takes and how its contributions are rendered: | Kind | Takes | Rendered as | Example | | --- | --- | --- | --- | | `CodeSocket` | Fragments of code, with the imports they need | One after another | The start-up phases | | `ArgsSocket` | Named arguments of a call | `name: value,` lines. A list argument unites the items of its contributors, or takes the items of one contributor only. Two values of a single argument conflict. | `theme` and `supportedLocales` of `MaterialApp` | | `WrapperSocket` | A widget around a piece of code, as an opening and a closing part | The first contribution outermost | `ProviderScope(child: …)` around the root widget | | `FactoryListSocket` | Functions that the socket's owner calls | List items | Navigator observers and listeners of the screen of the router, restorers of the preferences | | `KeyedSocket` | Entries with a key | Merged by key with a policy | Android permissions, `Info.plist` keys, Gradle plugins, README sections, sections of the guide for coding agents | | `ValueSocket` | One value, rendered at one tag, or at several places with a tag each (`ValueSocket.places`) | Merged with a policy | The minimum iOS version, the highest any module needs, and the version of core library desugaring, which renders a line in two places of the Gradle file | A fragment of code never imports anything itself. It lists its imports, such as `ImportRef('package:firebase_core/firebase_core.dart')`, and the pipeline adds them to the file that holds the socket's tag, merged and sorted. `ImportRef.app('firebase_options_of_flavor.dart')` imports a file of the app without knowing the app's package name. ### The sockets of the app entry The app entry role is open to every module, so any module can use these sockets: | Socket | Where | What goes in | | --- | --- | --- | | `bootstrapEarly`, `bootstrapPlatform`, `bootstrapDi`, `bootstrapLate` | `bootstrap()` | Start-up code, by phase | | `topLevel` | `lib/bootstrap.dart` | Top-level declarations, such as a handler of background messages | | `rootWrappers` | `main()` | Widgets around the root widget | | `appArgs` | the root `MaterialApp` | `theme`, `darkTheme`, `themeMode` and `locale`, which take one value, `localizationsDelegates`, which takes the list items of every contributor, and `supportedLocales`, which takes the list items of one contributor | | `appBuilder` | the `builder` of the root `MaterialApp` | Widgets around the content of every route | | `iosDeploymentTarget` | `project.pbxproj` | The minimum iOS version, where the highest wins | | `androidManifestPermissions` | `AndroidManifest.xml` | `` by name | | `androidManifestApplicationMeta` | `AndroidManifest.xml` | `` of the application | | `androidManifestApplicationComponents` | `AndroidManifest.xml` | ``, `` and `` elements inside ``, after its meta-data, as XML | | `mainActivityIntentFilters` | `AndroidManifest.xml` | ``s of the main activity, such as deep links | | `infoPlist` | `Info.plist` | Keys with a string, a boolean, an integer or an array of strings, where arrays are united | | `iosEntitlements` | `ios/Runner/Runner.entitlements` | Entitlements by key, such as `aps-environment`, merged as the keys of `Info.plist` | | `iosAppDelegateLaunch` | `AppDelegate.swift` | Swift statements that run in `application(_:didFinishLaunchingWithOptions:)`, before the call of `super.application` that hands the launch to Flutter | | `gradleSettingsPlugins`, `gradleAppPlugins`, `gradleAppDependencies` | Gradle files | Plugins with their versions, the plugins the app applies, and dependencies, where the highest version wins | | `androidCoreLibraryDesugaring` | the Gradle file of the app | The version of `desugar_jdk_libs`, where the highest wins. It turns core library desugaring on in `compileOptions` and adds the library to `dependencies`, since the build fails with either line alone. | | `readmeSections` | `README.md` | Sections by heading, such as the setup of Firebase | | `agentSections` | `AGENTS.md` | Sections of the guide for coding agents by heading, each with a note | The provider of the app entry creates the root `MaterialApp` in the `build` of a widget, below the root wrappers, and evaluates the arguments of `appArgs` there. So the expression of an argument may read `context`: it can take its value from an inherited widget that a module put among the `rootWrappers`, and the root rebuilds when that widget notifies. The theme role gives the root its `themeMode` this way, and the localization role its `locale`. That context is above the `MaterialApp`, so it has neither the theme nor the localizations of the app. The wrappers of `appBuilder` are below the `MaterialApp`, so a widget among them finds the theme and the localizations of the app above it. The app entry role puts one there itself, in every app: `StatusBarIcons` of `lib/core/app/status_bar_icons.dart`, which tells the system which icons of the status bar suit the theme. A few native sockets ask more of what goes in: - A contribution to `androidManifestApplicationComponents` indents its elements by eight spaces, and one to `iosAppDelegateLaunch` its lines by four, as the bodies around their tags are. - The manifest declares a component of each kind once, `` included, under one `android:name`. The contract harness checks the names as Android reads them, so a name that starts with a dot, or has none, is relative to the `namespace` of the Gradle file of the app. Android fails to build an app with two declarations of a component that differ, and keeps both of two equal ones. - The statements of `iosAppDelegateLaunch` run before Flutter registers the plugins of the app, which the scene of the app does once it connects. So they have no registry of plugins and no channel. `local_notifications` sets the delegate of the notification center there. The router role adds `observers` and `screenListeners`, and two families of sockets for the annotations of screens and of their parameters, which a router that needs annotations fills. The preferences role adds `restorers`, for the functions that restore what the modules keep in the preferences when the app starts. ## Who may contribute where - A socket of a role takes contributions from the modules that provide, require or use the role, and from the templates of the role and of the roles that require or use it. The sockets of the app entry are open to every module. - A socket of a module takes contributions from the modules that depend on it directly. - The sockets of the pipeline, which are the sections of `pubspec.yaml`, take no contributions. Modules contribute `PubspecContribution`s instead, and the pipeline merges them. A module may contribute data only to its own roles, and only a role's providers contribute its implementations. The pipeline checks all of it before it renders anything. ## Order When several modules put code into one socket, or several steps run after generation, they come in an order that the pipeline derives from the modules alone: 1. A module comes after the modules it depends on. 2. A module that requires a role, or names it in `when`, comes after the role's providers and its template. 3. A role's template comes after the role's providers, and after the providers and templates of the roles that its role requires or that its contributions name in `when`. A contributor comes after every contributor it reaches through these edges, even through modules that add nothing to the socket. Otherwise contributors are ordered by id. A cycle is an error. `smf create --explain` prints the order of every socket with more than one contributor, and the edges that decide it. A step that continues another step runs right after that step instead of in its own place; see [Continuing a step](https://doc.saymyframe.com/extending/infrastructure-module.md#continuing-a-step). That is why `installCrashReporting()` of the crash reporting role runs after `Firebase.initializeApp` of `firebase_core`: the role's template comes after its provider, `firebase_crashlytics`, which depends on `firebase_core`. A keyed socket can put its entries in an order of its own instead. The sections of the guide for coding agents do: the section of the app entry comes first, and the others follow in the order of their headings. The pipeline takes the notes of such a socket by the ids of their contributors alone, so a `when` of a note adds no edge, and no note can make an app impossible to generate. `--explain` does not list such a socket, which has no order of contributors to explain. ## Merging Keyed and value sockets merge the contributions of several modules with a policy of the socket: | Policy | How values merge | Used for | | --- | --- | --- | | conflict | Equal values agree, and different values are an error that names both modules. | Android permissions, README sections | | max | The highest version wins. | The minimum iOS version, Gradle plugins, core library desugaring | | `Info.plist` | Arrays of strings are united, and every other value must agree. | `Info.plist` keys, entitlements | | notes | The notes under one heading are united, each once: those of roles first, then those of modules. | Sections of the guide for coding agents | The pipeline merges `pubspec.yaml` itself. It intersects the constraints of a package that several modules add, and an empty intersection is an error. A package that is both a dependency and a dev dependency becomes a dependency. # Module independence Source: https://doc.saymyframe.com/concepts/independence SMF rests on one principle: modules do not know each other. Roles, sockets, variants and the checks of the pipeline all exist to keep it that way. ## What a module knows A module knows three things: - the modules in its `dependsOn`, in one direction only, so `firebase_analytics` depends on `firebase_core` and `firebase_core` knows nothing about it; - the roles it provides, requires or uses, through their sockets, their symbols and their data; - the app it is part of, meaning its name, its organization, its platforms and its identifiers. It never learns which modules the user picked. It never refers to what another module generates, such as a class, a file or a package, unless it depends on that module. ## What that looks like `firebase_analytics` logs a screen view whenever the screen changes, without knowing go_router. It uses the router role and gives the role a listener of the screen, only when the app has a router: ```dart const SocketContribution.item( RouterRole.screenListeners, Fragment( 'logFirebaseScreenView', imports: [ ImportRef.app( 'core/analytics/firebase_analytics_service.dart', show: ['logFirebaseScreenView'], ), ], ), when: {routerRole}, ), ``` In the module's template, the listener exists only inside `{{#has_router}}`, the presence flag of the router role. An app without a router gets neither the contribution nor the listener. A feature does not know get_it either. Its composition file calls `resolve()` of the DI role and hands the services to the feature's state, and `get_it`, or any other provider of the role, makes that call work. The feature's screens know even less. They talk only to their state, a Cubit through `context.read` or a provider through `ref`, and never to the container. ```mermaid flowchart TB screen["Screen widget"] -- "context.read or ref" --> state["Cubit or provider"] composition["Composition file of the feature"] -- "services" --> state composition -- "resolve<T>()" --> locator(["DI role: ServiceLocator"]) getit["get_it"] -. provides .-> locator screen -. "never" .-x getit ``` A setting works the same way. The module that owns a setting gives the settings screen role the widget of its row, and whichever module provides the screen shows it. Neither names the other, so the screen has the rows of exactly the modules that the app has. The setting is saved through the preferences role, and its label is translated through the localization role. The module names neither of the modules that provide them; see [How settings work](https://doc.saymyframe.com/concepts/settings.md). A screen that needs an account works the same way. Its feature asks for the condition `AuthRole.account` on the route, and whichever module has the screens of sign-in declares the guard that stands for it, among the built-in modules `sign_in`. The two know the auth role and not each other; see [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md). `sign_in` itself knows neither the module that keeps the accounts nor the router. It signs in through `appSession` of the auth role, and its screens neither close themselves nor navigate after a sign-in: two guards read the session, and the router shows the sign-in and leaves it. ## What the model enforces SMF checks these rules in code. `smf create` checks the contributions of the modules before it generates an app, and the contract harness runs the same checks in the tests of every module, together with checks of the generated code. | Rule | Checked by | | --- | --- | | A module puts code only into the sockets of its own roles, of the app entry and of the modules it depends on, and contributes data only to its own roles. The `when` of a contribution names only roles of the module. | `smf create` and the harness | | A feature keeps its files in `lib/features//`, and infrastructure declares no routes and has no variants. | `smf create` and the harness | | The package of a role's provider, such as `flutter_riverpod` of `riverpod`, goes into another module only through its variant for the provider or through a dependency on the provider. | `smf create` and the harness | | Every file of the app has exactly one owner. | `smf create` and the harness | | Code that refers to the symbols of a role that the module only uses exists only in apps with the role: a contribution with that code names the role in `when`, and a template puts the code inside `{{#has_}}` or reads it from a variable whose code depends on the role. Data for the role and code for its sockets need neither, because they apply only when the role is present. | the harness, in its app without the role | | Only the composition file of a feature resolves services. Other code gets them as parameters of its factory function, and only the DI container calls the functions that create them. | the harness | | Code of a module navigates only to its own routes and to those of the modules it depends on. | the harness | | Code of a module reads only its own texts and those of the modules it depends on. | the harness | | A module gets the preferences through a function that it gives the preferences role, or from the DI container. Only the DI container calls `createAppPreferences()`, and only `bootstrap()` calls `initPreferences()`. | the harness | | Code of a module signs in only through `appSession` of the auth role. It does not call `createAuthService()`, and only `bootstrap()` calls `initAuth()`. | the harness | | The provider of a role renders what the modules give the role: every registration of a service, every entry of the settings screen and every text. So the tests of a module need not look into the files of a provider. | the harness | | Code imports only the files its module may use: its own, those of the modules it depends on directly, and those of its roles. What a render hook of a role gives may also import the files of the modules that give the role data, such as the screens that a router routes: a fragment of the hook, or a file that it generates. The template of a brick may not, since it is the same whatever the modules give the role. An import that the pipeline adds for a fragment counts for the module of the fragment. | the harness | | A module that imports or exports the package of a role's provider adds the package itself, even when it depends on the provider. | the harness | ## What it buys Any combination of modules works. You can add a module, leave one out or pick another provider of a role, and the app still compiles. Continuous integration generates apps from the modules in many combinations, each module with each provider of the roles it requires or uses and every module together, and runs `flutter analyze` on each of them. Providers are replaceable. A second router or DI container can join without a change to the features, because the features never named the first one. Modules can come from anyone. A module by another author follows the same rules and goes through the same checks. See [Extending SMF](https://doc.saymyframe.com/extending.md). # The generation pipeline Source: https://doc.saymyframe.com/concepts/pipeline `smf create` runs eleven stages. The first seven decide what the app will be, and nothing of it is written yet. The rest render it, finish it in a temporary directory and move it into place, so a run that fails or is cancelled halfway leaves no half-made app in your project. ```mermaid flowchart TD select["1 Β· Selection"] --> identity["2 Β· Identity"] identity --> resolve["3 Β· Resolution"] resolve --> collect["4 Β· Collection"] collect --> validate["5 Β· Validation"] validate --> preflight["6 Β· Preflight"] preflight -- "with --explain" --> report["Print the report and stop"] preflight --> choose["7 Β· Choices"] choose --> render["8 Β· Rendering in memory"] render --> postgen["9 Β· Post-generation in a temporary directory"] postgen --> move["10 Β· Moving into place"] move --> done["11 Β· Report and exit code"] validate -. "a module cannot work: leave it out" .-> resolve preflight -. "a module cannot work: leave it out" .-> resolve ``` ## The stages | # | Stage | What happens | | --- | --- | --- | | 1 | Selection | The app name, the directory, the organization and the modules come from the options or from questions. The pipeline also decides here what to do with an existing directory, before anything else happens. | | 2 | Identity | The pipeline derives the package name and the platform identifiers of the app from the name and the organization, and gives every app the platforms Android and iOS. | | 3 | Resolution | The pipeline adds the modules that the chosen ones depend on, and a provider for every role that the modules require and every role that every app has exactly one of, such as the app entry: the only provider, or the one you pick. Each module with variants gets its variant for the provider in the app. This repeats until nothing changes. | | 4 | Collection | The pipeline collects the contributions of every module, of its variant and of the template of every role in the app, and records who contributed each. | | 5 | Validation | The pipeline checks the contributions against the rules of the module model, the kinds, the checks of the roles and their providers, and the tags in the templates. It merges `pubspec.yaml`, orders the contributions of every socket, and renders them once to catch merge conflicts early. It also plans the [steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#steps-by-hand) of the app, each once and in order, and asks the front end for the link to their guide. | | 6 | Preflight | The pipeline checks the machine: the Flutter SDK for every app, then what the modules need, each module after the modules it depends on. It compares the versions of the SDK with the constraints of the app. In a terminal, SMF offers to set up what is missing. | | 7 | Choices | Roles decide what the modules leave open. They ask what only you can decide, such as the start screen when several routes can start the app, or who may use the app without an account. Or they take it from an option, as the localization role takes the languages of the app from `--locales`. A role whose data depends on what another role chose makes its choice after that role. Then the contributions with conditions on what the roles chose apply only where those hold, such as the fallback start screen, which only an app that no route starts gets. | | 8 | Rendering | The render hooks of the roles and their providers run. The pipeline fills the sockets, adds the imports, renders the templates in memory and takes the files that the hooks generate. | | 9 | Post-generation | In a temporary directory: `flutter pub get`, code generation once if a module asks for it, the steps of the modules, `dart fix` for the imports, the full `dart fix`, and `dart format`. A run in a terminal asks before a step that the app is complete without, and before a step with a notice. | | 10 | Moving | The app moves to its directory without the files where Flutter records the temporary path, and `flutter pub get` writes those again there. | | 11 | Exit | `smf` reports what the app is without and which steps are left for later, then how many steps by hand the app has, with the link to their guide, and exits with its [exit code](https://doc.saymyframe.com/guides/smf-create.md#exit-codes). | ## Lenient and strict In stages 3 to 6, a problem that one module causes, such as a feature whose tab does not fit into the tab bar, leaves that module out by default. The pipeline warns, removes the module and runs again from stage 3. A problem that no single module causes stops the run, and with `--strict` every problem stops it. A check can also find something about the app that keeps every module in it, such as routes of which none can start the app. That is a warning about what the app is made of, with a code of the role that reports it, such as `router.no_start`. By default the pipeline prints it and goes on. With `--strict` it stops: on a warning of stage 5 before the machine is checked, and on a warning of stage 7 before the app is rendered. A warning about the machine never stops it. See [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). The pipeline leaves a module out only if an app can still be made without it. Every role that each app has exactly one of, such as the app entry, must keep a provider that is not left out. That provider must not depend on a module that is left out, and must not require a role whose providers are all left out. So the problem of the only provider of the app entry, such as a Flutter SDK that is too old for it, stops the run too, before anything is installed. ## `--explain` `--explain` runs stages 1 to 5 and only the checks of stage 6, without installing anything. It prints the app, the modules and why each is there, the roles, the order of the contributions, the dependencies, the commands that would run after generation, the steps by hand, and the state of the machine. Then it stops. It makes no choices, so it takes every contribution with a condition on a choice as one that applies, and shows no warning of a choice. ## The temporary directory The pipeline renders the app in memory and writes it to a temporary directory, where the commands of stage 9 run. The app moves to its directory only when they are done. If a command fails, the app stays in the temporary directory, and the error names it. When you cancel the run, the pipeline deletes the temporary directory. Some files hold the path of the app on this machine, such as `ios/Flutter/Generated.xcconfig`, `.dart_tool/` and `build/`. The pipeline does not move them, and `flutter pub get` in the app's directory writes them again with the right path. For the same reason, a step of a module must not write the absolute path of its working directory into the app. ## The packages ```mermaid flowchart LR cli["smf_flutter_cli
the smf command"] --> pipeline["smf_pipeline
the stages and the contract harness"] cli --> modules["module packages"] pipeline --> contracts["smf_contracts
the module model"] modules --> contracts modules -. "in tests" .-> pipeline ``` - [`smf_contracts`](https://pub.dev/packages/smf_contracts) defines the module model: modules, roles, sockets, contributions and the built-in roles. `package:smf_contracts/core.dart` is the model without concrete roles. - [`smf_pipeline`](https://pub.dev/packages/smf_pipeline) runs the stages. It imports only `core.dart`, so it knows no concrete role and no module, and everything specific comes from the modules and the roles themselves. It also has the contract harness, which the tests of modules use. - [`smf_flutter_cli`](https://pub.dev/packages/smf_flutter_cli) is the `smf` command: the list of modules it offers, and the terminal, the files and the processes of the machine it runs on. - Every module is a package of its own. It depends on `smf_contracts`, and on `smf_pipeline` only in its tests. # How settings work Source: https://doc.saymyframe.com/concepts/settings A setting is something the user chooses and the app remembers, such as the theme mode. In SMF a setting belongs to the module, or to the role, whose code needs it. That owner keeps the state of the setting, and three roles do the rest without knowing the owner: ```mermaid flowchart LR owner["Owner of a setting
a module or the template of a role"] owner -- "a restorer" --> prefs(["Preferences role"]) owner -- "an entry" --> screen(["Settings screen role"]) owner -- "texts" --> texts(["Localization role"]) sp["shared_preferences"] -. provides .-> prefs settings["settings"] -. provides .-> screen l10n["gen_l10n"] -. provides .-> texts ``` The preferences role remembers the setting, the settings screen role shows it to the user, and the localization role translates its label. A module can leave each of them optional by only using the role. Then, without preferences, the setting lasts as long as the app runs. Without a settings screen, the app gets no row for it. Without the localization role, its label is in English. ## The state belongs to the owner The owner keeps the setting in an object of its own, such as a `ValueNotifier` in a file that it generates. Widgets listen to that object and change the setting through it. They never touch the preferences, as the screens of a feature never touch the DI container. ## Preferences The preferences role keeps the settings of the app, and no secrets. Nothing in the preferences is encrypted, and a backup of the device carries them, so a token, a password, an API key or an encryption key never goes there. A secret belongs in the secure storage of the platform. The template of the role generates `lib/core/preferences/app_preferences.dart` with the `AppPreferences` interface, `initPreferences()` and `createAppPreferences()`. The module that provides the role contributes the implementation, as the providers of the other [service roles](https://doc.saymyframe.com/extending/role-provider.md#a-service-events-analytics-crash-reporting) do. An owner does not ask for the preferences. It gives the role a restorer, a function that takes the `AppPreferences`, through the socket `PreferencesRole.restorers`, and the app hands the preferences to every restorer when it starts: ```mermaid sequenceDiagram participant boot as bootstrap() participant init as initPreferences() participant impl as Implementation of the provider participant restorer as Restorer of an owner participant state as State of the owner boot->>init: await, in the platform phase init->>impl: open impl-->>init: AppPreferences init->>restorer: call with the preferences restorer->>state: the saved value, and the preferences Note over boot: DI phase, late phase, first frame state->>impl: later, a choice of the user: save it ``` A restorer keeps to these rules: - It is a function of the type `void Function(AppPreferences preferences)`. - It runs in the platform phase of `bootstrap()`, before the DI container is filled and before the first frame. So the setting has its saved value when the first screen builds, and when a router first asks a [guard](https://doc.saymyframe.com/concepts/guards.md) that reads it. - It reads the settings of its owner, puts them into the state of its owner, and keeps the preferences there for the writes to come. - It is synchronous and awaits nothing. The reads are synchronous, so it has done all of its work when it returns. The role does not wait for an asynchronous restorer and does not catch what such a one throws. - It keeps the current value when nothing is saved under its key. A write before the preferences are open changes only memory, so state that a test sets before `bootstrap()` survives the start. - It may run more than once. A test runs `initPreferences()` again to see what the next launch reads, and each restorer then gets the preferences that were opened anew. The role calls each restorer on its own, since the owners know nothing of each other. What one throws keeps no other from restoring and does not stop the start-up. The app starts with the defaults of that owner, and in debug mode it prints what was thrown. A restorer is the way to the preferences that every app has, for a module and for the template of a role. Neither calls `createAppPreferences()`, and only `bootstrap()` calls `initPreferences()`; a rule of the role checks both in the generated code. The tests of an app are free to call both, to read a key and to open the preferences again. In an app with a DI container, the role also registers the preferences there as a lazy singleton. So a service can take them as a dependency of its factory, and the composition file of a feature can resolve them. A key is `.`, such as `theme.mode`, where the owner is the module or the role whose code keeps the setting. The ids of modules and roles differ, so the keys of owners that keep to this form do not collide. Nothing checks it: two owners that save under one key overwrite each other's setting. If the preferences cannot be opened, `initPreferences()` fails, and `bootstrap()` with it. ## The settings screen The settings screen role connects the owners of settings with the screen that shows them. An owner contributes a `SettingsEntry`, which names the widget of the setting in a file that the owner generates. The widget has a `const` constructor that requires no arguments, so the screen can create it knowing nothing but its class. It reads and changes its setting itself. The module that provides the role is a module with a route that shows the screen, and it names that route with a `SettingsScreenRoute`. So the role requires the router. Every provider promises the same screen: - It shows every entry once, in the order of the role: the entries of the modules, in the order the modules were chosen, and then those of the templates of roles. - It shows them one below the other in a list that scrolls, on a `Material`. Each entry gets the same width and no limit on its height, so an entry may be a `ListTile` or a column of them. - It creates the widget of each entry through an import of its file with a prefix of its own. Two owners may name their widgets alike, and they still do not clash. How the user gets to the screen is up to the provider. `settings` makes its route a destination of the main navigation, which an app with a layout shows. The contract harness checks that the provider creates the widget of every entry, so the tests of an owner read its entry from the role and never from the files of a provider. What only a running app shows, such as the order and the scrolling, SMF's CI checks in running apps; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ## The theme mode, a setting of a role The theme role is built from these pieces, and it shows what the template of a role is for. The role splits the theme between its provider and its template: ```mermaid flowchart TB provider["Provider of the theme role
createLightTheme(context)
createDarkTheme(context)"] subgraph template ["Template of the theme role"] mode["appThemeMode
AppThemeModeScope"] row["ThemeModeSetting"] end root["Root MaterialApp
theme and darkTheme
themeMode"] provider --> root mode --> root mode -- "restoreAppThemeMode" --> prefs(["Preferences role"]) row -- "an entry" --> screen(["Settings screen role"]) row -- "texts" --> texts(["Localization role"]) ``` The provider owns the look. It generates `lib/core/theme/app_theme.dart` with `createLightTheme(context)` and `createDarkTheme(context)`, and that is all the role asks of it. The template owns the mode, the same with every provider. It generates `appThemeMode`, the controller of the mode, and `AppThemeModeScope`, the widget around the root of the app through which the root reads the mode. It gives the preferences role the restorer of the mode, which is saved under the key `theme.mode`. In an app with a settings screen, it generates `ThemeModeSetting` and gives the settings screen role an entry for it, and it gives the localization role the texts of that entry. It also gives the root `MaterialApp` its `theme`, its `darkTheme` and its `themeMode`. The role requires the preferences role, so an app with a theme always remembers the mode, and it only uses the other two. The three arguments of the root take one value each. A module that sets one of them cannot be in an app with the theme role, and `smf create` reports the two values. A provider whose look depends on state of its own, such as a color that the user picks, puts an inherited widget with that state among the root wrappers and reads it from the context that its two functions get. For a setting of that kind it contributes an entry of its own. The language of the app is a setting of a role in the same way. The template of the localization role keeps the language that the user chose in `appLocale`, gives the preferences role its restorer, and gives the settings screen role the entry that chooses it; see [Texts and languages](https://doc.saymyframe.com/concepts/localization.md#the-language-that-the-user-chose). ## Next - [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md) and [Theme](https://doc.saymyframe.com/guides/theme.md) show what the app has and how its code uses it. - [Add a setting](https://doc.saymyframe.com/extending/settings.md) builds a module with a setting, its restorer, its entry and its texts. - [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#preferences), [Provide the settings screen](https://doc.saymyframe.com/extending/provide-settings-screen.md) and [Provide the theme](https://doc.saymyframe.com/extending/provide-theme.md) cover the modules that provide these roles. # Texts and languages Source: https://doc.saymyframe.com/concepts/localization The texts that a user sees belong to the modules that show them. A module does not know which other modules the app has, which languages they speak or how the app keeps its translations. So it gives its texts to the localization role, and reads them back through the role: ```mermaid flowchart TB module["Module
its texts, with translations"] -- "TextsData" --> role(["Localization role"]) template["Template of another role
its texts"] -- "TextsData" --> role role -- "the texts and the languages of the app" --> provider["Provider of the role
a getter for each text"] provider -- "context.l10n" --> code["Code of the app"] ``` ## A text and its owner A text is a `LocalizedText`: a name, the text in English, and its translations by the code of their language, such as `uk`. The owner of a text is the module, or the template of a role, that gives it to the role as `TextsData`. The role names every text apart from those of other owners. The getter of a text starts with the id of its owner in lowerCamelCase, followed by the name of the text: the text `title` of the module `haptics` is read as `context.l10n.hapticsTitle`. When the texts of two owners would still need one getter, the role reports them. A text has no parameters and no plural forms, so neither its English text nor a translation has a brace. ## With the role and without it A module that only uses the localization role works in an app without it too. Its templates read a text through a variable that the role makes for it, and the variable has one value for each kind of app: | App | The variable `text_title` renders as | | --- | --- | | with the localization role | `context.l10n.hapticsTitle`, with the import of the file of the texts | | without it | `'Haptic feedback'`, the English text as a literal | The template of a role reads its texts the same way, through its render hook. [Texts](https://doc.saymyframe.com/extending/texts.md) shows the code. ## The languages of the app The template of the role chooses the languages of the app before the app is rendered: - By default, every language that a text of the app is in, English first and the others in the order the texts name them. - With the option `--locales`, the languages that it names, in its order. English is always among them, since a text reads in English wherever it has no translation. An app can be only in a language in which Flutter has the texts of its own widgets. The role knows those languages as `LocalizationRole.supportedLanguages`, the set of the oldest Flutter that SMF generates apps for. It leaves any other language of a text out of the app, and `--locales` refuses such a language. Without the option, the role warns of each language that it leaves out, with the owner and the texts. It always warns about each text that has no translation into a language of the app. The role asks no question: the languages follow from the texts of the modules and from the option. In an app that no route starts, [`flutter_core`](https://doc.saymyframe.com/modules/flutter-core.md#its-texts-and-the-languages-of-the-app), the module that every app has, gives the role the two texts of its fallback start screen, in English and in Ukrainian. The other built-in modules have their texts in both languages too. So by default an app with the role is in both languages, also an app without a feature. ## What the role generates Whichever module provides the role, its template generates `lib/core/l10n/app_locale.dart` with: - `appLocales`, the languages of the app as `Locale`s, the first of which the app uses when the device asks for none of them; - `appLocale`, which keeps the language that the user chose: its `value` is one of `appLocales`, or `null` while the app follows the device, and `choose()` changes it; - `AppLocaleScope`, the widget around the root of the app through which the root reads `appLocale`, so that it rebuilds in the new language when the choice changes; - `restoreAppLocale()`, the restorer of the choice. The template also gives the root `MaterialApp` its `locale`, its `supportedLocales` and the delegates of Flutter's own localizations, adds `flutter_localizations` to the app, and names the languages in the `Info.plist` of the iOS app. In the README of the app, it writes the section "Languages", which tells each place that a new language goes into. ## The language that the user chose The language is a setting of the role, as [the theme mode](https://doc.saymyframe.com/concepts/settings.md#the-theme-mode-a-setting-of-a-role) is a setting of the theme role. So the role works with two more roles: | Role | The localization role | What its template gives it | | --- | --- | --- | | Preferences | requires it | `restoreAppLocale`, a restorer. A choice is saved under the key `localization.locale`, as the code of the language, and removed when the app follows the device again. | | Settings screen | uses it | In an app with a settings screen, `LanguageSetting`, the entry in which the user chooses a language of the app or the languages of the device, in `lib/core/l10n/language_setting.dart`. | The texts of the entry are texts of the template itself, in English and in Ukrainian, which it gives the role only in an app with a settings screen. The entry shows a language by its name in that language. The role has the names of English and Ukrainian, and `smf create` warns of any other language of such an app, whose name the developer adds to the file of the entry. Because the role requires the preferences, an app with a module that provides the localization always has a module that provides the preferences, and remembers the language. [Languages](https://doc.saymyframe.com/guides/languages.md#the-language-that-the-user-chose) shows `appLocale` from the side of the app. ## What the provider generates The provider keeps the texts. It generates `lib/core/l10n/l10n.dart` with the extension `AppTexts` on `BuildContext`, whose getter `l10n` returns an object with a `String` getter for each text of the app: - Each getter returns the text in the language of the context, or in English when the text has no translation into that language. - The provider renders the texts in the languages of the app only. - `context.l10n` works in every context below the root of the app, in the language that the root is in, also once that language changes. How the texts get there is the provider's choice: in files of translations that a tool turns into code, or in Dart code. [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) keeps them in ARB files, one for each language, from which gen-l10n of Flutter generates the code. A provider that loads its texts with a delegate adds the delegate to the `localizationsDelegates` of the root. ## Rules In an app with the role, the role checks the modules before the app is generated, and the contract harness checks the generated code: | Rule | What it requires | | --- | --- | | `localization.texts` | The texts of a module have lowerCamelCase names that differ, an English text, translations by the code of their language, and no braces. A variable of a brick that reads a text reads one that the app has, and is its English text in an app without the role. A text in the data of another role, such as the label of a destination, is among the texts that its module gave the role, and two such texts of one name do not differ. | | `localization.text_access` | Code of a module reads only its own texts and those of the modules it depends on. The template of a role reads its own, and the texts in the data that the modules give its role or a role that it requires or uses, such as the labels of the destinations. | | `localization.texts_rendered` | A file of the provider names the getter of every text of the app. | The role also says what holds at the root of the app. Every delegate among the `localizationsDelegates` of the root supports each language of the app, and the `supportedLocales` of the root are those of the role alone: the argument takes the items of one contributor, so `smf create` reports a module that gives the root a locale of its own as a conflict with the role. So a module brings no delegate for texts of its own, which would have to know the languages of the app, and adds no language to the root. It gives its texts to the role. ## Next - [Languages](https://doc.saymyframe.com/guides/languages.md) shows what the app has and how its code reads a text. - [Texts](https://doc.saymyframe.com/extending/texts.md) shows how a module gives its texts and reads them in its templates. - [Provide the localization](https://doc.saymyframe.com/extending/provide-localization.md) covers a provider of the role. # Guards of routes Source: https://doc.saymyframe.com/concepts/guards A guard keeps the user from screens of the app until something holds. There are two kinds: - A gate keeps the user from the whole app, such as an onboarding that the user has to finish first, terms to accept, or a sign-in in an app that nobody uses without an account. The built-in gates are that of [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) and `sign_in.gate` of [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md). - A guard that stands for a condition keeps the user only from the routes that ask for the condition, such as the screens that need an account. The built-in one is `sign_in.hasAccount`. [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md) describes it. A module declares a guard as data of the router role, next to its routes. Whichever module provides the router then asks the guards of every module the same way, and the other modules of the app know nothing of them. ## A gate over the whole app A module declares a guard as a `RouteGuard` of `smf_contracts`: | Part of a guard | What it is | | --- | --- | | `name` | The name of the guard in its module. The full name is `.`, such as `terms.accepted`. | | `allows` | A function of the app that returns a `ValueListenable`: whether the guard allows, which notifies its listeners when that changes. | | `redirectTo` | The target of the guard: a route of the module, which the router shows while the guard does not allow. | | `stage` | When the app asks the guard among the guards of its kind: `GuardStage.welcome` or `GuardStage.identity`. Every guard has one. See [the order of the guards](#the-order-of-the-guards). | | `resumes` | Whether the router brings the user back to where they were once the guard allows again. It is `true` unless the guard says otherwise. See [where the user comes back to](#where-the-user-comes-back-to). | | `condition` | The condition that the guard stands for. A guard without one is a gate. | The target and the routes below it are the flow of the guard, the screens that the user may see while the guard does not allow. While a gate does not allow, the router shows the target in place of every location outside the flow, of whichever module. The target is a top-level route of the module that needs no values and is outside the main navigation, which a gate keeps the user out of. No route of the flow can start the app, and none of them asks for a condition. The app calls the function of a guard once, when its router first asks the guards, which is after `bootstrap()`. From then on it reads the value whenever it asks. So the value is known without waiting: a guard that depends on something saved on the device takes it in `bootstrap()`, as a [restorer of the preferences](https://doc.saymyframe.com/concepts/settings.md#preferences) does. The value changes outside the build of a frame, such as in the handler of a tap, because the router navigates when it changes. ## What the user sees A feature `terms` keeps the user at `/terms` until the terms are accepted. The app starts on `/home`: ```mermaid sequenceDiagram actor user as User participant router as Router participant navigation as GuardedNavigation of the role participant guard as Guard terms.accepted user->>router: starts the app, which opens on /home router->>navigation: asked about home.home at /home navigation->>guard: does it allow? guard-->>navigation: no navigation-->>router: show /terms instead, and /home is remembered router->>user: the terms screen user->>guard: accepts the terms guard->>router: guardChanges notifies router->>navigation: changed, with its pages navigation-->>router: show /home instead, the remembered location router->>user: the home screen ``` The screen of the flow only changes what the guard reads. It navigates nowhere: the router leaves the flow. ## The flow is closed The routes of a flow show only while a guard with that flow does not allow. The flow is over once the guard allows, and every other guard of the module with the same target allows too. From then on the router shows the screen that the app starts on in place of each location of the flow, whether `go()`, `push()`, `replace()` or the platform asks for it. Such a `push()` completes with `null`. While another gate does not allow, the router shows the target of that gate instead. So no code navigates into the flow of a gate, and that includes the module of the guard: it changes what the guard reads, and the router shows the target. A link to `/onboarding` in an app whose onboarding is finished opens the screen that the app starts on. A guard that stands for a condition is the exception. While it does not allow and every gate does, the routes of its flow show like any route, so a screen may open its target, and a link to one of them opens it over the screen that the app starts on; see [the flow of such a guard](https://doc.saymyframe.com/concepts/conditions.md#the-flow-of-the-guard). ## The order of the guards The app asks its gates first, and then its guards that stand for a condition. It asks the guards of each kind by their stage, then in the order of the modules, then as their module declares them. | Stage | What it is for | | --- | --- | | `GuardStage.welcome` | What a new user goes through on the first launch, before the app asks who the user is, such as an onboarding. | | `GuardStage.identity` | What asks who the user is, such as a sign-in. | The app asks the guards of an earlier stage first, whatever the order of the modules. The guard of `onboarding` has the stage `welcome`, and the two guards of `sign_in` the stage `identity`. So the onboarding comes before the sign-in, whichever of the two modules was named first, and neither module names the other to place its guard. The first gate that does not allow decides, for every route, and no later guard is asked. That is why the flows of the gates show one after another. Only when every gate allows does the app ask the guards that stand for a condition. A module cannot add a stage. A guard that is neither of the two takes the stage that its flow belongs to: `welcome` if the flow needs to know nothing of the user, as that of a consent or of a required update, and `identity` if it needs to know who the user is, as that of a subscription. The order of the modules then places it among the guards of that stage. So the app may ask such a guard before the guard that asks who the user is, and it allows while it cannot tell who the user is. In the app, the stage shows only in the order of `routeGuards`. ## What every router does Before it shows a location, a router asks the guards about it. That holds for the location the app starts on, for each location that `go()`, `push()` or `replace()` is asked to show, and for each location that the platform gives the router. | The location | What the router does | | --- | --- | | A gate keeps the user from it. | It shows the target of the gate in its place, as `go()` to the target does. The target takes the whole stack, and the stacks of every branch of the main navigation. Such a `push()` completes with `null` at once. | | It is in a flow that is over. | It shows the screen that the app starts on in place of the stack. Such a `push()` completes with `null` at once. | | It asks for a condition that does not hold. | It opens the target of the guard of that condition over the page that the user is on, and the request waits; see [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md#what-the-user-sees). | | It is a page of the flow of a guard that stands for a condition, and a link asks for it, with no page of the app below it. | It opens that page over the screen that the app starts on, so that back leads into the app; see [the flow of the guard](https://doc.saymyframe.com/concepts/conditions.md#the-flow-of-the-guard). | In the first two cases the router never builds the screen of the location that was asked for, and the listeners of the screen never hear of it. In the third it shows that screen once the condition holds. When a guard starts or stops allowing, the router tells the role of the pages that the user can get back to, and does what the role answers. It shows a location in place of its whole stack, closes the pages on top that have to leave, or leaves everything as it is. The target of a gate takes the pages of every branch of the main navigation, since a gate keeps the user from those pages. That holds whenever the gate allows again: also in the turn in which it stopped allowing, as when code signs one user out and the next one in, and while the transition to its target is on its way. Each branch is then back on its destination. ## Where the user comes back to The role remembers one location for the user to come back to, and it remembers one only for a gate: | What happened | What the role remembers | Where the user lands once the gates allow | | --- | --- | --- | | The user or the platform asked for a location that a gate kept them from. | That location. A later one replaces an earlier one, so a link that arrives while the flow is shown wins. | The remembered location. | | A gate that brings the user back stopped allowing while the user was in the app, and nothing was remembered yet. | The location below the pages that pushes showed, such as the tab that those pages were opened from. When pushes showed every page, the screen that the app starts on. | The remembered location. | | A guard that does not bring the user back stopped allowing. | Nothing. It also forgets what it remembered, for whichever gate. | A location that was asked for since then, or else the screen that the app starts on. | | A gate started allowing with nothing remembered, as in an app that the platform opened on a location of the flow. | Nothing. | The screen that the app starts on. | The role never remembers a location in the flow of a guard: once that guard allows, its flow is over. Once the router has shown the remembered location, the role forgets it. It also forgets it when the user moves on, which is when the router asks about a location that no gate keeps the user from and that is outside every flow, or in one that is over. A guard brings the user back unless it says otherwise, with `resumes: false`. The guard of the onboarding brings the user back: a user who asked to see the onboarding again comes back to the screen they were on. The guards of `sign_in` say otherwise. After a sign-out, the next user comes neither to the screen that the last one was on nor to a link that the last one followed. A location that is asked for after such a guard stopped, while it does not allow, is still remembered, so the user comes to a link that arrives then. The role looks at the guards each time the router asks about a location or tells it that a guard notified. It takes a guard to have stopped when the guard does not allow and allowed at the look before. So a guard that does not allow from the first launch has not stopped, and the location that the app is opened with is shown after the flows of a first launch. A guard that stops and allows again between two looks, such as one that does not notify, is not seen to stop, and the role forgets nothing then. ## What a screen does A screen never closes itself, and never navigates, after it changed what a guard reads. The router has done both by then. That goes for a screen of a flow that made its guard allow, as after a sign-in. It also goes for a page that asks for a condition and ends it itself, as a screen of an account does with its sign-out. A `pop()` after the change closes the page that is on top by then. After a sign-in that is the page that the user asked for, and a `push()` that waited for it completes with `null`. After a sign-out it is the page below the one that the router closed, which may be the main navigation of the app. A `go()` after the change takes the place of what the router showed. ## What the role generates In an app whose modules declare guards, the template of the router role adds to `lib/core/router/app_router.dart`: | | | | --- | --- | | `routeGuards` | The guards of the app, in the order the app asks them. Each is a `RouteGuard` of the app, a class that the role generates into that file. It is not the class of `smf_contracts` with the same name, with which a module declares the guard. | | `redirectOf(routeName)` | The location that the guards show when the router is asked for a route, or `null` when they let the user see it. | | `flowIsOver(routeName)` | Whether the route is in the flow of a guard and every guard with that flow allows. | | `guardChanges` | A `Listenable` that notifies when a guard starts or stops allowing. | | `GuardedNavigation` | The class through which a router asks the guards, with `asked` and `changed`, and the classes of its answers: `ShowInstead`, `ShowOver`, `ShowNothing` and `ClosePages`. It keeps the remembered location. | A guard of the app has its full name, its `allows`, its target as `redirectTo`, and the full names of the routes of its `flow`. It has `resumes: false` when it does not bring the user back, and a guard that stands for a condition has the `routes` that ask for it. This is the list of an app with `onboarding` and `sign_in`: ```dart title="lib/core/router/app_router.dart" final List routeGuards = [ RouteGuard( 'onboarding.firstRun', allows: guard0.onboardingCompleted(), redirectTo: const OnboardingOnboardingLocation(), flow: const {'onboarding.onboarding'}, ), RouteGuard( 'sign_in.gate', allows: guard1.signInAllowsApp(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, ), RouteGuard( 'sign_in.hasAccount', allows: guard1.signInHasAccount(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, routes: const {'sign_in.account'}, ), ]; ``` The two gates come first, by their stages, and the guard that stands for a condition after them. The two guards of `sign_in` show the same target, so they have one flow, which is over once both allow. The class decides what a router does about the guards, and the memory of the gates is in it, written once. A module that provides the router only asks and does what it is answered. So routers that ask alike show the user the same pages at the same time. One thing is up to the router: whether it can close on its own a page that `replace()` showed in place of a page that no push showed, which changes the location that the role remembers below such a page. An app without guards gets none of this code. ## Rules | Rule | What it requires | | --- | --- | | `router.guards` | The guards of a module have valid names and functions of the app. Each shows a top-level route of the module that needs no values, is outside the main navigation, and has no start candidate in its flow. A guard that stands for a condition is the only one of its module for it, and the module requires or provides the role of the condition. | | `router.guard_functions` | The function of every guard is a top-level function of its file that takes no arguments and returns a `ValueListenable`. | | `router.guards_asked` | In an app with guards, the files of the module that provides the router create a `GuardedNavigation`, read `guardChanges`, and name the answers `ShowOver` and `ClosePages`. | The first is checked before an app is generated, and the other two by the contract harness. The last one keeps a router that knows nothing of the guards out of an app with a module that needs them. It does not tell whether a router does what the guards answer: only a running app shows that, and SMF's CI checks it there with every router that SMF has. See [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). `smf create` also refuses a `--start` in the flow of a guard, since the app shows the flow until the guard allows, and then the screen that it starts on. ## Next - [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md) describes a guard that keeps the user only from some routes. - [Navigation](https://doc.saymyframe.com/guides/navigation.md#guards) describes the guards from the side of the app. - [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md#a-guard) declares the guard of this page. - [Ask the guards in a router](https://doc.saymyframe.com/extending/router-guards.md) shows how a router asks the guards, and [`go_router`](https://doc.saymyframe.com/modules/go-router.md#guards) how go_router does. # Conditions of routes Source: https://doc.saymyframe.com/concepts/conditions A [gate](https://doc.saymyframe.com/concepts/guards.md) keeps the user from the whole app. Some screens need more than the rest of the app does: in an app that lets everyone in, the screen of the account is still only for a user with an account. A condition is what such a screen needs. Three parties meet through it, and the modules among them need not know each other: ```mermaid flowchart LR feature["A feature
with a screen that needs an account"] -- "asks for it on a route" --> condition(["A condition of a role
AuthRole.account"]) guard["sign_in
the module with the screens of sign-in"] -- "stands for it with a guard" --> condition ``` - A role publishes the condition, since the role knows what it is. The auth role publishes `AuthRole.account`. - A feature asks for the condition on a route. It lists the role among its roles, and knows no module with a guard. - A module that requires or provides the role stands for the condition with a guard. The function of the guard says whether the condition holds, and its target is the route to show until it does. The built-in [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) does the last two itself: its route of the account asks for `AuthRole.account`, and its guard `sign_in.hasAccount` stands for it. A feature of yours that asks for the same condition gets the same guard, without naming `sign_in`. ## Who declares what A role publishes a condition as a constant of its class, a `RouteCondition` with the role and a name: ```dart static const account = RouteCondition(authRole, 'account'); ``` Messages name a condition `.`, such as `auth.account`. No code of an app has the name. A feature asks for the condition in `Route.conditions`, and the routes below that route ask for it too. This is the route of the account of `sign_in`: ```dart Route( '/account', name: 'account', screen: ScreenRef( 'AccountScreen', import: ImportRef.app('$_folder/account_screen.dart'), ), conditions: [AuthRole.account], ), ``` Every user gets to the main navigation, to the screen that the app starts on and to the flow of a guard. So a route that asks for a condition is none of these: it is no destination and below none, it is no start candidate and above none, and it is outside the flows of the guards of its module. A module stands for the condition with a `RouteGuard` whose `condition` names it, as `sign_in` does: ```dart RouteGuard( name: accountGuard, allows: FunctionRef('signInHasAccount', import: _guards), redirectTo: _route, stage: GuardStage.identity, resumes: false, condition: AuthRole.account, ), ``` The module declares at most one guard for a condition, and an app has one: two modules with a guard for the same condition cannot be in one app. ## What the user sees While the condition does not hold, a request for a route that asks for it opens the target of the guard over the page that the user is on, and the request waits. Here a user without an account is on the settings screen and taps the entry of the account, which pushes `/sign_in/account`: ```mermaid sequenceDiagram actor user as User participant router as Router participant navigation as GuardedNavigation of the role participant guard as Guard sign_in.hasAccount user->>router: push of /sign_in/account, from /settings router->>navigation: asked about sign_in.account, on top of settings.settings navigation->>guard: does it allow? guard-->>navigation: no navigation-->>router: show the target of the guard over the page router->>user: the sign-in screen, over the settings screen Note over router: the request waits user->>guard: signs in guard->>router: guardChanges notifies router->>navigation: changed, with its pages navigation-->>router: close the page on top router->>navigation: asked about sign_in.account again navigation-->>router: show it router->>user: the screen of the account, over the settings screen ``` | What happens | What the router does | | --- | --- | | The user goes back from the target. | The user is on the page they were on, and the request is dropped. A `push()` that waited completes with `null`. | | The condition holds. | The router closes the pages of the flow and does what was asked. `push()` shows the route over the page that the user was on and completes with the value of its page. `go()` shows the route in place of the stack, and `replace()` in place of that page. | | A further request for a route that asks for the condition, while a page of the flow is open. | Nothing. The flow is open already, and the first request waits. | | The platform asks for such a route, or code does before the app has a page. | The target opens over the screen that the app starts on. Once the condition holds, the route shows as `go()` to it does. | For a route that asks for two conditions, the target of the first guard that does not allow opens. Once that guard allows, the router closes its flow and asks about the request again, so the target of the second guard opens in turn. ## When the condition stops holding When the condition stops holding, the router closes each page that asks for it, with the pages over it. The user is then on the page that those pages were opened from. A page that asks for the condition and has no page below it, as after `go()` to it, leaves for the screen that the app starts on. So a screen that ends the condition itself, as the screen of the account does with its sign-out, only ends it. It neither closes itself nor navigates; see [what a screen does](https://doc.saymyframe.com/concepts/guards.md#what-a-screen-does). ## The flow of the guard The flow of such a guard is its target and the routes below it, as for a gate, and it is over once the guard allows. Until then every route shows that does not ask for the condition, and the routes of the flow are among them. So a module may navigate to the target of its guard while the condition does not hold, as to the sign-in that a guest opens. | How a page of the flow is asked for | What the router shows | | --- | --- | | With `push()`, on a page | The page of the flow over that page, so the user can go back from it. Once the condition holds, the router closes it as it closes a target that it opened itself. | | With `go()`, on a page | The page of the flow in place of the stack, as the code asked, with no way back. | | With no pages, as by a link | The page of the flow over the screen that the app starts on, with that screen alone below it. Back leads into the app, and the router closes the page once the condition holds. That goes for a route below the target too. | Asked for by a link, a page of the flow would stand alone otherwise, with no way back into the app. A flow that a gate keeps open too is the gate's, and its page takes the place of the stack. The screens of the flow move between its routes with `push()` or `replace()`, which keep the request waiting. `go()` takes the place of the page that the flow was opened over, and the request goes with it. ## Next to a gate The app asks its gates first, so a gate that does not allow decides for every route, and for the routes that ask for a condition too. A guard that stands for a condition may show the target of a gate of its module. The two then have one flow, which is over only once both allow. The two guards of `sign_in` are such a pair: in an app whose gate lets everyone in, the screens of the sign-in still show while `sign_in.hasAccount` does not allow. The functions of two such guards read one notifier, so that the router never finds that one of them changed and the other did not yet. When a gate stops allowing while the flow of a condition is open, the target of the gate takes the place of the stack, and the request is dropped with the pages of its flow. If that target is a page of the same flow, the request waits on and is dropped once the target leaves. The router remembers a location only for a gate. A guard that stands for a condition takes the user from no location: when it stops allowing, the user is on the page below the pages that closed, whatever its `resumes` says. With `resumes: false`, such a guard still makes the router forget what a gate made it remember. ### Two known limits Behind a gate that does not allow, the router remembers a location for the gate and opens no flow. Two kinds of links are lost that way: - A link to a route that asks for a condition. If the gate then allows while the condition does not hold, the user comes to the screen that the app starts on. The same link opens the target of the guard over the start screen in an app whose gates allow. - A link to a page of the flow of a guard that stands for a condition, behind a gate with another flow. The router never remembers a location in a flow. So in an app that everyone may use, a link that opens the app on a first launch, behind an onboarding, to the screen of the account or to the sign-in leaves the user on the screen that the app starts on once the onboarding is finished. ## An app without a guard for the condition An app may have no guard that stands for a condition: it lacks the role, or it has no module with such a guard. The routes that ask for the condition then show like any other, and the router role reports nothing. Whether such an app is worth a warning is up to the role of the condition. Its hooks see the routes and the guards of the app when it requires or uses the router role, with `RouterFacade.routesAsking(condition)` and `RouterFacade.guardFor(condition)`. The auth role warns this way when routes ask for `AuthRole.account` and no guard of the app stands for it, as in an app with a feature that asks for it and without `sign_in`. The warning names each such route, here the route `orders.orders` of such a feature: ```text The route orders.orders is for users with an account (it asks for the condition auth.account), but no module of the app has a guard for that condition, so every user gets to it. ``` It is a warning and no error, since the developer of the app may write the guard later. ## In the app In the app, a guard that stands for a condition has `routes`, the full names of the routes that ask for it, which the role collects from every module. The app has nothing else of a condition. This is the guard of `sign_in`: ```dart title="lib/core/router/app_router.dart" RouteGuard( 'sign_in.hasAccount', allows: guard0.signInHasAccount(), redirectTo: const SignInSignInLocation(), flow: const {'sign_in.signIn', 'sign_in.signUp', 'sign_in.resetPassword'}, resumes: false, routes: const {'sign_in.account'}, ), ``` The `routes` do not inherit in the app. The role lists each route below a route that asks, and a developer who adds a route by hand adds the routes below it too. ## Rules | Rule | What it requires of a condition | | --- | --- | | `router.routes` | A route asks only for conditions of the roles that its module requires, uses or provides. Such a route is outside the main navigation and the flows of the guards of the module, and neither it nor a route below it is a start candidate. | | `router.guards` | A guard that stands for a condition is the only one of its module for it, and the module requires or provides the role of the condition. | `smf create` checks both before it generates an app. It also reports the guards of two modules that stand for one condition, and refuses a `--start` on a route that asks for a condition, also in an app without a guard for it. ## Next - [Guards of routes](https://doc.saymyframe.com/concepts/guards.md) describes the gates, the order of the guards and where the user comes back to. - [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md#a-route-that-asks-for-a-condition) asks for a condition on a route and declares a guard for one. - [Define a role](https://doc.saymyframe.com/extending/new-role.md#conditions-for-routes) publishes a condition. - [Ask the guards in a router](https://doc.saymyframe.com/extending/router-guards.md) shows what a router does with the answers. # Extending SMF Source: https://doc.saymyframe.com/extending The modules of SMF are ordinary Dart packages built on [`smf_contracts`](https://pub.dev/packages/smf_contracts). A module of yours follows the same rules and goes through the same checks as the built-in ones. The pages of this section show how to write one, test it and generate apps with it. ## What you can write - A feature has screens with their routes and their state for each state manager, and gets its services through dependency injection. It can keep the user from the rest of the app with a guard, and ask for a condition, such as an account, on the routes that need one. See [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md). - An infrastructure module sets up a library or a service with start-up code, native settings, dependencies, checks of the machine, commands that run after generation and the steps that only the developer of the app can do. See [Write an infrastructure module](https://doc.saymyframe.com/extending/infrastructure-module.md). - A module of either kind can have a setting that the app remembers and shows on its settings screen, a step of the onboarding, texts in the languages of the app, and notes for the coding agents that work on the app. See [Add a setting](https://doc.saymyframe.com/extending/settings.md), [Add a step to the onboarding](https://doc.saymyframe.com/extending/onboarding-steps.md) and [Texts](https://doc.saymyframe.com/extending/texts.md). - A provider of a role can be another router, DI container, state manager or layout, a service for analytics, crash reporting, events, preferences, notifications, push messages or purchases, sign-in, a settings screen, an onboarding, a theme, the texts of the app, or the values of `.env`. See [Provide a role](https://doc.saymyframe.com/extending/role-provider.md). - A new role is a replaceable part of an app that SMF does not have yet, with its sockets, its template, its options and its rules. See [Define a role](https://doc.saymyframe.com/extending/new-role.md). Before you start, read [the module model](https://doc.saymyframe.com/concepts/module-model.md) and [module independence](https://doc.saymyframe.com/concepts/independence.md), since the rules that the pipeline enforces follow from them. ## How a module reaches an app `smf` offers a fixed list of modules. To generate apps with a module of yours, build a command of your own on `smf_flutter_cli`, which exports the command line as `runCli` and its modules as `smfModules`: ```dart title="bin/my_smf.dart" import 'dart:io'; import 'package:smf_counter/smf_counter.dart'; import 'package:smf_flutter_cli/smf_flutter_cli.dart'; Future main(List arguments) async { final code = await runCli( arguments, modules: const [...smfModules, CounterModule()], ); await Future.wait([stdout.flush(), stderr.flush()]); exit(code); } ``` The command has every option and question of `smf create`, and it offers your module next to the built-in ones: ```bash dart run bin/my_smf.dart create my_app -m home,counter,bottom_tabs,bloc ``` A module that many apps need can also become part of SMF itself; see [Contributing](https://doc.saymyframe.com/contributing.md). [Publish and use a module](https://doc.saymyframe.com/extending/publishing.md) covers both ways. ## The pages of this section 1. [A module package](https://doc.saymyframe.com/extending/module-package.md) covers the layout of the package, its bricks and their bundles. 2. [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md) builds a counter screen with BLoC and Riverpod variants from start to end, declares a guard, and asks for a condition on a route. 3. [Write an infrastructure module](https://doc.saymyframe.com/extending/infrastructure-module.md) covers sockets, dependencies, notes for coding agents, checks of the machine, steps after generation and steps by hand. 4. [Add a setting](https://doc.saymyframe.com/extending/settings.md) builds a module with a setting that the app remembers and shows on its settings screen. 5. [Add a step to the onboarding](https://doc.saymyframe.com/extending/onboarding-steps.md) gives the onboarding a page of a module, such as one that asks for a permission. 6. [Texts](https://doc.saymyframe.com/extending/texts.md) covers the texts of a module in the languages of the app. 7. [Provide a role](https://doc.saymyframe.com/extending/role-provider.md) covers plain providers, service roles, listeners of the router and providers that render the data of their role. Pages of their own cover [the guards in a router](https://doc.saymyframe.com/extending/router-guards.md) and four more roles: [the settings screen](https://doc.saymyframe.com/extending/provide-settings-screen.md), [the localization](https://doc.saymyframe.com/extending/provide-localization.md), [the theme](https://doc.saymyframe.com/extending/provide-theme.md) and [sign-in](https://doc.saymyframe.com/extending/provide-auth.md). 8. [Define a role](https://doc.saymyframe.com/extending/new-role.md) covers sockets, the interface, the template, options and their modes, warnings, conditions on a choice, conditions for routes and rules. 9. [Templates](https://doc.saymyframe.com/extending/templates.md) lists the rules of the bricks. 10. [Test a module](https://doc.saymyframe.com/extending/testing.md) covers the contract harness and the checks of the package. 11. [Rules for modules](https://doc.saymyframe.com/extending/rules.md) is a checklist. 12. [Publish and use a module](https://doc.saymyframe.com/extending/publishing.md) explains how a module reaches users. The API reference of every type is on pub.dev: [`smf_contracts`](https://pub.dev/documentation/smf_contracts/latest/) for the module model and [`smf_pipeline`](https://pub.dev/documentation/smf_pipeline/latest/) for the harness. # A module package Source: https://doc.saymyframe.com/extending/module-package A module is a Dart package. This is the package of the counter feature that [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md) builds: ```text smf_counter/ β”œβ”€β”€ pubspec.yaml β”œβ”€β”€ analysis_options.yaml β”œβ”€β”€ bricks/ β”‚ β”œβ”€β”€ counter/ β”‚ β”‚ β”œβ”€β”€ brick.yaml β”‚ β”‚ └── __brick__/lib/features/counter/counter_store.dart β”‚ β”œβ”€β”€ counter_bloc/ β”‚ β”‚ β”œβ”€β”€ brick.yaml β”‚ β”‚ └── __brick__/lib/features/counter/... β”‚ └── counter_riverpod/ β”‚ β”œβ”€β”€ brick.yaml β”‚ └── __brick__/lib/features/counter/... β”œβ”€β”€ lib/ β”‚ β”œβ”€β”€ bundles/ β”‚ β”‚ β”œβ”€β”€ counter_bundle.dart β”‚ β”‚ β”œβ”€β”€ counter_bloc_bundle.dart β”‚ β”‚ └── counter_riverpod_bundle.dart β”‚ └── smf_counter.dart └── test/ β”œβ”€β”€ architecture_test.dart └── counter_module_test.dart ``` - `lib/smf_counter.dart` holds the module: a class that extends `SmfModule`. - `bricks/` holds the templates of the files the module adds to an app, as [mason](https://pub.dev/packages/mason) bricks. - `lib/bundles/` holds the bricks bundled into Dart, which the module contributes. You generate them from `bricks/`. - `test/` runs the contract harness over the module and checks the rules of a module package; see [Test a module](https://doc.saymyframe.com/extending/testing.md). ## The pubspec ```yaml title="pubspec.yaml" name: smf_counter description: A counter feature for apps that SMF generates. version: 0.1.0 environment: sdk: ^3.12.0 dependencies: mason: ^0.1.1 smf_contracts: ^0.8.0 dev_dependencies: lints: ^6.0.0 smf_bloc: ^0.3.5 smf_flutter_core: ^0.7.0 smf_gen_l10n: ^0.6.0 smf_get_it: ^0.4.4 smf_go_router: ^0.6.2 smf_pipeline: ^0.8.0 smf_riverpod: ^0.3.5 smf_shared_preferences: ^0.4.5 test: ^1.24.0 ``` The code of a module needs `smf_contracts`, and `mason` for the bundles. The rest is for the tests: `smf_pipeline` has the contract harness, and the other modules make the apps of the tests complete. The package depends on another module only when the module declares it in `dependsOn`, as `smf_firebase_analytics` does with `smf_firebase_core`. A module is plain Dart. It runs inside `smf`, and the Flutter code it adds lives in its bricks. The code in `lib/` does not import `dart:io` or other libraries that reach the machine, and its checks and commands use the environment that the pipeline gives them. ## The module class A module imports the module model, `package:smf_contracts/smf_contracts.dart`, and declares its id once, as a constant: ```dart import 'package:smf_contracts/smf_contracts.dart'; final class CounterModule extends SmfModule { const CounterModule(); /// The id of the module, as in `-m counter`. static const id = ModuleId('counter'); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'A screen that counts taps', kind: ModuleKinds.feature, ); @override List contribute(ModuleContext context) => []; } ``` The id is lower snake_case and unique among the modules of a command. Another module refers to it through this constant, as in `dependsOn: {CounterModule.id}`, so a dependency on the module is a dependency on its package too. The description is what the questions of `smf create` show next to the id. ## Bricks A brick is a directory with a `brick.yaml` and the templates of its files in `__brick__/`, at their paths in the app: ```yaml title="bricks/counter/brick.yaml" name: counter description: "The store of the counter feature." version: 0.1.0+1 environment: mason: ^0.1.1 ``` A module has as many bricks as it needs. Files that only some apps get, such as the files of a variant, go into a brick of their own, which the module contributes only in those apps. Bricks have no mason hooks. SMF rejects a brick with hooks, and a module checks the machine and runs commands through its contributions instead. See [Templates](https://doc.saymyframe.com/extending/templates.md) for what a template may contain. Keep the bricks out of the analysis of the package, since their files are templates rather than Dart: ```yaml title="analysis_options.yaml" include: package:lints/recommended.yaml analyzer: exclude: - bricks/** ``` Do not run `dart format` on `bricks/` either, because it breaks templates that parse as Dart. ## Bundles The module contributes its bricks as bundles, which are Dart files that hold the bricks. Generate them with [mason_cli](https://pub.dev/packages/mason_cli): ```bash dart pub global activate mason_cli mason bundle bricks/counter -t dart -o lib/bundles mason bundle bricks/counter_bloc -t dart -o lib/bundles mason bundle bricks/counter_riverpod -t dart -o lib/bundles ``` Each command writes `lib/bundles/_bundle.dart` with a top-level variable such as `counterBundle`, which the module contributes as `BrickContribution(counterBundle)`. Bundle again after every change of a brick, and commit the bundles, since the published package needs them. # Write a feature module Source: https://doc.saymyframe.com/extending/feature-module The feature `counter` has one screen that counts taps on its button, and it does most of what a feature can do: - it declares a route for whatever router the app has, and a tab in the main navigation; - it registers a service of its own, `CounterStore`, in the DI container; - it keeps the count in a Cubit with BLoC or in a Notifier with Riverpod, through a variant for each state manager; - its composition file takes the store from the container, and its screens talk only to their state. The code below was generated into apps with both state managers and checked with `flutter analyze`. ## The descriptor ```dart title="lib/smf_counter.dart" import 'package:smf_contracts/smf_contracts.dart'; import 'package:smf_counter/bundles/counter_bloc_bundle.dart'; import 'package:smf_counter/bundles/counter_bundle.dart'; import 'package:smf_counter/bundles/counter_riverpod_bundle.dart'; /// A feature with a screen that counts taps on its button, with a variant /// for each module that manages state. final class CounterModule extends SmfModule { /// Creates the module. const CounterModule(); /// The id of the module. static const id = ModuleId('counter'); static const _store = ImportRef.app('features/counter/counter_store.dart'); /// The label of the tab of the counter. static const _label = LocalizedText( 'label', en: 'Counter', translations: {'uk': 'Π›Ρ–Ρ‡ΠΈΠ»ΡŒΠ½ΠΈΠΊ'}, ); @override ModuleDescriptor get descriptor => ModuleDescriptor( id: id, description: 'A screen that counts taps', kind: ModuleKinds.feature, // The composition file resolves the store. requires: const {diRole}, // The label of the tab follows the language of the app. uses: const {localizationRole}, variants: Variants( role: stateManagementRole, byProvider: { const ModuleId('bloc'): (context) => [ BrickContribution(counterBlocBundle), const PubspecContribution.hosted('flutter_bloc', 'any'), ], const ModuleId('riverpod'): (context) => [ BrickContribution(counterRiverpodBundle), const PubspecContribution.hosted('flutter_riverpod', 'any'), ], }, ), ); // ... contribute(), below. } ``` - `kind: ModuleKinds.feature` makes the module require the router role and keep its files in `lib/features/counter/`. It also lets the module resolve services in one place, its composition file. - `requires: {diRole}` is there because the composition file resolves the store, so the feature needs a DI container. When one module provides it, `smf create` adds that module, `get_it`, by itself. - `uses: {localizationRole}` is there for the label of the tab, a text that the app shows in its language. The module only uses the role, so it works in an app without it, where the label is in English. - `variants` has the contributions for each provider of the state management role, keyed by the provider's id. The feature does not depend on `smf_bloc` or `smf_riverpod`: the keys are plain values. Each variant brings the package of its state manager with the constraint `any`, so the version stays with the module that provides the role. A module with variants requires their role, so an app with the counter always has a state manager. - `selectedByDefault: true`, which this module leaves out, makes a run in a terminal offer the module selected among the modules of its kind, so that Enter takes it, as `home` does for a start screen that a new app should have. It is for a module with no role, since a module that provides a role is asked about through its role, where Enter takes the first provider. A run without a terminal takes only the modules that it was given. ## The store and its registration The store is a plain class in the brick `counter`, which every app with the counter gets: ```dart title="bricks/counter/__brick__/lib/features/counter/counter_store.dart" /// Keeps the count of the counter screen while the app runs. class CounterStore { /// The number of taps so far. int count = 0; } /// Creates the store; the DI container of the app calls it. CounterStore createCounterStore() => CounterStore(); ``` The module registers the store as data of the DI role, with its type and the top-level function that creates it. The default lifetime is a lazy singleton, which is created on first use: ```dart title="lib/smf_counter.dart" @override List contribute(ModuleContext context) => [ BrickContribution(counterBundle), diRole.data( const DiRegistration( type: TypeRef('CounterStore', import: _store), create: FactoryRef('createCounterStore', import: _store), ), ), // ... the label and the route, below. ]; ``` `ImportRef.app` names a file of the app by its path below `lib/`, without the package name of the app, which the module does not know. With get_it, the registration becomes this line of `registerDependencies()`: ```dart getIt.registerLazySingleton(() => di0.createCounterStore()); ``` A factory that needs other services lists them in `FactoryRef.deps`, and the container passes them as arguments, in that order. ## The route and the tab The feature gives the localization role the label of its tab, and declares its routes as data of the router role: ```dart title="lib/smf_counter.dart" localizationRole.data(const TextsData([_label])), routerRole.data( const RoutesData([ Route( '/', name: 'counter', screen: ScreenRef( 'CounterScreen', import: ImportRef.app('features/counter/counter_screen.dart'), ), destination: Destination( label: _label, icon: Fragment( 'Icons.add', imports: [ ImportRef('package:flutter/material.dart', show: ['Icons']), ], ), ), ), ]), ), ``` - The path `/` is relative to the feature, so the full path is `/counter`, and the name `counter` makes the full name `counter.counter` and the method `context.nav.counter.counter()`. - `destination` puts the route into the main navigation, as a tab with a label and an icon, when the app has a layout. The icon is a constant expression of type `IconData` with the imports it needs. - The label is a `LocalizedText`, a text of the module with its translations. The module gives the localization role the same text, so in an app with that role the tab reads it from the texts of the app, as `context.l10n.counterLabel`, and follows the language. In an app without the role, the tab shows the English text. - The route has no `startCandidate: true`, so the app does not start on it. Mark a route as a start candidate when the app can open on it. When several routes can, `smf create` asks which one. A module can also do without the localization role. Its label is then the English text alone, which every app shows: ```dart label: LocalizedText('label', en: 'Counter'), ``` `smf create` reports a translation of such a label, which no app would show. In an app with the localization role, it also reports a module that lists the role and does not give it the label. ## The BLoC variant The brick `counter_bloc` has the composition file and the screen for BLoC. The composition file creates the Cubit with the services it needs. It is the only file of the feature that calls `resolve`: ```dart title="bricks/counter_bloc/__brick__/lib/features/counter/counter_composition.dart" import 'package:flutter_bloc/flutter_bloc.dart'; import '../../core/di/service_locator.dart'; import 'counter_store.dart'; /// Creates the cubit of the counter screen with the services it needs. CounterCubit createCounterCubit() => CounterCubit(resolve()); /// The count of the counter screen. class CounterCubit extends Cubit { /// Creates the cubit that keeps its count in [_store]. CounterCubit(this._store) : super(_store.count); final CounterStore _store; /// Counts a tap. void increment() { _store.count++; emit(_store.count); } } ``` The screen provides the Cubit and talks only to it: ```dart title="bricks/counter_bloc/__brick__/lib/features/counter/counter_screen.dart" import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'counter_composition.dart'; /// Shows how many times its button was tapped. {{{smf_router__screen_annotations__counter__counter_screen}}} class CounterScreen extends StatelessWidget { /// Creates the screen. const CounterScreen({super.key}); @override Widget build(BuildContext context) => BlocProvider( create: (_) => createCounterCubit(), child: Scaffold( appBar: AppBar(title: const Text('Counter')), body: Center( child: BlocBuilder( builder: (context, count) => Text('$count'), ), ), floatingActionButton: Builder( builder: (context) => FloatingActionButton( onPressed: () => context.read().increment(), child: const Icon(Icons.add), ), ), ), ); } ``` The line `{{{smf_router__screen_annotations__counter__counter_screen}}}` is the tag of a socket of the router role, where a router that needs annotations on its screens, such as `@RoutePage()`, puts them. Every screen of a route has this tag on its own line right before its class, named after the feature and the class. With go_router the tag renders to nothing, and the line goes away. ## The Riverpod variant The brick `counter_riverpod` has the same two files for Riverpod. Its composition file bridges the container to a provider: ```dart title="bricks/counter_riverpod/__brick__/lib/features/counter/counter_composition.dart" import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/di/service_locator.dart'; import 'counter_store.dart'; /// The store of the counter, from the service locator of the app. final counterStoreProvider = Provider( (_) => resolve(), ); /// The count of the counter screen. final counterProvider = NotifierProvider(Counter.new); /// Counts the taps on the counter screen. class Counter extends Notifier { @override int build() => ref.read(counterStoreProvider).count; /// Counts a tap. void increment() { final store = ref.read(counterStoreProvider); store.count++; state = store.count; } } ``` ```dart title="bricks/counter_riverpod/__brick__/lib/features/counter/counter_screen.dart" import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'counter_composition.dart'; /// Shows how many times its button was tapped. {{{smf_router__screen_annotations__counter__counter_screen}}} class CounterScreen extends ConsumerWidget { /// Creates the screen. const CounterScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) => Scaffold( appBar: AppBar(title: const Text('Counter')), body: Center(child: Text('${ref.watch(counterProvider)}')), floatingActionButton: FloatingActionButton( onPressed: () => ref.read(counterProvider.notifier).increment(), child: const Icon(Icons.add), ), ); } ``` Both variants generate files at the same paths. That works because an app gets only one of them. ### A look that the variants share The two variants of the counter each have a whole screen, which is fine for a screen of a few lines. A feature with more to show keeps the look out of its variants, as the built-in [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) does with its four screens: | Brick | In | What it has | | --- | --- | --- | | `sign_in` | every app with the module | The look: the views, such as `SignInView`, their widgets, the values of the state and the functions of the guards. A view is a plain Flutter widget that gets the state of its call and callbacks, and imports nothing of a state manager. | | `sign_in_bloc` | the variant for `bloc` | The screens, a cubit for each, and the file that creates the cubits. | | `sign_in_riverpod` | the variant for `riverpod` | The same screens, and a provider for each with its `Notifier`. | The screens are at the same paths in both variants, such as `lib/features/sign_in/sign_in_screen.dart`, and each only gives its view the state. The descriptor names a function for each variant: ```dart variants: Variants( role: stateManagementRole, // Each variant imports the package of its provider, whose // constraint the provider owns. byProvider: {blocVariant: _bloc, riverpodVariant: _riverpod}, ), ``` A variant contributes like the module does, so it can bring more than a brick. The variant for `bloc` also puts a cubit around the root of the app, for the widgets that read who uses the app, and adds its part of the note for coding agents: ```dart static List _bloc(ModuleContext context) => [ BrickContribution(signInBlocBundle), const PubspecContribution.hosted('flutter_bloc', 'any'), // Who uses the app, for every widget of the app. const SocketContribution.wrap( AppEntryRole.rootWrappers, Fragment.wrap( 'BlocProvider(create: (_) => createSessionCubit(), child: ', ')', imports: [ ImportRef( 'package:flutter_bloc/flutter_bloc.dart', show: ['BlocProvider'], ), ImportRef.app( '$_folder/sign_in_composition.dart', show: ['createSessionCubit'], ), ], ), ), AppEntryRole.agentSections.entry( agentHeading, AgentNote(blocAgentNote), ), ]; ``` With the look in one place, a change of a field or of a text is one change. [Test a module](https://doc.saymyframe.com/extending/testing.md#the-state-of-a-variant) shows how the state of each variant is tested. ## Generate an app with it Add the module to a command of your own, as [Extending SMF](https://doc.saymyframe.com/extending.md#how-a-module-reaches-an-app) shows, bundle the bricks, and generate an app: ```bash dart run bin/my_smf.dart create counter_app --org com.example -m home,counter,bottom_tabs,bloc --no-input ``` ```text Adding flutter_core: the only provider of the app entry role, which every app needs. Adding go_router: the only provider of the router role, which home requires. Adding get_it: the only provider of the dependency injection role, which counter requires. ... Created counter_app in /Users/you/projects/counter_app. ``` The app has two tabs, Home and Counter, and `lib/features/counter/` holds the store, the composition file and the screen of the BLoC variant. With `-m home,counter,bottom_tabs,riverpod`, it gets the Riverpod variant instead. Without a state manager in `-m`, a run in a terminal asks for one, and a run without a terminal stops with a usage error. ## What the pipeline checks Before it generates an app, `smf create` checks, among other things, that: - every file of the module is in `lib/features/counter/`; - the module declares at least one route, with valid paths, names, screens and parameters, and every route can be reached; - in an app with the localization role, the label of its tab is a text that the module gave the role; - the template of every screen has the tag of its annotations; - the module has a variant for the provider in the app, and the packages of a state manager come only through its variant. The [contract harness](https://doc.saymyframe.com/extending/testing.md) runs these checks too, and checks the generated code: - the unnamed constructor of every screen is `const` and takes the parameters of its route; - only the composition file resolves services, and the module requires the DI role for it; - the function of every registration is a top-level function of its file that takes the services it lists; - the code navigates only to the module's own routes and to those of the modules it depends on. ## Routes with parameters and children A route can have children, shown on top of it, and parameters from its path and its query: ```dart Route( '/', name: 'list', screen: ScreenRef( 'CatalogScreen', import: ImportRef.app('features/catalog/catalog_screen.dart'), ), startCandidate: true, children: [ Route( 'item/:id', name: 'item', screen: ScreenRef( 'ItemScreen', import: ImportRef.app('features/catalog/item_screen.dart'), ), params: [ RouteParam.path('id', type: int), RouteParam.query('color', type: String, optional: true), ], ), ], ), ``` - A child's path has no leading `/` and is relative to its parent, so this one is `/catalog/item/:id`. - A parameter is a `String`, an `int`, a `double` or a `bool`. A path parameter is always required, and a query parameter is required unless it is `optional`. - The screen's unnamed constructor takes each parameter as a named parameter of the same name, nullable when optional. The template puts the tag of the parameter's annotations before it, on a line of its own: ```dart const ItemScreen({ {{{smf_router__param_annotations__catalog__item_screen__id}}} required this.id, {{{smf_router__param_annotations__catalog__item_screen__color}}} this.color, super.key, }); ``` - A parameter cannot take a name that the facade uses itself, which means `key`, `path`, `parent`, `chain` and `routeName`, or the name of a member of `Object` or of a `dart:core` type in lowercase, such as `int`. - A route with children takes no required query parameters, since navigating to a child rebuilds its parents from the path alone. - A router matches a location against the routes in the order a module declares them, each followed by its children, and the first match wins. Declare a route with a fixed segment, such as `/new`, before a route with a parameter in its place, such as `/:id`. In an app with a main navigation, the router matches the destinations and their children first. SMF reports a route that another route leaves unreachable. - A destination must be a top-level route without required parameters, since selecting it has no values to give. A start candidate takes no required parameters either. The screen of the list navigates to an item through the facade: ```dart TextButton( onPressed: () => context.nav.catalog.item(id: 5).push(), child: const Text('Item 5'), ) ``` A feature navigates only to its own routes, and to those of features it depends on with `dependsOn`, through `context.nav` or their location classes. ## A guard A feature can keep the user from the rest of the app until a condition holds, with a [guard](https://doc.saymyframe.com/concepts/guards.md) over the whole app, a gate. The built-in [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md) is such a feature. The smaller feature `terms` of this section shows its screen in place of every other screen until the user accepts the terms, and remembers the answer. It needs no DI container: its state is a notifier of its own, which a restorer fills from the preferences. It declares the guard next to its route: ```dart title="lib/smf_terms.dart" static const _status = ImportRef.app('features/terms/terms_status.dart'); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Terms that the user accepts before using the app', kind: ModuleKinds.feature, // The answer is saved in the preferences. requires: {preferencesRole}, ); @override List contribute(ModuleContext context) => [ BrickContribution(termsBundle), routerRole.data( const RoutesData( [ Route( '/', name: 'terms', screen: ScreenRef( 'TermsScreen', import: ImportRef.app('features/terms/terms_screen.dart'), ), ), ], guards: [ RouteGuard( name: 'accepted', allows: FunctionRef('termsAccepted', import: _status), redirectTo: 'terms', stage: GuardStage.welcome, ), ], ), ), const SocketContribution.item( PreferencesRole.restorers, Fragment('restoreTerms', imports: [_status]), ), ]; ``` - `allows` names a top-level function of a file of the app, without parameters, that returns a `ValueListenable`. The router role imports the file with a prefix of its own. - `redirectTo` names the target of the guard: a top-level route of the feature that needs no values and is not a destination of the main navigation. The target and the routes below it are the flow of the guard, and none of them is a start candidate. - `stage` is required: every guard is of the stage `GuardStage.welcome` or `GuardStage.identity`, which says when the app asks it among its gates. The terms need to know nothing of the user, so the guard has the stage `GuardStage.welcome`, and the app asks it before a guard of the stage `GuardStage.identity`, which asks who the user is. Among the guards of one stage, the order of the modules decides. See [the order of the guards](https://doc.saymyframe.com/concepts/guards.md#the-order-of-the-guards). - The guard leaves `resumes` at `true`. If it stops allowing while the app runs, the router brings the user back to where they were once it allows again. A guard whose next user should start anew, as after a sign-out, sets `resumes: false`. - The feature requires the preferences role, because it saves the answer there. With one module that provides the role, `smf create` adds it by itself. [Add a setting](https://doc.saymyframe.com/extending/settings.md) describes the restorer. The function of the guard and what it reads are in a file of the feature: ```dart title="bricks/terms/__brick__/lib/features/terms/terms_status.dart" import 'package:flutter/foundation.dart'; import '../../core/preferences/app_preferences.dart'; /// The key of the answer in the preferences of the app. const _key = 'terms.accepted'; final ValueNotifier _accepted = ValueNotifier(false); AppPreferences? _preferences; /// Whether the user has accepted the terms; the guard of the feature /// listens to it. ValueListenable termsAccepted() => _accepted; /// Accepts the terms and saves the answer. Future acceptTerms() async { _accepted.value = true; await _preferences?.setBool(_key, true); } /// Takes the answer that is saved, and keeps [preferences] for the answer /// to come; the app calls it before its first frame. void restoreTerms(AppPreferences preferences) { _preferences = preferences; _accepted.value = preferences.getBool(_key) ?? _accepted.value; } ``` The screen of the flow only changes what the guard reads: ```dart title="bricks/terms/__brick__/lib/features/terms/terms_screen.dart" import 'package:flutter/material.dart'; import 'terms_status.dart'; /// Shows the terms of the app until the user accepts them. {{{smf_router__screen_annotations__terms__terms_screen}}} class TermsScreen extends StatelessWidget { /// Creates the screen. const TermsScreen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text('Terms')), body: const Center( child: FilledButton(onPressed: acceptTerms, child: Text('Accept')), ), ); } ``` - The app calls `termsAccepted()` once, when its router first asks the guards, which is after `bootstrap()`. The restorer has run by then, so the value is known without waiting. - The value changes in the handler of a tap, outside the build of a frame, because the router navigates when it changes. - The screen navigates nowhere, and it does not close itself. Once the guard allows, the router leaves the flow for the location that the user asked for, or for the screen that the app starts on. - The route shows only while the guard does not allow. Once the terms are accepted, a navigation to `/terms`, such as a link, shows the screen that the app starts on. So no code navigates to the terms: a module that wants to show them again changes what the guard reads. - A feature whose guard needs a service keeps the function in its composition file, which may resolve services. In an app with `-m home,terms`, the app opens on the terms. `go()`, `push()` and `replace()` of the home screen show the terms too, and once the user taps Accept, the app shows the home screen. `smf create` refuses `--start /terms`, since the route is in the flow of the guard. Before it generates an app, `smf create` checks the name of each guard, its function and its target. The contract harness also checks that the function is a top-level function of its file that takes no arguments and returns a `ValueListenable`, and that the files of the module that provides the router ask the guards through the `GuardedNavigation` of the role. Whether a router does what the guards answer, only a running app shows; see [Guards of routes](https://doc.saymyframe.com/concepts/guards.md#rules). ## A route that asks for a condition A gate keeps the user from the whole app. A feature whose screen needs more than the rest of the app does, such as an account, asks for a [condition](https://doc.saymyframe.com/concepts/conditions.md) on the route of that screen instead. A role publishes the condition, and the feature lists that role. This sketch is a feature with a profile screen for users with an account, which asks for `AuthRole.account` of the auth role: ```dart title="lib/smf_profile.dart" @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'A profile screen for users with an account', kind: ModuleKinds.feature, // The screen reads the session of the app, and its route asks for a // condition of the role. requires: {authRole}, ); @override List contribute(ModuleContext context) => [ BrickContribution(profileBundle), routerRole.data( const RoutesData([ Route( '/', name: 'profile', screen: ScreenRef( 'ProfileScreen', import: ImportRef.app('features/profile/profile_screen.dart'), ), conditions: [AuthRole.account], ), ]), ), ]; ``` - The routes below a route that asks for a condition ask for it too. - The feature knows no module with a guard. In an app with a guard that stands for the condition, a request for the route opens the target of that guard over the page that the user is on, and the route shows once the condition holds. In an app without such a guard, the route shows like any other, and the auth role warns of it when the app is generated. - Every user gets to the main navigation, to the screen that the app starts on and to the flow of a guard. So a route that asks for a condition is no destination and below none, neither it nor a route below it is a start candidate, and it is outside the flows of the guards of the module. - When the condition stops holding, the router closes the page. A screen that ends the condition itself, as with a sign-out button, only ends it: it neither closes itself nor navigates. ### A guard that stands for a condition A module that requires or provides the role of a condition can stand for it, with a guard that names it in `condition`. The built-in [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) declares a gate and such a guard, with one target: ```dart guards: [ // After a sign-out, the next user starts on the screen that // the app starts on. RouteGuard( name: gate, allows: FunctionRef('signInAllowsApp', import: _guards), redirectTo: _route, stage: GuardStage.identity, resumes: false, ), RouteGuard( name: accountGuard, allows: FunctionRef('signInHasAccount', import: _guards), redirectTo: _route, stage: GuardStage.identity, resumes: false, condition: AuthRole.account, ), ], ``` The functions of the two guards are in a file of the feature, and each returns a value of the session of the app: ```dart title="lib/features/sign_in/sign_in_guards.dart" ValueListenable signInAllowsApp() => appSession.allowsApp; ``` ```dart title="lib/features/sign_in/sign_in_guards.dart" ValueListenable signInHasAccount() => appSession.hasAccount; ``` - The function says whether the condition holds, and the target is the route that the router opens while it does not. - The guard keeps the user only from the routes that ask for the condition, of whichever module. `sign_in` asks for it itself on the route of its account screen, and a feature of yours that asks for `AuthRole.account` gets the same guard. - A module declares at most one guard for a condition, and two modules with a guard for the same condition cannot be in one app. - The guard may show the target of a gate of its module, as this one does. The two then have one flow, which is over once both allow, and their functions read one notifier, here the session, so that the router never finds that one of them changed and the other did not yet. - Both guards ask who the user is, so they have the stage `GuardStage.identity`, and neither brings the user back. - Until the condition holds, the routes of the flow show like any route. A screen may open the target with `push()`, and a link to a route of the flow opens it over the screen that the app starts on. Inside the flow, its screens navigate with `push()` or `replace()`, which keep the request that opened the flow waiting. [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md) describes what the user sees, and [Define a role](https://doc.saymyframe.com/extending/new-role.md#conditions-for-routes) how a role publishes a condition. ## Texts, settings and notes The screens of this page show their texts as literals, to keep the examples short. A feature gives its texts to the localization role, so that they follow the language of the app; see [Texts](https://doc.saymyframe.com/extending/texts.md). A feature can also have a setting that the app remembers and shows on its settings screen, as [Add a setting](https://doc.saymyframe.com/extending/settings.md) shows, and a section in the guide for coding agents of the app, under a heading of its own; see [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). # Write an infrastructure module Source: https://doc.saymyframe.com/extending/infrastructure-module An infrastructure module sets up a library or a service without screens of its own. It declares no routes, keeps nothing in `lib/features/`, has no variants, and never takes services from the DI container itself. It puts its code and settings into the app entry, which every module may use, and into the sockets of the roles and modules it declares. The examples on this page come from two small modules that were generated into an app and checked with `flutter analyze`: `logging`, which sets up the [logging](https://pub.dev/packages/logging) package, and `git`, which makes the new app a Git repository. ## Start-up code `bootstrap()` runs the start-up code of all modules in four phases: early, platform, DI and late. A module adds a fragment of code to a phase, with the imports it needs: ```dart @override List contribute(ModuleContext context) => [ const PubspecContribution.hosted('logging', '^1.3.0'), const SocketContribution.code( AppEntryRole.bootstrapEarly, Fragment( r"Logger.root.onRecord.listen((record) => debugPrint('${record.level.name}: ${record.message}'));", imports: [ ImportRef('package:flutter/foundation.dart', show: ['debugPrint']), ImportRef('package:logging/logging.dart', show: ['Logger']), ], ), ), ]; ``` The pipeline adds the imports to `lib/bootstrap.dart`, merges them with those of other modules, and formats the file: ```dart title="lib/bootstrap.dart" import 'package:flutter/foundation.dart' show debugPrint; import 'package:logging/logging.dart' show Logger; Future bootstrap() async { Logger.root.onRecord.listen( (record) => debugPrint('${record.level.name}: ${record.message}'), ); } ``` Pick the phase by what the code needs: early for what must come first, platform for platform services such as `Firebase.initializeApp`, DI for the registration of the services, and late for code that needs the services. Code that must be declared at the top level of `lib/bootstrap.dart`, such as a handler of background messages, goes into `AppEntryRole.topLevel`. `lib/bootstrap.dart` imports neither `material` nor `cupertino`, so start-up code does not depend on a design library. ## Wrappers around the app `AppEntryRole.rootWrappers` wraps the root widget in `main()`, and `AppEntryRole.appBuilder` wraps the content of every route, in the `builder` of the root `MaterialApp`. A wrapper has an opening and a closing part. This is how `riverpod` adds its `ProviderScope`: ```dart const SocketContribution.wrap( AppEntryRole.rootWrappers, Fragment.wrap( 'ProviderScope(child: ', ')', imports: [ ImportRef( 'package:flutter_riverpod/flutter_riverpod.dart', show: ['ProviderScope'], ), ], ), ), ``` The first contribution is the outermost wrapper, as [the order of contributions](https://doc.saymyframe.com/concepts/sockets.md#order) decides. `AppEntryRole.appArgs` sets arguments of the root `MaterialApp`: `theme`, `darkTheme`, `themeMode` and `locale`, which take one value, `localizationsDelegates`, which takes the list items of every contributor, and `supportedLocales`, which takes the list items of one contributor. The root is created in the `build` of a widget below the root wrappers, so the expression of an argument may read `context`. An inherited widget among the root wrappers can give the root a value this way, and the root rebuilds when the widget notifies. The theme role gives the root its mode like this: ```dart const SocketContribution.wrap( AppEntryRole.rootWrappers, Fragment.wrap( 'AppThemeModeScope(notifier: appThemeMode, child: ', ')', imports: [_themeMode], ), ), // ... const SocketContribution.arg( AppEntryRole.appArgs, 'themeMode', Fragment('AppThemeModeScope.of(context)', imports: [_themeMode]), ), ``` That context is above the `MaterialApp`, so it has neither the theme nor the localizations of the app. Two rules of the app entry role make it the same with every module that provides the app entry. The tags of the root wrappers are in the body of `main()`, which runs the root widget inside them (`app_entry.root_wrappers_in_main`). And the provider creates the root `MaterialApp` in a method `build(BuildContext context)` of a class (`app_entry.root_in_build`). Two different values of an argument that takes one are an error that names both contributors, and `smf create` stops. The items of a second contributor of `supportedLocales` are a conflict too, also when they are the same items: every delegate of the root has to support each of its locales, so a locale that one contributor adds would break the delegates of another. `smf create` leaves the module of those items out with a warning, or stops with `--strict`. In an app with the theme role, the role sets `theme`, `darkTheme` and `themeMode`, and in an app with the localization role, the role sets `locale` and is the one contributor of `supportedLocales`. So a module leaves these arguments to the roles: a theme comes from a module that [provides the theme role](https://doc.saymyframe.com/extending/provide-theme.md), and a module gives its [texts](https://doc.saymyframe.com/extending/texts.md) to the localization role instead of bringing a delegate of its own. ## Dependencies `PubspecContribution` adds to the `pubspec.yaml` of the app: - `PubspecContribution.hosted('logging', '^1.3.0')` depends on a package of pub.dev, and `dev: true` makes it a dev dependency. - `PubspecContribution.sdk('flutter_localizations')` depends on a package of the Flutter SDK. - `PubspecContribution.flutter(assets: [...], fonts: [...], generate: true)` adds to the `flutter:` section. - `PubspecContribution.environment(sdk: ..., flutter: ...)` constrains the Dart and Flutter versions of the app. The pipeline intersects the constraints of a package that several modules add, and an empty intersection is an error. Declare `environment` only when your package needs a newer Dart or Flutter than the app has anyway. `flutter_core` sets Dart `^3.12.0` and Flutter `>=3.44.0`, and `smf create` checks the Flutter SDK against the merged constraints before it generates anything. A package that the provider of a role brings, such as `flutter_riverpod` of `riverpod`, is that provider's. Another module adds it only in its variant for the provider, with the constraint `any`, or when it depends on the provider. A package that no provider brings is shared, and every module that needs it adds it. A provider brings a package when it adds the package outside a variant with a constraint other than `any`. In a provider, add a shared package, such as `collection`, with `any`. See [The packages of a provider](https://doc.saymyframe.com/extending/role-provider.md#the-packages-of-a-provider). ## Native settings The app entry has sockets for the native files, so a module never edits them: ```dart AppEntryRole.iosDeploymentTarget.value('16.0'), AppEntryRole.androidManifestPermissions.key('android.permission.INTERNET'), AppEntryRole.androidManifestApplicationMeta.entry( 'com.example.sdk.CHANNEL', const AndroidMetaData.value('stable'), ), AppEntryRole.infoPlist.entry( 'UIBackgroundModes', const PlistStringArray(['fetch']), ), AppEntryRole.gradleSettingsPlugins.entry('io.github.ben-manes.versions', '0.64.0'), AppEntryRole.gradleAppPlugins.key('io.github.ben-manes.versions'), AppEntryRole.gradleAppDependencies.entry('androidx.annotation:annotation', '1.9.1'), AppEntryRole.androidCoreLibraryDesugaring.value('2.1.4'), ...AppEntryRole.paidTeamEntitlement( 'com.apple.developer.applesignin', const PlistStringArray(['Default']), ), const SocketContribution.code( AppEntryRole.iosAppDelegateLaunch, Fragment(' UNUserNotificationCenter.current().delegate = self'), ), const SocketContribution.code( AppEntryRole.androidManifestApplicationComponents, Fragment(''' '''), ), ``` - The minimum iOS version is the highest that any module asks for, and `flutter_core` gives 15.0. - Equal entries of several modules merge, and different values of one key are an error that names both modules. Arrays of strings in `Info.plist` and in the entitlements are united, and Gradle versions take the highest. - A key that the template of `flutter_core` has already, such as `CFBundleName`, cannot be added again. The Gradle sockets do not take the plugins that the template declares or applies, or the Kotlin plugin, which the Flutter Gradle plugin applies itself. - `AppEntryRole.mainActivityIntentFilters` takes `` elements of the main activity as XML, such as deep links. - `androidCoreLibraryDesugaring` takes the version of `desugar_jdk_libs` that a library of the app asks for, when the Android build of an app with that library fails without desugaring. The highest version wins, and the one value turns desugaring on in `compileOptions` and adds the library to `dependencies`. The build fails with either line alone. - `iosEntitlements` takes the entitlements of the iOS app into `ios/Runner/Runner.entitlements`. On a device, the capability of an entitlement may need a team of the paid Apple Developer Program. The simulator signs the app without one. An entitlement that only such a team signs, such as the one of Sign in with Apple above or `aps-environment` for push messages, goes in with `AppEntryRole.paidTeamEntitlement`, which also lists the step by hand in which the developer signs the app with that team; see [a step of a role](#a-step-of-a-role). - `iosAppDelegateLaunch` takes Swift statements, indented by four spaces, that run in `application(_:didFinishLaunchingWithOptions:)` before the launch goes to Flutter. They read the app delegate as `self`, and the parameters `application` and `launchOptions`, and take no imports: the file imports `Flutter` and `UIKit`, and `Flutter` brings `UserNotifications`. Flutter registers the plugins of the app once its scene connects, after this method, so the statements have no registry of plugins and no channel. - `androidManifestApplicationComponents` takes ``, `` and `` elements as XML, indented by eight spaces, for a component that the app has to declare itself, such as a receiver that the manifest of a library leaves out. Declare each component once. The contract harness reports two declarations of one `android:name`, also from two modules, and reads a name that starts with a dot, or has none, against the `namespace` of the app, as Android does. Android fails to build an app whose two declarations of a component differ. [`local_notifications`](https://doc.saymyframe.com/modules/local-notifications.md) uses three of these sockets: desugaring, the receivers of its package with the permission to start after a restart of the device, and the delegate of the notification center in the `AppDelegate`. ## README sections `AppEntryRole.readmeSections` adds a section to the `README.md` of the app, under a heading of its own, in Markdown: ```dart AppEntryRole.readmeSections.entry( 'Logging', 'The app logs with the [logging](https://pub.dev/packages/logging) ' 'package: create a `Logger` per class. `bootstrap()` prints the ' 'records at `Logger.root.level` and above, which is INFO by default.', ), ``` Use it for what someone who opens the app needs to know about your module, such as how to set up a service again. `firebase_core` explains there how to configure Firebase. The heading "Finish the setup" is taken: a step that only the developer can do is a [step by hand](#steps-by-hand), which the app entry role lists in that section. ## Notes for coding agents Every app has a guide for the coding agents that work on it, `AGENTS.md`. `AppEntryRole.agentSections` is the socket of its sections, and a module adds a note to it under a heading, in Markdown: ```dart static const _agentNote = ''' - For the feedback of a tap, call `tapFeedback()` of `lib/core/haptics/haptics.dart`. Do not call `HapticFeedback` yourself: the user can turn the feedback off, and only `tapFeedback()` asks. - Change the choice only with `chooseHaptics()`, which also saves it when the app has preferences. '''; ``` ```dart AppEntryRole.agentSections.entry('Haptics', AgentNote(_agentNote)), ``` A note tells what the code of the app does not show: a rule that holds across files, an order, what not to do and what to do instead, a placeholder, a step that needs a person. What the code shows needs no note, and setup that needs a person or an account goes into a README section. The built-in modules keep the texts of their notes in `lib/src/agents.dart` of their package. ### The heading of a note - The template of a role writes the note of the role under the description of the role, such as `routerRole.description`: where the files of the role are, how code uses it, and what code must not do. Such a note holds whichever module provides the role, so it never names a provider or its package. Only a template contributes it, with `AgentNote.ofRole`, and the socket refuses one from a module; see [Define a role](https://doc.saymyframe.com/extending/new-role.md#the-template). - A module that provides a role adds its note under the same heading, with `AgentNote`, and the section has the note of the role first. A provider that wraps a package opens its note with a line that names the package, such as "With `go_router`:". Then it tells where it writes what the role describes, and how to add one more by hand. A provider that wraps a tool of Flutter names the tool instead, as `gen_l10n` does with "With `gen-l10n` of Flutter:". - A module without a role uses a heading of its own, as `haptics` does above. The notes under one heading are united into one section: the notes of roles first, then the others in the order of the ids of their contributors, each once. The section of the app entry comes first in the guide, and the others follow in the order of their headings. So replacing the provider of a role changes only its own note. ### The rules of a note - It is true in every app that has it. A note about a file that only some apps have goes into a contribution of its own, with the role of that file in its `when`. `firebase_analytics` adds its note on screen views with `when: {routerRole}`, since only an app with a router has the listener that logs them. - What depends on the data of a role comes from the render hook of the role or of the module that provides it, as a fragment for the socket. `go_router` tells this way where the destinations of the main navigation go, only in an app that has one, and the router role adds what it tells of the guards only in an app with guards. - It stays in its section. It has no line that starts a title or another section, with `# ` or `## ` or with a line of `=` or `-` under a line of text, and it closes its fenced code blocks. A heading is one line. - It names a file or a directory of the app in backticks, by its path from the root of the app, such as `lib/core/haptics/haptics.dart`. A file that a later step writes, such as one of a tool that runs after generation, is named as a pattern, with `<…>` or `*`, or left to the README. ### What is checked In every app that the contract harness renders, the rule `app_entry.agent_guide_paths` reads the paths that the guide names in backticks below a top-level directory of a Flutter project, such as `lib/`, `test/` or `android/`, and its paths to Dart files. It reports one that the app does not have. It does not read the name of a file at the root of the app, such as `pubspec.yaml`. The socket puts its sections in an order of its own, so a `when` of a note adds nothing to [the order of contributions](https://doc.saymyframe.com/concepts/sockets.md#order), and no note can make an app impossible to generate. A test can also hold the notes of the roles against the modules that provide the roles, with `roleNoteProblems`: see [The notes of roles](https://doc.saymyframe.com/extending/testing.md#the-notes-of-roles). Nothing checks what a sentence of a note says about the code, which only a test of that code can pin. A test of the module can pin the names: it reads the note from the app, and checks that each name of code that the note gives is one that a file of the app declares or uses. [Test a module](https://doc.saymyframe.com/extending/testing.md#checking-one-app) shows how a test reads the notes. ## Building on another module When your module builds on another module itself, and not on a role, depend on it with the id constant of its package: ```dart dependsOn: {FirebaseCoreModule.id}, ``` The other module comes into the app with yours, and the constant makes its package a dependency of yours. Your module may then put code into the sockets of that module. A module can declare sockets of its own, such as `SocketRef.module(id, 'setup', CodeSocket())`, which only the modules that depend on it directly may fill. Prefer a role whenever one describes what you need, so that the user can pick its provider. ## Code generation A module that needs `build_runner` contributes a `CodegenRequest`, and the builders it needs as dev dependencies: ```dart const PubspecContribution.hosted('json_annotation', '^4.9.0'), const PubspecContribution.hosted('json_serializable', '^6.9.0', dev: true), const CodegenRequest(description: 'JSON code of FixtureModel'), ``` However many modules ask, the pipeline runs `dart run build_runner build --force-jit` once, after `flutter pub get`, and adds `build_runner` to the dev dependencies itself. A library that the builders generate and that code of the app imports, such as `lib/core/di/dependencies.config.dart`, goes into `outputs`, so that the pipeline and the harness know about it. Part files, such as `.g.dart`, need no mention. ## Checking the machine A module that needs a tool on the machine contributes a `Preflight` with checks. A check has an id, unique in its module, and a description, which the report of `--explain` and the warnings show: ```dart /// Checks that Git is installed. final class GitCheck extends PreflightCheck { const GitCheck(); @override String get id => 'git'; @override String get description => 'Git'; @override Future check(SmfEnvironment environment) async { if (await environment.findExecutable('git') != null) { return const PreflightPassed(); } return const PreflightMissing( instructions: 'Install Git from https://git-scm.com/downloads.', ); } } ``` - `check` only reads the machine, because `--explain` runs it too. It does not install anything, log in, ask the user or change files other than its temporary files. It returns `PreflightPassed`, `PreflightMissing` with instructions, or `PreflightFailed` when the check itself could not run. - When the check finds something other than what it looks for, such as an older version of the tool, it says what it found in `PreflightMissing(found: ...)`, as a clause such as `'git 2.20.0 is installed'`. The pipeline then says that the tool is needed, but git 2.20.0 is installed, rather than that the tool is missing. - A missing tool that the check can install is `PreflightMissing(installable: true)`. In a terminal, unless the run skips external setup, the pipeline asks the user, showing what the check found and its instructions, calls `install`, and runs `check` again. `install` returns a `ToolInstall` with the directories of what it installed, which the pipeline adds to the `PATH` of later checks and commands. - A failed check is a warning by default. Set `required` only when the app cannot work without the tool. A failed required check leaves the module out of the app, or stops the run with `--strict` or when no app can be made without the module. - Never show the output of a command that can hold a secret, such as a token of a login. The login check of `firebase_core` reports only the error of the command. - Run commands with the `processRunner` of the environment, and find them with `findExecutable`, which also looks in the directories of tools installed during the run. The names `flutter` and `dart` stand for the Flutter SDK that the pipeline checked. On Windows, a batch file such as `dart.bat` cannot take arguments with `^`, `<`, `>`, `%`, `&`, `|` or `"`, because `cmd.exe` would read them as its own. - A command that may wait a long time, such as one that asks a service over the network, gets a `timeout` in `processRunner.run`. The runner then stops the command along with the processes it started, and the result says so with `timedOut`. The login check of `firebase_core` gives `firebase projects:list` 40 seconds. - The pipeline shows the progress "Checking the machine" while the checks run, and another progress for a check that runs again after an installation, so a check does not need to show one itself. - Read an environment variable of `smf` with `environmentVariable`, such as `SSH_CONNECTION`, which tells the login check of `firebase_core` that the session is over SSH. On Windows, the name may have any case. See the checks of [`firebase_core`](https://doc.saymyframe.com/guides/firebase.md#before-generation-the-machine) for checks that install tools and log in. ### The order of the checks The pipeline checks the machine for a module after the modules it depends on, directly or not. It does not matter where the user named those modules, or whether the pipeline added them. The checks of the other modules keep the order of the modules of the app, and those of the templates of the roles come last. After an installation, the pipeline runs again only the checks after it that have not passed. So a check of your module may need a tool that a check of a module it depends on installs. It cannot count on a check of any other module, whose place depends on the order in which the user named the modules. ### A check from the module you depend on A step names only checks of its own module in `needs`. So when your module needs more of a tool than the module it depends on checks, that module can offer you a check to put into your own `Preflight`. `smf_firebase_core` does: for a module that depends on it and runs a command that only newer versions of the Firebase CLI have, it exports `FirebaseCliVersionCheck`. ```dart const version = FirebaseCliVersionCheck(minimum: '15.34.0'); const Preflight([version]), PostGenStep(tool, arguments, skippable: true, needs: [version.id]), ``` `smf_firebase_core` knows how to ask the Firebase CLI, and your module knows the number: the lowest version that has its command, as three numbers. `firebase_auth` asks for 15.34.0 this way, the first Firebase CLI that enables sign-in methods without adding a web app to a project that has the apps of `flutterfire configure`. - The check reads `firebase --version` as the check of the Firebase CLI of `firebase_core` runs it. It accepts that version and any later one, of a later major version too. A pre-release of the lowest version comes before it. - For an older Firebase CLI, it tells which command it found, in which version, and how to update it. It installs nothing: other projects of the user run the Firebase CLI too, so the user updates it. - On a machine without the Firebase CLI, it reports it missing, and the check of `firebase_core` offers the installation. That check runs first, so after the installation the check of the version runs again and reads the version that was installed. ## Commands after generation A `PostGenStep` runs a command in the new app, after `flutter pub get` and code generation: ```dart const Preflight([GitCheck()]), PostGenStep( ToolRef('git'), ['init', '--quiet'], description: 'Creating a Git repository', skippable: true, needs: ['git'], ), ``` ```text βœ“ Getting the packages of the app (1.0s) βœ“ Creating a Git repository (0.0s) βœ“ Cleaning up the imports (1.9s) ``` | Option | Meaning | | --- | --- | | `description` | What the step does, for its progress and for the instructions when it is left for later. | | `interactive` | The command talks to the user, so it runs with the terminal attached, and only in a run that can ask. | | `external` | The command needs something outside the app, such as an account, so a run with `--skip-external-setup` leaves it for later. | | `skippable` | The app is complete without it, so the pipeline may leave it for later, printing its command, instead of failing. In a run that can ask, the pipeline asks before it runs the step, so the user can leave it for later too. | | `needs` | Ids of checks of the module's `Preflight`. When one has not passed, the step does not run, is not asked about, and is left for later with the check as the reason. | | `id` | The id by which other steps continue this one, a `PostGenStepId` of the module and a name. See [Continuing a step](#continuing-a-step). | | `followUpOf` | The id of the step that this one continues. | | `notice` | What the user has to know before the step runs and its description does not tell, such as a side effect of the tool that it runs. The step then runs only once the user agreed to it. See [A step with a notice](#a-step-with-a-notice). | A step that is not skippable fails the generation when it fails or cannot run, unless it continues a step that is not done. `ToolRef` names the executable, arguments that always come first, and environment variables. `firebase_core`, for example, runs a script of the app as `ToolRef('dart')` with the arguments `[configureScript, AppEntryRole.defaultFlavor.name]`. When a run ends, it reports the steps that are not done. A step that could not run or failed is a warning. A step that was left for later is in a list after the line that the app is created, with its description, the reason, its command and its notice. [The machine and external setup](https://doc.saymyframe.com/guides/smf-create.md#the-machine-and-external-setup) has an example of each. The step runs in the temporary directory of the app, which then moves to its place, so it must not write the absolute path of its working directory into the app. The pipeline writes the files where Flutter records such paths again in the app's directory. ### Continuing a step A step can continue another step, such as with a tool that needs what that step set up. The module of the step to continue gives it an `id` and publishes the id as a constant of its module class, next to its `ModuleId`. `firebase_core` does this for the step that configures Firebase, which has `id: configureStep`: ```dart final class FirebaseCoreModule extends SmfModule { static const id = ModuleId('firebase_core'); static const configureStep = PostGenStepId(id, 'configure'); // ... } ``` `firebase_auth` depends on `firebase_core`, and continues that step with the script that enables the sign-in methods in the project that the user chose: ```dart PostGenStep( const ToolRef('dart'), const [enableSignInScript], followUpOf: FirebaseCoreModule.configureStep, description: 'Enabling the sign-in methods of the app in its Firebase project', notice: enableSignInNotice, skippable: true, external: true, needs: [firebaseCliWithSignIn.id], ), ``` A step that continues another is part of it: - It runs right after the step it continues, once that step succeeded, rather than in its own place among the steps. The user is not asked about it, unless it has a [notice](#a-step-with-a-notice). - When the step it continues does not run or fails, it does not run either. It is left for later after that step, with that step as the reason, whether it is skippable or not. - It applies to the app whenever the step it continues does, so it has no `when` of its own. Otherwise it runs by its own options, such as `needs` and `skippable`. - Another step can continue it in turn, and then runs right after it. A module continues its own steps and the steps of the modules it depends on directly. So the module of a step never learns which modules continue it. The pipeline reports as problems of the module a step whose `id` names another module, two steps with one id, a step that continues a step it may not continue or a step that the app does not have, a step that continues another and has a `when`, and steps that continue each other in a cycle. A step runs once, when the app is generated. For what has to follow every later run of a tool too, the app needs a place of its own, which a module gives it as a script of the app. `tool/configure_firebase.dart` of `firebase_core` is such a script: it runs each Dart file of `tool/firebase_configured/`, in the order of their names, after each flavor that it configures. So `firebase_crashlytics`, which has to fix a file that flutterfire writes again in each of its runs, puts a brick file there and has no step, and `firebase_core` knows nothing of it. The file has only the libraries of Dart, since `dart` cannot load a file that imports Flutter. ### A step with a notice Some steps do more than their description says, such as a tool that also changes something in an account of the user. A step tells the user of that in its `notice`, and then runs only once the user agreed to it. `firebase_auth` has such a step. It continues the step of `firebase_core` that configures Firebase, and enables the sign-in methods of the app in the Firebase project with a script of the app. For a way to sign in of Google, the script also changes the project and files of the app, which the description of the step does not tell: ```dart const enableSignInNotice = 'If the app signs in with Google, it also gives ' "Google the app's name and the Firebase CLI account's email for its " 'consent screen, registers the SHA-1 and SHA-256 of this ' "machine's Android debug key (creating the key if there is none, as the " "first debug build would), downloads the app's Firebase files again and " 'writes the iOS URL scheme into ios/Runner/Info.plist.'; ``` A step cannot tell what the roles of the app chose, since the pipeline needs the steps before any role chooses, and a step that continues another takes no condition at all. So the step and its notice are the same in every app, and the notice says "if the app signs in with Google", which is true of every app. ```dart final PostGenStep enableSignIn = PostGenStep( const ToolRef('dart'), const [enableSignInScript], followUpOf: FirebaseCoreModule.configureStep, description: 'Enabling the sign-in methods of the app in its Firebase ' 'project', notice: enableSignInNotice, skippable: true, external: true, needs: [firebaseCliWithSignIn.id], ); ``` The step needs `firebaseCliWithSignIn`, the module's `FirebaseCliVersionCheck(minimum: '15.34.0')`, and the question of a run in a terminal is one line: ```text Enabling the sign-in methods of the app in its Firebase project (dart tool/enable_firebase_sign_in.dart), for firebase_auth. If the app signs in with Google, it also gives Google the app's name and the Firebase CLI account's email for its consent screen, registers the SHA-1 and SHA-256 of this machine's Android debug key (creating the key if there is none, as the first debug build would), downloads the app's Firebase files again and writes the iOS URL scheme into ios/Runner/Info.plist. Run it now? ``` What a run does with such a step: | The run | What happens to a step with a notice | | --- | --- | | It can ask, and the step can run. | It asks about the step, with the notice in the question: ` (), for . Run it now?`. Enter answers yes, as for every step. For a step that continues another, the question comes once that step succeeded. | | It can ask, and the step cannot run. | It does not ask, and leaves the step for later like any other. That is a step that is `external` in a run that skips external setup, one that `needs` a check which has not passed, one whose tool is missing, and one that continues a step that is not done. | | It cannot ask. | It leaves the step for later, although it runs a step without a notice unasked. | When the user declines a step, the steps that continue it are left for later after it, without a question. The notice follows the command of a step that is left for later, whatever the reason, and `--explain` shows it under the command. So write it as a sentence or two on one line that read on their own in each of these places, without a reference to the question, such as "answer no". The pipeline reports a notice that is blank or has a line break. The user may decline the step, so a step with a notice is `skippable`, and the pipeline reports one that is not. ## Steps by hand Some of the setup of an app is out of reach of any command, such as uploading a key to the Firebase console or signing the iOS app with a paid Apple Developer team. A module tells of such a step with a `ManualStep`: an id and a short title, and nothing else. How to do the step, click by click, is in its guide, on a page that the id names. `firebase_messaging` publishes its step as a constant of its module class, next to its `ModuleId`, and lists it among its contributions, since every app of the module needs it: ```dart final class FirebaseMessagingModule extends SmfModule { static const id = ModuleId('firebase_messaging'); static const apnsKeyStep = ManualStep( ManualStepId(id, 'apns_key'), 'Give Firebase your Apple push key (APNs key)', ); // ... } ``` An app with steps by hand gets them in four places: - At the end of `smf create`, after the steps that are left for later, the line `Finish the setup by hand in 2 steps:`, or `in one step:`, with the link to their guide on a line of its own. The run asks nothing about them, so a run without a terminal prints the same line. See [steps by hand](https://doc.saymyframe.com/guides/smf-create.md#steps-by-hand). - In `smf create --explain`, the section `By hand`: the link, then each step as `: (<contributors>)`. See [Explain](https://doc.saymyframe.com/guides/smf-create.md#explain). - In the README of the app, the section "Finish the setup" (`AppEntryRole.setupHeading`), which comes before every other section. It lists the titles, numbered, with the link to their guide. Only the template of the app entry role writes it: `AppEntryRole.readmeSections` refuses that heading from anyone else. - In `AGENTS.md`, a second note of the app entry role, which tells coding agents that only the developer of the app does these steps. An app without steps has none of these. ### The id and the title `ManualStepId(module, name)` names a step of a module. The name is lower snake_case, such as `apns_key`, and no other step of the owner has it. `ManualStepId.wire` is the id as the link carries it, `<owner>.<name>`, such as `firebase_messaging.apns_key`. It names the step for good: a link that a run once printed still leads to the guide of the step, so never rename a step. The title tells what the developer does, and the guide tells how. It is one line of at most 80 characters (`ManualStep.maxTitleLength`) with no spaces around it, starts with an upper-case letter or with `iOS`, and has neither a final period nor a backslash. When only an app with a role needs the step, and the module only uses that role, the step lists the role in its `when`, as other contributions do. The pipeline reports, as a problem of the contributor: - a name that is not lower snake_case; - an id of another module (a variant counts as its module), and an id of a module from the template of a role; - an id of a role that the contributor does not provide, require or use, and that is not open to all modules; - a title against its rules; - a second title under one id, at the contributor that comes later in the order of the steps. So in lenient mode, `smf create` leaves out the module at fault. ### A step of a role Contributors that do not know each other may need the same step. A role publishes such a step as a constant of its class, with `ManualStepId.role(role, name)`. Each contributor lists it, and the app has it once. A step with an id of a role applies only in an app with that role. The registry refuses a role with the id of a module, so steps of two owners never share an id in the link. The app entry role publishes one such step, `AppEntryRole.iosAppIdStep` (`app_entry.ios_app_id`), in which the developer signs the iOS app in Xcode once with a team of the paid Apple Developer Program. That registers the App ID of the app with the capabilities of its entitlements. An app needs the step when its entitlements have one that only such a team signs, one of `AppEntryRole.paidTeamEntitlements`: `aps-environment`, `com.apple.developer.applesignin` and `com.apple.developer.associated-domains`. `AppEntryRole.paidTeamEntitlement(key, value, when:)` gives the entry of `AppEntryRole.iosEntitlements` and the step together, under the same roles: ```dart ...AppEntryRole.paidTeamEntitlement( 'com.apple.developer.applesignin', const PlistStringArray(['Default']), ), ``` It throws an `ArgumentError` for any other key: a free team signs any other entitlement, which goes into `iosEntitlements` alone and needs no step. The structural rule `app_entry.ios_app_id_step` reports an app whose `ios/Runner/Runner.entitlements` has a key of `paidTeamEntitlements` and whose steps lack this one. In SMF, `apple_sign_in` and the template of the push role add their entitlements this way. ### Steps that depend on the data of a role A step that depends on what the modules give a role comes from the `manualSteps` hook of the template of the role or of a provider of it. `firebase_auth` lists the steps of Apple only in an app with a way to sign in of Apple, and the SHA of a release only in one with a way to sign in that needs the certificate of the Android app, such as Google: ```dart @override List<ManualStep> manualSteps(RoleHookInput<AuthData> input) { final methods = firebaseMethodsOf(authRole.methodsIn(input)); return [ if (methods.containsKey('apple.com')) ...const [ FirebaseAuthModule.appleProviderStep, FirebaseAuthModule.appleRevocationStep, ], if (methods.values .any((needs) => needs.contains(SignInNeed.androidCertificate))) FirebaseAuthModule.googleReleaseShaStep, ]; } ``` - The hook runs once, in the validation, before the roles choose, so `input.choice` is `null`. No step depends on a choice, and `--explain`, which stops before the choices, has the steps too. - A step of the hook has no `when`, since the hook asks for the presence of the roles itself with `input.has(role)`. The pipeline reports a step with `when` and a hook that throws. - The hook of a provider gives an id of its own module, or of a role that its module provides, requires or uses, or that is open to all modules. The hook of a template gives an id of its role, of a role that the role requires or uses, or of a role that is open to all modules. - A step that every app with the role or with the provider has is a contribution of the template or of the module instead. ### The order The pipeline plans the steps once, in the validation. It orders them by the edges between their contributors, as it orders the steps after generation. A cycle of those edges is no problem here, since the order only tells the developer which step to do first, and the contributors on the cycle are ordered by name. Each id comes once, in the place of its first step, with every contributor that lists it. The steps of roles come first, because a role publishes a step that its contributors need before their own. The link, the README and `--explain` give the steps in this order. The render hooks and the structural rules of a role that is open to all modules, which only the app entry is, get the planned steps and the link as `RoleHookInput.manualSetup`. Every other role gets `ManualSetup.none`, since the ids name modules that the role does not know of. ### The link and the guides The pipeline knows no site. The front end names the page that guides the developer: a `SetupLink`, a function from the ids of the steps, in their order, to a `Uri`, which `runSmf` and `CreatePipeline` take as `setupLink`. Without one, the run prints no line about the steps, and `--explain` and the README list them without a link. `smf create` names [the setup page](https://doc.saymyframe.com/setup.md) of this site, with the ids after `?steps=`, separated by commas, as in `https://doc.saymyframe.com/setup?steps=app_entry.ios_app_id,firebase_messaging.apns_key`. A [command of your own](https://doc.saymyframe.com/extending/publishing.md#a-command-of-your-own) built on `runCli` names the same page, which shows a step that it has no guide for by its id and points to the README of the app for its title. This site keeps a guide for every step of the modules that `smf create` offers. `packages/smf_flutter_cli/setup_steps.json` is their catalog: each id once, with its title, its owner and the modules that bring it into an app. After a change of the steps of such a module, run `dart run tool/setup_steps.dart` in `packages/smf_flutter_cli`, which writes the file. `test/setup_steps_test.dart` fails until the file is up to date. A new step also needs its guide on this site, whose build compares its copy of the catalog with the guides. An id that no app has any more moves to `retired` in the catalog and keeps its guide, since a link that a run once printed names it. ### In tests `ContractResult.manualSteps` has the planned steps of the app of a case, each a `PlannedManualStep` with its `step` and its `contributors`, and `ContractResult.setupLink` their link. The harness plans them before the roles choose, so a harness that does not render has them too, and `result.app!.manualSteps` has the same steps. The harness takes a `setupLink`, and has none by default. The tests of `apple_sign_in` check the step of its entitlement this way: ```dart final planned = result.manualSteps.single; expect(planned.step.id, AppEntryRole.iosAppIdStep.id); expect(planned.step.title, AppEntryRole.iosAppIdStep.title); ``` ## Services An infrastructure module that creates services registers them as data of the DI role, and gets the services they need through the factory, as in `FactoryRef('createApiClient', import: ..., deps: [ServiceRef(TypeRef('HttpClient', import: ...))])`. The container calls the factory with those services, and the module never calls `resolve`. See [registering services](https://doc.saymyframe.com/extending/role-provider.md#registering-services). A module that implements analytics, crash reporting, events, preferences, notifications, push messages or sign-in provides the role instead; see [Provide a role](https://doc.saymyframe.com/extending/role-provider.md). A module that keeps a setting of its own in the preferences gives the preferences role a restorer; see [Add a setting](https://doc.saymyframe.com/extending/settings.md). # Add a setting Source: https://doc.saymyframe.com/extending/settings The module `haptics` gives the code of the app a light vibration for the feedback of a tap, which the user can turn off. It is an infrastructure module with one setting, and it works with three roles that it only uses: - the preferences role remembers the setting between the launches of the app; - the settings screen role shows a row that changes it; - the localization role has the label of the row in the languages of the app. The module names none of the modules that provide these roles, and it works in an app without any of them. The code below was generated into apps with and without each role and checked with `flutter analyze`. [How settings work](https://doc.saymyframe.com/concepts/settings.md) explains the roles. ## The descriptor ```dart title="lib/smf_haptics.dart" import 'package:smf_contracts/smf_contracts.dart'; import 'package:smf_haptics/bundles/haptics_bundle.dart'; import 'package:smf_haptics/bundles/haptics_setting_bundle.dart'; /// Haptic feedback that the user can turn off: a setting that the app /// remembers when it has preferences, with a row on the settings screen /// when it has one. final class HapticsModule extends SmfModule { /// Creates the module. const HapticsModule(); /// The id of the module. static const id = ModuleId('haptics'); static const _file = ImportRef.app('core/haptics/haptics.dart'); // ... the texts and the note, below. @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Haptic feedback that the user can turn off', kind: ModuleKinds.infrastructure, uses: {preferencesRole, settingsScreenRole, localizationRole}, ); // ... contribute(), below. } ``` The module lists the three roles in `uses`, so each is optional. A module that cannot work without a role lists it in `requires` instead, and an app with the module then always has a module that provides the role. ## The state The brick `haptics` holds the state of the setting and the functions that read and change it. Every app with the module gets it: ```dart title="bricks/haptics/__brick__/lib/core/haptics/haptics.dart" import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; {{#has_preferences}} import '../preferences/app_preferences.dart'; {{/has_preferences}} /// Whether the app answers a tap with a vibration: on until the user turns /// it off. final ValueNotifier<bool> hapticsEnabled = ValueNotifier(true); {{#has_preferences}} /// The key of the choice in the preferences of the app. const _key = 'haptics.enabled'; /// The preferences that remember the choice, once the app opened them. AppPreferences? _preferences; {{/has_preferences}} /// Vibrates lightly, unless the user turned the haptic feedback off. void tapFeedback() { if (hapticsEnabled.value) HapticFeedback.selectionClick(); } /// Turns the haptic feedback on or off{{#has_preferences}}, and saves the choice{{/has_preferences}}. Future<void> chooseHaptics({required bool enabled}) async { hapticsEnabled.value = enabled;{{#has_preferences}} await _preferences?.setBool(_key, enabled);{{/has_preferences}} } {{#has_preferences}} /// Takes the choice that is saved, or keeps the current one when nothing is /// saved, and keeps [preferences] for the choices to come; the app calls it /// before its first frame. void restoreHaptics(AppPreferences preferences) { _preferences = preferences; hapticsEnabled.value = preferences.getBool(_key) ?? hapticsEnabled.value; } {{/has_preferences}} ``` - The state is plain Flutter, a `ValueNotifier`, so the module needs no state manager and has no variants. - Widgets listen to `hapticsEnabled` and change the setting with `chooseHaptics()`. They never touch the preferences. - Everything that refers to `AppPreferences`, a symbol of a role that the module only uses, is inside `{{#has_preferences}}`. An app without preferences gets the file without it, and the setting then lasts as long as the app runs. - The key is `<module id>.<setting>`, here `haptics.enabled`. The ids of modules differ, so the keys of modules that keep to this form do not collide. ## Remember the setting A module does not ask for the preferences. It gives the preferences role a restorer, a function that takes the `AppPreferences`, and the app calls it when it starts: ```dart title="lib/smf_haptics.dart" @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(hapticsBundle), const SocketContribution.item( PreferencesRole.restorers, Fragment('restoreHaptics', imports: [_file]), ), // ... the row and the note, below. ]; ``` The contribution needs no `when`, because code for a socket of a role applies only in an app with the role. In such an app, the function is in the list of restorers of the role: ```dart title="lib/core/preferences/app_preferences.dart" final List<void Function(AppPreferences preferences)> _restorers = [ restoreHaptics, ]; ``` A restorer follows [the rules of the preferences role](https://doc.saymyframe.com/concepts/settings.md#preferences). It is synchronous, keeps the current value when nothing is saved under its key, as `?? hapticsEnabled.value` does, keeps the preferences for the writes of its module, and may run more than once. The module never calls `createAppPreferences()` or `initPreferences()`. Nothing in the preferences is encrypted, so a module keeps no token, password or key there: a secret belongs in the secure storage of the platform. ## A row on the settings screen The row is a widget in a brick of its own, `haptics_setting`: ```dart title="bricks/haptics_setting/__brick__/lib/core/haptics/haptics_setting.dart" import 'package:flutter/material.dart'; import 'haptics.dart'; /// The row of the settings screen that turns the haptic feedback on or off. class HapticsSetting extends StatelessWidget { /// Creates the row. const HapticsSetting({super.key}); @override Widget build(BuildContext context) => ValueListenableBuilder<bool>( valueListenable: hapticsEnabled, builder: (context, enabled, _) => SwitchListTile( secondary: const Icon(Icons.vibration), title: Text({{{text_title}}}), value: enabled, onChanged: (value) => chooseHaptics(enabled: value), ), ); } ``` The module contributes the brick only in an app with a settings screen, and gives the settings screen role an entry that names the widget: ```dart title="lib/smf_haptics.dart" BrickContribution( hapticsSettingBundle, vars: localizationRole.varsOf(id, _texts), when: const {settingsScreenRole}, ), localizationRole.data(_texts, when: const {settingsScreenRole}), settingsScreenRole.data( const SettingsEntry( widget: TypeRef( 'HapticsSetting', import: ImportRef.app('core/haptics/haptics_setting.dart'), ), ), ), ``` - The widget is a class in a file that the module generates, with a `const` unnamed constructor that requires no arguments. The screen knows nothing else of it, so the widget reads and changes its setting itself. - The screen sets the width of the row and puts no limit on its height, so the widget may be a `ListTile` or a column of them. - The brick has `when: {settingsScreenRole}`, so an app without a settings screen does not get the file. The entry itself needs no `when`, since data for a role applies only when the role is present. - The import of the entry spells the path of the file as the brick does, and the brick has the file at a path without variables. The module that provides the settings screen shows the row. With [`settings`](https://doc.saymyframe.com/modules/settings.md), the screen imports the file with a prefix of its own and puts the row into its group, a card below the title of the screen: ```dart title="lib/features/settings/settings_screen.dart" import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:my_app/core/haptics/haptics_setting.dart' as entry0; // ... const _Group(children: [entry0.HapticsSetting()]), ``` Without a module with a setting, that screen has a note for the developer of the app in place of the group, so the row of `haptics` is what gives this app its group. The rows of the modules come in the order the modules were chosen, and after them the rows that the templates of roles contribute. ## The label and the note The label of the row is a text of the module, which it gives the localization role with a translation: ```dart title="lib/smf_haptics.dart" static const _texts = TextsData([ LocalizedText( 'title', en: 'Haptic feedback', translations: {'uk': 'Π’Ρ–Π±Ρ€ΠΎΠ²Ρ–Π΄Π³ΡƒΠΊ'}, ), ]); ``` The template reads it as `{{{text_title}}}`, a variable of `localizationRole.varsOf`. It renders as `context.l10n.hapticsTitle` in an app with the localization role, and as `'Haptic feedback'` in one without it. The module gives the role the texts only in an app with a settings screen, where the row is. [Texts](https://doc.saymyframe.com/extending/texts.md) describes texts in full. The module also tells coding agents what its code does not show, in a section of the guide of the app: ```dart title="lib/smf_haptics.dart" static const _agentNote = ''' - For the feedback of a tap, call `tapFeedback()` of `lib/core/haptics/haptics.dart`. Do not call `HapticFeedback` yourself: the user can turn the feedback off, and only `tapFeedback()` asks. - Change the choice only with `chooseHaptics()`, which also saves it when the app has preferences. '''; // ... and in contribute(): AppEntryRole.agentSections.entry('Haptics', AgentNote(_agentNote)), ``` See [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). ## Generate an app with it Add the module to a command of your own, as [Extending SMF](https://doc.saymyframe.com/extending.md#how-a-module-reaches-an-app) shows, bundle the bricks, and generate an app: ```bash dart run bin/my_smf.dart create my_app --org com.example -m home,settings,bottom_tabs,haptics,shared_preferences --no-input ``` The app has two tabs, Home and Settings. The settings screen has the row Haptic feedback, and the app remembers the choice. With `gen_l10n` in `-m` too, the label of the row follows the language of the app, in English and in Ukrainian. With `-m haptics` alone, the app gets `lib/core/haptics/haptics.dart` without the code for the preferences, and no row. ## What the pipeline checks Before it generates an app, `smf create` checks the rules of each role that the app has. Among other things: - in an app with a settings screen, the bricks of the module generate the file of the widget of each of its entries, and only in such an app when the module only uses the role; - in an app with the localization role, the texts of the module have valid names, an English text and translations by the code of their language, and each variable that reads a text reads one that the app has. The [contract harness](https://doc.saymyframe.com/extending/testing.md) runs these checks too, in an app for each subset of the roles that the module uses and the registry of the tests has a provider of, and checks the generated code: - the widget of every entry is a class in a file of its contributor, with a `const` unnamed constructor that requires no arguments; - the module that provides the settings screen creates the widget of every entry; - no file of the module calls `createAppPreferences()` or `initPreferences()`; - in the app without a role, no file of the module refers to a symbol of that role. ## Test the module The contract harness builds an app of the module for each subset of the roles that it uses, and checks every one: ```dart title="test/haptics_module_test.dart" import 'package:smf_flutter_core/smf_flutter_core.dart'; import 'package:smf_gen_l10n/smf_gen_l10n.dart'; import 'package:smf_go_router/smf_go_router.dart'; import 'package:smf_haptics/smf_haptics.dart'; import 'package:smf_pipeline/smf_pipeline.dart'; import 'package:smf_pipeline/testing.dart'; import 'package:smf_settings/smf_settings.dart'; import 'package:smf_shared_preferences/smf_shared_preferences.dart'; import 'package:test/test.dart'; void main() { test('every app of the module follows the rules of its roles', () async { final harness = ContractHarness( ModuleRegistry(const [ FlutterCoreModule(), // The settings screen is a feature, which requires a router. GoRouterModule(), SettingsModule(), SharedPreferencesModule(), GenL10nModule(), HapticsModule(), ]), ); final results = await harness.checkAll(); for (final result in results) { expect(result.errors, isEmpty, reason: '${result.contractCase}'); } expect(await harness.uncheckedProviders(), isEmpty); }); } ``` The registry has a module for each role that `haptics` uses, since the harness builds an app with a role only when the registry has a provider of it. It also has what those modules need themselves: `SettingsModule` is a feature, which requires a router, and `GenL10nModule` requires the preferences. Without `GoRouterModule`, every case with the settings screen would report that no module provides the router role. [Test a module](https://doc.saymyframe.com/extending/testing.md) describes the harness, and how a test reads what the module gave a role. ## A setting of a role The template of a role contributes a setting the same way, when its role requires or uses the preferences role and the settings screen role. The theme role keeps the theme mode like this: its template gives the preferences role the restorer of the mode and the settings screen role an entry for it. The widget of such an entry is in a brick of the template, not of the module that provides the role. See [Define a role](https://doc.saymyframe.com/extending/new-role.md#the-template). # Add a step to the onboarding Source: https://doc.saymyframe.com/extending/onboarding-steps A module can ask a new user for something on a page of the onboarding, such as a permission that it needs. It gives the onboarding screen role a step: an icon, a title, a text, the label of a button and the function that the button calls. The module that provides the role, such as [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md), draws the step in the look of its own pages. The two know the role and not each other. The notifications role adds such a step, which asks for the permission to show notifications. This page shows a step of a module `photos` of your own, which asks for access to the photos of the device. ## The step The module lists the onboarding screen role in `uses`, since it works without an onboarding too, and gives the role an `OnboardingStep`: ```dart title="lib/smf_photos.dart" static const _step = ImportRef.app('core/photos/photos_step.dart'); static const _title = LocalizedText('stepTitle', en: 'Your photos'); static const _text = LocalizedText( 'stepText', en: 'Choose photos from the device for your albums.', ); static const _action = LocalizedText('stepAction', en: 'Allow access'); static const _later = LocalizedText('stepLater', en: 'Not now'); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Photos of the device', kind: ModuleKinds.infrastructure, uses: {onboardingScreenRole, localizationRole}, ); @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(photosBundle), onboardingScreenRole.data( const OnboardingStep( name: 'access', stage: OnboardingStage.permission, icon: Fragment( 'Icons.photo_library_outlined', imports: [ImportRef('package:flutter/material.dart')], ), title: _title, text: _text, action: _action, later: _later, run: FunctionRef('askPhotoAccess', import: _step), showIf: FunctionRef('photoAccessUnasked', import: _step), ), ), localizationRole.data( const TextsData([_title, _text, _action, _later]), when: {onboardingScreenRole}, ), ]; ``` | Field | What it is | | --- | --- | | `name` | The name of the step among those of the module, in lowerCamelCase. Its full name, the id of the module and the name, is `photos.access`, as the data of the role and the tests name it. | | `stage` | When the onboarding shows the step among the steps of the app: `permission`, for a permission that the app asks for, and then `offer`, for an offer of the app, such as the paywall that sells premium access. The list of stages is closed, so a module cannot add one, and a step of another kind takes the stage closest to what it does. | | `icon` | An expression of the type `IconData` with the imports it needs, which the onboarding shows in the cell of the page. | | `title`, `text` | The title of the page and the text below it. | | `action`, `run` | The label of the button and the function that it calls. | | `later` | The label of a second button, which goes on without calling `run`, or `null` for a step without it. | | `showIf` | The function that says whether the onboarding shows the step, or `null` for a step that it always shows. | The data needs no `when`: data of a role applies only in an app with the role. The texts of the step are texts of the module. A module that lists the localization role gives that role each of them too, with `when: {onboardingScreenRole}`, and the app shows them in its language. A module without the localization role shows them in English and gives them no translations. ## The functions `run` and `showIf` are top-level functions of a file that a brick of the module generates. `run` takes the `BuildContext` of the onboarding screen and returns a `Future`. `showIf` takes no arguments, returns a `bool` at once and changes nothing. ```dart title="bricks/photos/__brick__/lib/core/photos/photos_step.dart" /// Whether the onboarding shows the step: while the app has not asked for /// access to the photos. bool photoAccessUnasked() => !photoAccess.asked; /// Asks for access to the photos of the device: the action of the step. Future<void> askPhotoAccess(BuildContext _) => photoAccess.request(); ``` A `run` that needs no context takes it all the same, as `BuildContext _`. A `run` that shows a screen of its own over the onboarding, as the step of [`paywall`](https://doc.saymyframe.com/modules/paywall.md) shows the paywall, pushes it with `Navigator.of(context, rootNavigator: true)` and completes once that screen is closed: a guard of the routes may keep the router from showing a route while the onboarding is on, and the onboarding goes on when the future completes. The router does not close such a screen, so `run` closes it itself when it is done. The brick needs no condition either, since the code that needs the photos calls the same function. The onboarding asks `showIf` once when it opens, so the function reads what the app knows already, such as what the start-up restored from the preferences. Skipping the onboarding skips its steps, and a user may tap the second button. So do not rely on the step alone: the screen that needs the access asks for it too, with the same function. ## What the role generates Whichever module provides the onboarding, the template of the role writes the steps of the app into `lib/core/onboarding/onboarding_steps.dart`, as the constant list `appOnboardingSteps`. The labels are top-level functions that read the texts of the module in the language of the app, and the file of the functions of each module is imported with a prefix of its own, so two modules may have functions of one name: ```dart title="lib/core/onboarding/onboarding_steps.dart" const List<OnboardingStep> appOnboardingSteps = [ OnboardingStep( icon: Icons.photo_library_outlined, title: _photosAccessTitle, text: _photosAccessText, action: _photosAccessAction, run: step0.askPhotoAccess, later: _photosAccessLater, showIf: step0.photoAccessUnasked, ), ]; String _photosAccessTitle(BuildContext context) => context.l10n.photosStepTitle; ``` The steps come in the order of their stages. Steps of one stage come in the order of their modules, and then those of the templates of roles. The steps of one module keep its order. ## What the onboarding does with a step The onboarding screen of every provider of the role reads `appOnboardingSteps` and keeps to this: - It asks each step for its `showIf` each time it shows, and leaves out a step that returns `false`. A step that it shows stays while the user is on it. - It shows each step that it kept on a page of its own, in the order of the list, with no other page between two steps: the icon, the title as a header for a screen reader, the text and the buttons. It calls the functions of the labels when it builds, so they follow the language of the app. - A tap on the button of the action calls `run` once, with the `BuildContext` of the screen, and the buttons of the step take no tap until the future completes. Then the onboarding goes on to the next page, also when the future fails, and the error reaches the handlers of the errors of the app. The second button goes on without calling `run`. - A swipe past a step, or Skip, calls no `run`. When the app shows the onboarding is up to the provider. `onboarding` shows it on the first launch, with a guard of the routes; see [steps of other modules](https://doc.saymyframe.com/modules/onboarding.md#steps-of-other-modules). A provider names its route with an `OnboardingScreenRoute`, so that code which knows only the role finds the screen. ## What is checked The module rule `onboarding_screen.steps` reports a step whose name is not a lowerCamelCase identifier or is the name of another step of the module, a step without an icon, texts with translations in a module that does not list the localization role, and a function in a file that the bricks of the module do not generate. In every app that the contract harness renders, `onboarding_screen.step_functions` checks that the functions are top-level functions of the files of the module, that `run` takes the `BuildContext` of the onboarding screen and returns a `Future`, and that `showIf` takes no arguments and returns a `bool`. `onboarding_screen.steps_shown` checks that a file of the provider reads `appOnboardingSteps`. ## Test the module The contract harness builds an app with a role only when the registry of the tests has a provider of it. So the registry of a module with a step has a provider of the onboarding screen role, such as `OnboardingModule` of `smf_onboarding` as a dev dependency, and what that provider needs: the role requires a router, and `onboarding` requires the preferences. A module that lists the localization role adds a provider of it too: ```dart title="test/photos_module_test.dart" final harness = ContractHarness( ModuleRegistry(const [ FlutterCoreModule(), // The onboarding screen role requires a router. GoRouterModule(), // The onboarding remembers in the preferences that it is finished. SharedPreferencesModule(), OnboardingModule(), GenL10nModule(), PhotosModule(), ]), ); final results = await harness.checkAll(); for (final result in results) { expect(result.errors, isEmpty, reason: '${result.contractCase}'); } expect(await harness.uncheckedProviders(), isEmpty); ``` The harness then builds the apps of the module with the onboarding and without it, and with the localization and without it, and runs the rules above in each. A test of the module reads its steps from the role, not from the files of a provider: ```dart final input = onboardingScreenRole.hookInput(result.hook!); final steps = onboardingScreenRole.stepsIn(input); expect(steps.map((step) => step.fullName), contains('photos.access')); ``` What the onboarding shows of a step, and what its buttons do, only a running app shows. SMF's CI checks it with a fixture provider and fixture steps; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). # Texts Source: https://doc.saymyframe.com/extending/texts A text that a user sees belongs to the module that shows it. The module gives its texts to the localization role, in English and in the other languages that it has them in, and its templates read them through the role. A module that only uses the role works in an app without it too, where each text reads in English. [Texts and languages](https://doc.saymyframe.com/concepts/localization.md) explains the role. The examples come from the module `haptics` of [Add a setting](https://doc.saymyframe.com/extending/settings.md), whose row on the settings screen has a label. ## Declare the texts ```dart static const _texts = TextsData([ LocalizedText( 'title', en: 'Haptic feedback', translations: {'uk': 'Π’Ρ–Π±Ρ€ΠΎΠ²Ρ–Π΄Π³ΡƒΠΊ'}, ), ]); ``` | Part | Rules | | --- | --- | | The name | A lowerCamelCase identifier, such as `title` or `openDetails`, with a name of its own among the texts of the module. Names that differ only in case count as one. | | `en` | The text in English, which is never empty. The app shows it in every language that the text has no translation into, and in an app without the role. | | `translations` | The text in other languages, by the code of each: two or three lowercase letters without a region, such as `uk`. English is not among them, and no translation is empty. Leave a language out to show the text in English there. | A text takes no parameters and has no plural forms, so no text has a `{` or a `}`. An app can be only in a language in which Flutter has the texts of its own widgets, one of `LocalizationRole.supportedLanguages`. A translation into any other language is left out of the app. Unless `--locales` chose the languages, `smf create` warns of it, with the module and the text. ## Give the texts to the role, and read them The module lists the role in `uses`, gives it the texts as data, and gives its brick a variable for each text: ```dart uses: {preferencesRole, settingsScreenRole, localizationRole}, ``` ```dart BrickContribution( hapticsSettingBundle, vars: localizationRole.varsOf(id, _texts), when: const {settingsScreenRole}, ), localizationRole.data(_texts, when: const {settingsScreenRole}), ``` The `when` of both contributions is about the row of `haptics`, as [the section below](#texts-that-only-some-apps-need) explains. A module whose texts every app needs leaves it out. `varsOf` makes the variable `text_<name>` for each text, with the name in snake_case: `title` is `text_title`, and `openDetails` is `text_open_details`. A template reads it where a widget shows the text: ```dart title: Text({{{text_title}}}), ``` The variable renders by the app: | App | `Text({{{text_title}}})` renders as | | --- | --- | | with the localization role | `Text(context.l10n.hapticsTitle)`, and the file gets the import of `lib/core/l10n/l10n.dart` | | without it | `Text('Haptic feedback')` | The getter of a text starts with the id of the module in lowerCamelCase, followed by the name of the text with a capital: `title` of `haptics` is `hapticsTitle`, and `ok` of `firebase_core` would be `firebaseCoreOk`. A template reads a text variable by these rules: - in three braces, and outside every mustache section; - where a `BuildContext context` below the root `MaterialApp` is in scope, such as in the `build` of a widget; - not inside a `const` expression, since `context.l10n.hapticsTitle` is not a constant. A widget that is `const` only in an app without the role gets the keyword from an inverted section next to the variable, as in `{{^has_localization}}const {{/has_localization}}Text({{{text_title}}})`. Give the role the same texts as `varsOf` gets. In an app with the role, `smf create` reports a variable whose text no module gave the role, since the module that provides the role would have no getter for it. ## Texts that only some apps need The label of `haptics` is needed only in an app with a settings screen, where its row is. So the brick that reads it and the data of the texts both name that role in `when`, as the contributions above do. The settings screen role asks for the first: a module that only uses it generates the file of its row only in an app with a settings screen. The second keeps a text that no screen shows out of the app. A text variable cannot be read inside `{{#has_<role>}}`. A text that needs another role goes into a brick of its own, contributed with `when` of that role, as here. See [variables that depend on a role](https://doc.saymyframe.com/extending/templates.md#variables-that-depend-on-a-role). ## Whose texts code may read The code of a module reads only its own texts and those of the modules in its `dependsOn`, each through its getter. In an app with the role, the contract harness checks it for every text that code reads from `context.l10n` or from a variable called `l10n`. A module brings no delegate for texts of its own and adds no language to the root of the app. Every delegate of the root has to support each language of the app, and only the role knows them. ## Texts in the data of another role The data that a module gives another role can have a text that a user sees too. The label of a destination is one: a feature gives it to the router role in its routes, as `Destination(label: ...)`, and the layout role shows it. Such a text is a `LocalizedText` of the module like any other: - A module that lists the localization role gives that role the same text among its `TextsData`. The app then reads the text from its texts, in its language. In an app with the role, `smf create` reports a text of such data that the module did not give the role, or gave it otherwise. - A module that does not list the role gives the text in English alone, which every app shows. `smf create` reports a translation there, which no app would show. - Two such texts of one name that differ are an error, since the app reads a text of a module by its name and would show the same text for both. [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md#the-route-and-the-tab) has the label of a tab as the example. A role whose data has such texts implements `DataWithTexts` in the data, and its template reads each text with `expressionOf`, as the next section shows. ## Texts of the template of a role The template of a role gives its texts the same way, when its role lists the localization role in `uses` or `requires`. A render hook takes no variable of `varsOf`, so the template reads each text with `expressionOf`. The theme role does this for the texts of its row on the settings screen: ```dart @override RoleOutput render(RoleHookInput<NoDsl> input) => RoleOutput( vars: { 'mode_key': SmfNames.dartString(ThemeRole.modeKey), for (final MapEntry(key: variable, value: text) in _texts.entries) variable: localizationRole.expressionOf( input, const RoleTemplateOrigin(themeRole), text, ), }, ); ``` The getter of such a text starts with the id of the role: the text `title` of the theme role is `context.l10n.themeTitle`. The template reads its own texts, and the texts in the data that the modules give its role, each as a text of the module that gave it. ## In tests The contract harness checks the rules of the texts in the apps with the localization role. So the registry of the tests of a module with texts has a module that provides the role, such as `GenL10nModule` of `smf_gen_l10n`, and one that provides the preferences, which the role requires. The harness then builds the apps of the module with the role and without it. A test of a module reads what the module gave the role from the role, not from the files of the module that provides it: ```dart final input = localizationRole.hookInput(result.hook!); final texts = localizationRole.textsIn(input); final languages = localizationRole.localesIn(input); ``` `textsIn` returns the texts of the whole app, each with its owner. An app of the tests that no route starts has the texts of `flutter_core` too, the two of its fallback start screen in English and in Ukrainian, so its languages include Ukrainian whatever the module under test gives. A test takes the texts of its own module by their owner: ```dart final own = [ for (final text in texts) if (text.owner == const ModuleOrigin(HapticsModule.id)) text.getter, ]; ``` See [Test a module](https://doc.saymyframe.com/extending/testing.md#checking-one-app). # Provide a role Source: https://doc.saymyframe.com/extending/role-provider A module provides a role with a provider object in its descriptor. What the provider has to do depends on the role. Some roles need only a package, and others give the provider their data to render. The examples come from the built-in modules. ## A plain provider A module whose files and dependencies alone implement the role uses `RoleProvider.plain`. This is `bloc`, which adds its package and its note for coding agents: ```dart final class BlocModule extends SmfModule { /// Creates the module. const BlocModule(); /// The id of the module, by which other modules key their variants for /// BLoC. static const id = ModuleId('bloc'); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'BLoC with flutter_bloc', kind: ModuleKinds.infrastructure, providers: [RoleProvider.plain(stateManagementRole)], ); @override List<Contribution> contribute(ModuleContext context) => [ const PubspecContribution.hosted('flutter_bloc', '^9.1.1'), AppEntryRole.agentSections.entry( stateManagementRole.description, AgentNote(agentNote), ), ]; } ``` A provider of the state management role brings its package with a constraint of its own, which makes the package belong to the provider. Features add it only in their variant for this provider, with the constraint `any`. The provider's id is the key of those variants, so choose it with care. `riverpod` also adds its `ProviderScope` to the root wrappers. ### The packages of a provider A provider brings a package when it adds the package outside a variant, with a constraint other than `any`. The package then belongs to the provider, unless a module that the provider depends on brings it too. In an app with the provider, every other module that adds the package, with any constraint, must take it from the provider: in its variant for the provider, with `any`, or through a dependency on the provider. `smf create` reports any other module that adds it. By default it leaves that module out of the app, and with `--strict` it stops. So bring only the packages that implement your role. A package that many modules add, such as `collection`, stays shared as long as no provider brings it, so add such a package with `any`. If your provider brought it with a constraint of its own, every module that adds it without a variant for your provider or a dependency on it would be reported in the apps that have your provider. Two providers that bring the same package, neither depending on the other, are both reported in an app that has both. A module that imports the package of a provider adds the package too, even when it depends on the provider, so that the check above sees it. The contract harness reports code that imports or exports such a package without adding it. Your provider may import, for a fragment or in a file that its render hook generates, the package that a module which gives your role data adds, since the code of the data may need it. ## A service: events, analytics, crash reporting The events, analytics and crash reporting roles generate the interface of their service and everything around it: the function that returns the app's service, a service that forwards every call to all providers when the role takes several, the registration in the DI container, and start-up code. A provider only implements the interface and contributes its implementation as data of the role. This is `event_bus`: ```dart final class EventBusModule extends SmfModule { /// Creates the module. const EventBusModule(); /// The id of the module. static const id = ModuleId('event_bus'); static const _file = ImportRef.app( 'core/events/event_bus_communication_service.dart', ); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Events between parts of the app with event_bus', kind: ModuleKinds.infrastructure, providers: [RoleProvider.plain(eventsRole)], ); @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(eventBusBundle), const PubspecContribution.hosted('event_bus', '^2.0.1'), eventsRole.data( const RoleImplementation( type: TypeRef('EventBusCommunicationService', import: _file), create: FactoryRef( 'createEventBusCommunicationService', import: _file, ), ), ), AppEntryRole.agentSections.entry( eventsRole.description, AgentNote(agentNote), ), ]; } ``` Its brick implements the interface of the role, which it imports from the role's file: ```dart title="lib/core/events/event_bus_communication_service.dart" import 'package:event_bus/event_bus.dart'; import 'communication_service.dart'; CommunicationService createEventBusCommunicationService() => EventBusCommunicationService(EventBus()); final class EventBusCommunicationService implements CommunicationService { EventBusCommunicationService(this._eventBus); final EventBus _eventBus; @override void fire(AppEvent event) => _eventBus.fire(event); @override Stream<T> on<T extends AppEvent>() => _eventBus.on<T>(); } ``` - A provider contributes exactly one implementation, and only a provider of the role contributes one. No module puts code into the socket of the implementations, which the template fills. - The function that creates the implementation takes no arguments, so the service works without a DI container. The role registers the service in the container when there is one. - An implementation that starts asynchronously uses `RoleImplementation.async(type: ..., init: ...)`, whose function returns a `Future`. The role awaits it in the platform phase of `bootstrap()`. - A crash reporter only reports. The template of the crash reporting role installs the handlers of errors, which present the errors as Flutter does, so the reporter prints nothing. A provider whose SDK installs handlers of its own turns them off. ### What the services promise An events service delivers each event once to every listener of its type that is listening when the event is fired, in the order the events were fired. Whether it also delivers the event to the listeners of a type that the event extends or implements, such as `on<AppEvent>()`, is up to the provider, and `event_bus` does. A listener of any other type gets neither the event nor an error. The stream of `on<T>()` has only the events fired after it is listened to, so an event fired after `on<T>()` returned the stream, but before `listen`, is not in it. A cancelled subscription gets no more events. An app can have several providers of analytics and of crash reporting, which know nothing of each other, so the service of the role calls each of them on its own. A provider that throws, or whose future fails, keeps no other provider from the call, and its failure reaches neither the code that called nor the handlers of the errors of the app. In debug mode the service prints it, so a provider that does not work shows in the console. Each analytics provider gets its own copy of the map of parameters, and one that changes the map changes nothing for the caller or for the other providers. A provider whose factory throws, or whose asynchronous start fails, is left out, and the app starts and works with the others. SMF's CI checks these promises in running apps. The test of the events role runs in every app with the role in [the matrix of the built-in modules](https://doc.saymyframe.com/contributing.md#generated-apps). The tests of analytics and crash reporting run in an app with the Firebase providers of both roles next to fixture providers of the same roles. ### Preferences The preferences role is a service role too: its template generates the `AppPreferences` interface, and a provider contributes one implementation of it. This is what `shared_preferences` contributes: ```dart @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(sharedPreferencesBundle), const PubspecContribution.hosted('shared_preferences', '^2.5.5'), preferencesRole.data( const RoleImplementation.async( type: TypeRef('SharedAppPreferences', import: _file), init: FactoryRef('openSharedAppPreferences', import: _file), ), ), AppEntryRole.agentSections.entry( preferencesRole.description, AgentNote(agentNote), ), ]; ``` The role does more with the implementation than create it. `initPreferences()` of the role opens the preferences with the function of the implementation and then gives them to the [restorers](https://doc.saymyframe.com/concepts/settings.md#preferences) of the modules, and `bootstrap()` awaits it in its platform phase, whether the implementation is created asynchronously or not. A test runs `initPreferences()` again to see what the next launch reads, so the function of the implementation reads what is saved each time it is called. Every implementation keeps what the interface promises: - A read is synchronous, from memory, and never throws. It returns `null` when the key has no value of the type it asks for. Whether a number saved as an `int` is read as a `double`, or the other way round, is up to the provider. - Once the future of a write completes, reads return what it saved, in this run of the app and after its next launch. - A key has one value. A write replaces what the key had, a value of another type too, and `remove` makes the reads of the key return `null` again. - The preferences keep a copy of a list they are given, and a read returns a copy of it. A package may promise less than the role, and the implementation then makes up the difference. The reads of the shared_preferences package cast the value and throw on another type, and the package keeps the list that it is given, so `SharedAppPreferences` checks the type of each value itself and hands the package a copy of each list. SMF's CI checks these promises in running apps with every module that provides the role, and on devices, where the platform side of the provider is the real one; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ### Notifications and push messages The notifications role and the push role take one implementation each, of `NotificationsService` and of `PushService`. As with the auth role, the code of the app never calls the service of a provider. It uses `appNotifications` and `appPush`, which the templates generate and which do what is the same with every provider: the permission and what the app remembers of it, the owners of notifications, the address of the device. Neither role registers anything in a DI container, and `bootstrap()` awaits `initNotifications()` and then `initPush()` in its platform phase. This is what `local_notifications` contributes for the role, next to its native settings: ```dart notificationsRole.data( const RoleImplementation.async( type: TypeRef('LocalNotificationsService', import: _file), init: FactoryRef('openLocalNotifications', import: _file), ), ), ``` [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md#for-a-provider) sums up what a provider of each keeps to, and the doc comments of the two interfaces in the app hold the full contracts. ### Purchases The purchases role takes one implementation, of `PurchasesService`. The code of the app never calls the service of a provider: it uses `appPurchases`, which the template generates and which does what is the same with every provider, such as whose the purchases are and what the app does while they are not set up. The role registers nothing in a DI container, and `bootstrap()` awaits `initPurchases()` in its platform phase. This is what `revenuecat` contributes for the role: ```dart purchasesRole.data( const RoleImplementation( type: TypeRef('RevenueCatPurchasesService', import: _file), create: FactoryRef('createRevenueCatPurchasesService', import: _file), ), ), ``` [Purchases](https://doc.saymyframe.com/guides/purchases.md#for-a-provider) sums up what a provider keeps to, and the doc comments of the interface in the app hold the full contract. ### Values in .env A provider of the role of the values in `.env` generates `AppEnv` in `lib/core/env/app_env.dart`, with a getter for each key of `envRole.keysIn(input)`, from its render hook. A provider that needs arguments on the commands of the `flutter` tool that build, run or test the app gives them to the role, as `dart_define` does: ```dart envRole.data(const EnvToolArguments(['--dart-define-from-file=.env'])), ``` [Values in .env](https://doc.saymyframe.com/guides/env.md#for-a-provider) tells what `AppEnv` keeps to. ### REST API The REST role takes one implementation, of `RestTransport` in `lib/core/rest/rest_transport.dart`: one exchange on the wire, and nothing else. The template generates `appRest` over it, and everything that the client guarantees is in that code: the join of a path and the address, the failures, the repeats, the redirects, the timeout, the token of the user. So a second provider keeps every guarantee by construction. The role registers nothing in a DI container and adds nothing to `bootstrap()`, so the template refuses an implementation that is created asynchronously. This is what `dio` contributes for the role: ```dart restRole.data( const RoleImplementation( type: TypeRef('DioRestTransport', import: _file), create: FactoryRef('createDioRestTransport', import: _file), ), ), ``` The doc of `RestTransport` holds the contract, which only a running app shows: - `send()` makes one attempt, and a provider repeats nothing. - A provider follows no redirect: a 3xx is a reply. `appRest` follows them, since it knows which header may go where. - Any status is a reply, and it keeps the headers of the reply, with their names in lower case. A provider whose stack decoded a body leaves out `content-encoding` and its `content-length`, which no longer tell of the bytes. A body in a coding that the stack did not decode keeps them. - A failure to connect, a TLS handshake or a certificate that fails, and a connection that breaks are `RestConnectionFailed`. On `dart:io` those are `SocketException`, `HttpException` and `TlsException`. Any other error is a bug of the provider, which reaches the caller as the reason `unknown`. - When `RestExchange.stop` completes, a provider closes the connection at once. It needs no timeout of its own, since `appRest` stops every exchange. On `dart:io` the call ends at once, but a TLS handshake on its way cannot be ended, not even by `close(force: true)`: its socket closes when the handshake ends or the server ends it. A provider that shares one `HttpClient` cannot end a TCP connect on its way either: the system ends it. - On `dart:io`, a provider that keeps an `HttpClient` makes a new one when `HttpOverrides` change, as they do when a test starts or closes a `RestTestServer`. - It sends the address as it is, with those headers and that body. Its stack may add the headers of the transport itself, such as `host`, `user-agent` and `accept-encoding`. It adds no credential or cookie, and keeps none between two calls. - It writes no header, no query and no body to a log or a hint. - Its function takes no arguments, never throws and does not wait, and the implementation works from the first call. The tests of the role run in every app with a provider, so a new provider gets them; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). ### Sign-in The auth role takes one implementation too: its template generates the `AuthService` interface, and a provider contributes its implementation of it. Unlike the other services, the code of the app never calls this one. It signs in through `appSession`, which the template generates and which does what is the same with every provider. The role registers nothing in a DI container. [Provide sign-in](https://doc.saymyframe.com/extending/provide-auth.md) describes what the service keeps to. ## Following the router A provider can work with another role through the roles its role uses. The analytics role uses the router, so `firebase_analytics` gives the router a listener of the screen, only when the app has a router: ```dart const SocketContribution.item( RouterRole.screenListeners, Fragment( 'logFirebaseScreenView', imports: [ ImportRef.app( 'core/analytics/firebase_analytics_service.dart', show: ['logFirebaseScreenView'], ), ], ), when: {routerRole}, ), ``` The listener is a function of the module's own file, which exists only in an app with a router: ```dart {{#has_router}} void logFirebaseScreenView(String? route, String location) { final name = route ?? (Uri.parse(location).path == '/' ? '/' : null); if (name == null) return; FirebaseAnalytics.instance.logScreenView(screenName: name).catchError( (Object error) => debugPrint('Firebase Analytics: $error'), test: (error) => error is PlatformException, ); }{{/has_router}} ``` A listener has the type `void Function(String? route, String location)`. It follows the screen the user sees, which is the page of the router on top of the app. Pages that the app shows past the router, such as with `Navigator.push`, and dialogs are not pages of the router. Every provider of the router promises to call each listener once for each change of that screen: - when the app shows its first screen; - when another page comes on top: a page that a navigation shows, a page that shows again as the pages above it close, or the page of the tab, or other branch of the main navigation, that the user selects; - when the page on top shows another location, such as the same route with other values of its parameters. The router does not call a listener for the pages that a navigation puts below the one on top, such as the parents of a route that `go()` shows, and never twice in a row for the same page at the same location. So a listener hears of the back button of the system only when the button closes a page of the router: when it closes a dialog, the page below stays the screen the user sees. The listener gets the full name of the route, such as `home.home`, and the location with its query and fragment. For a screen that is not a route of a module, the route is `null` and the location is still that of the screen: `/` for the fallback start screen, or the location that the router could not show for its error screen. The router may call a listener while the app builds, so a listener only takes note of the screen. It does not navigate, rebuild widgets or throw. The router calls each listener on its own, since the modules of the listeners know nothing of each other. A listener that throws anyway keeps no other listener from hearing of the screen, and what it throws reaches neither the router nor the handlers of the errors of the app. In debug mode the router prints it, so a listener that fails shows in the console. `RouterRole.observers` takes factories of `NavigatorObserver`s instead, which a router calls once for each navigator it creates. An observer sees the pages of one navigator, not the screen the user sees, so use the listeners to follow screens. ## Registering services A module that creates services of the app registers them as data of the DI role with `diRole.data(DiRegistration(...))`, and the provider of the role renders them in the form of its container: | Field | Meaning | | --- | --- | | `type` | The type the service is registered as, usually an interface, with the import that declares it. | | `create` | The top-level function that creates it. Its `deps` are the services it takes, which the container passes in that order. | | `lifetime` | `lazySingleton`, the default, is created on first use. `singleton` is created while the services are registered, and `factory` makes a new one on every use. | | `isAsync` | The function returns a `Future`. Only a singleton can be created asynchronously, and `registerDependencies()` waits for it. | | `dependsOn` | Services that a singleton must wait for although it does not take them. | | `dispose` | A top-level function that takes the instance of a singleton or lazy singleton and disposes of it when `resetDependencies()` resets the container. | | `instanceName` | A name that tells this service apart from others of the same type. | A value known only at run time, such as the id of the item that a screen shows, is not part of a registration. A function in the composition file of a feature takes it as a parameter, as in `DetailsCubit createDetailsCubit(int id)`. Elsewhere, a factory class that takes its services in its constructor creates the objects with such values in a method such as `call(int id)`. It is registered like any other service, and other services take it in their `deps`. The DI role checks the registrations of the app before anything is generated. A service registered twice is an error, and so are a dependency that nobody registers, a cycle, and a singleton that waits for a service that is neither created asynchronously nor waits itself. The fields beyond the basics need capabilities of the container, which each provider declares, and get_it has them all. The provider of the role renders every registration: its files call or tear off the factory of each registration, and its dispose function if it has one. The contract harness checks this in the apps of every provider. So the tests of a module that registers services read the registrations with `diRole.graphOf`, not in the files of a provider; see [Test a module](https://doc.saymyframe.com/extending/testing.md#checking-one-app). The provider also declares `Future<void> resetDependencies()` in `lib/core/di/dependencies.dart`, next to `createServiceLocator()` and `registerDependencies()`. It disposes of the services that the container created, each with its `dispose` function, in the reverse order of their registration. Then it removes every service, so that `registerDependencies()` can register them again. It creates nothing just to dispose of it, so a lazy singleton that nothing resolved is neither created nor disposed of. The app itself never calls `resetDependencies()`, but its tests can, such as a test that registers the services again. SMF's CI runs the start-up of the apps of every provider of the DI role and checks that every registered service resolves, a singleton or lazy singleton to the same instance each time. It also checks that none resolves after `resetDependencies()` and that all of them resolve again after `registerDependencies()`. The services of the fixtures note what their `dispose` functions do, so CI checks the order of the disposal too. ## A provider that renders its data A role with data gives it to its provider, which turns it into code. `go_router` renders the routes of all features into the variables of its brick: ```dart final class _GoRouterProvider extends RoleProvider<RoutesData> { const _GoRouterProvider(); @override Role<RoutesData> get role => routerRole; @override RoleOutput render(RoleHookInput<RoutesData> input) { final facade = routerRole.facadeOf(input); final routes = GoRoutes.of( facade, start: routerRole.startIn(input), mainNavigation: input.has(layoutRole), ); return RoleOutput( fragments: [ if (routes.hasMainNavigation) AppEntryRole.agentSections.entry( routerRole.description, AgentNote(mainNavigationAgentNote), ) else if (input.has(layoutRole)) AppEntryRole.agentSections.entry( routerRole.description, AgentNote(firstDestinationAgentNote), ), ], vars: { 'initial_location': routes.initialLocation, 'main_navigation': routes.hasMainNavigation, 'routes': routes.routes, 'main_navigation_route': routes.mainNavigation, 'value_checks': routes.valueChecks, // Whether the modules of the app declare guards, which the router // then asks. 'guards': facade.guards.isNotEmpty, }, ); } } ``` - `render` gets the data of the role in the order the modules were chosen, with the module that contributed each, and the data of the roles its role requires or uses. `input.has(role)` tells whether such a role is present. The role offers typed views of its data, such as `routerRole.facadeOf(input)`, the routes with their full paths and names, which the provider shares with the facade, so both agree on every path and name. - `RoleOutput.vars` are variables of the provider's bricks. A variable can be a `Fragment` of code with imports, such as the routes, which a template reads as `{{{routes}}}`, and the pipeline adds its imports to that file. See [Templates](https://doc.saymyframe.com/extending/templates.md#variables-of-render-hooks). - `RoleOutput.fragments` put code into sockets, with the same access rules as the module's contributions. Here they are the notes of the module for coding agents that depend on the routes of the app; see [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). - `RoleOutput.files` are text files of the provider, each by its path in the app. A brick has the same files in every app, so a file whose path depends on the data of the role, such as one file for each item that the modules give the role, comes from the hook. See [Files of render hooks](https://doc.saymyframe.com/extending/templates.md#files-of-render-hooks). - `validate` checks the data against what the provider supports and returns problems. `LayoutProvider` does it for the number of destinations, and `bottom_tabs` sets `maxDestinations` to 5. - `manualSteps` returns the steps of the setup that the developer of the app does by hand and that depend on the data, such as those that `firebase_auth` lists for the ways to sign in of Apple and Google. See [Steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#steps-that-depend-on-the-data-of-a-role). The documentation of each role on pub.dev says what it expects of its providers, meaning the files and symbols they generate and the behavior they promise: - the app entry, [`AppEntryRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/AppEntryRole-class.html): `main()` in `lib/main.dart`, which initializes the binding, awaits `bootstrap()` and runs the root widget inside the root wrappers; `bootstrap()` in `lib/bootstrap.dart`, with the phases of start-up in their order and without a design library; the root of the app as a `MaterialApp`, created in the `build(BuildContext context)` of a widget, so that the arguments that modules give the root read the context below the wrappers; the fallback start screen, only in an app that no route starts (`RouterRole.noStartRoute`); and the native projects, with the tags of the native sockets and `ios/Runner/Runner.entitlements`, which every build configuration of the app target signs with; - the router, [`RouterRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/RouterRole-class.html): `createAppRouter()` in `lib/core/router/app_router_factory.dart`, routes named by their full names, the start route at `/`, or the fallback start screen of the app entry there, imported only where no route starts the app, the main navigation around the layout's `AppShell`, the `StateError` of `push()` and `replace()` with a location of the main navigation on a page over it, a `config` created once, the back button of the system, on its error screen too, `push()` and `replace()` on that screen, observers for every navigator, the listeners of the screen, each called on its own, and the [guards](https://doc.saymyframe.com/extending/router-guards.md) of an app that has them; - the layout, [`LayoutRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/LayoutRole-class.html): `AppShell(destinations:, currentIndex:, onSelect:, body:)` in `lib/core/layout/app_shell.dart`, with `destinations`, `currentIndex` and `onSelect` as public fields or getters; - dependency injection, [`DiRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/DiRole-class.html): `createServiceLocator()`, `registerDependencies()` and `resetDependencies()` in `lib/core/di/dependencies.dart`, the registrations in the order of `DiGraph.ordered`, a call or a tear-off of the factory of every registration and of its dispose function, and the capabilities of the container; - the settings screen, [`SettingsScreenRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/SettingsScreenRole-class.html): a route of the provider that shows [the screen](https://doc.saymyframe.com/extending/provide-settings-screen.md), with every entry of the modules once, in the order of the role; - localization, [`LocalizationRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/LocalizationRole-class.html): the extension `AppTexts` on `BuildContext` in `lib/core/l10n/l10n.dart`, with a getter for [each text](https://doc.saymyframe.com/extending/provide-localization.md) of the app in each of its languages; - the theme, [`ThemeRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/ThemeRole-class.html): `createLightTheme(context)` and `createDarkTheme(context)` in `lib/core/theme/app_theme.dart`, the [look](https://doc.saymyframe.com/extending/provide-theme.md) of the app; - the onboarding screen, [`OnboardingScreenRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/OnboardingScreenRole-class.html): a route of the provider that shows the onboarding, named with an `OnboardingScreenRoute`, and a file of the provider that reads `appOnboardingSteps` of `lib/core/onboarding/onboarding_steps.dart` and shows each step that its `showIf` keeps, on a page of its own, in the order of the list; see [Add a step to the onboarding](https://doc.saymyframe.com/extending/onboarding-steps.md#what-the-onboarding-does-with-a-step); - sign-in, [`AuthRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/AuthRole-class.html): one implementation of `AuthService` of `lib/core/auth/auth_service.dart`, the same in every mode of the app, whose calls fail only with an `AuthFailure`; see [Provide sign-in](https://doc.saymyframe.com/extending/provide-auth.md); - notifications, [`NotificationsRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/NotificationsRole-class.html): one implementation of `NotificationsService` of `lib/core/notifications/notifications_service.dart`, whose function asks the user nothing, that shows every notification in the channel of the app, schedules at about a time, also after a restart of the device, and opens the settings of the system on a request where the platform has no question; see [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md#for-a-provider); - push messages, [`PushRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/PushRole-class.html): one implementation of `PushService` of `lib/core/push/push_service.dart`, whose `address` keeps from one launch to the next and never throws, which never asks for the permission to show notifications, and which tells whether the platform shows a message in the foreground; see [Notifications and push messages](https://doc.saymyframe.com/guides/notifications.md#for-a-provider); - purchases, [`PurchasesRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/PurchasesRole-class.html): one implementation of `PurchasesService` of `lib/core/purchases/purchases_service.dart`, whose function asks the user nothing and never throws, whose calls fail only with a `PurchasesFailure`, and which keeps the purchases of each user apart; see [Purchases](https://doc.saymyframe.com/guides/purchases.md#for-a-provider); - the values in `.env`, [`EnvRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/EnvRole-class.html): `AppEnv` in `lib/core/env/app_env.dart`, with a getter for every key that returns the value of `.env`, or `null` for an empty or missing one, before any code of the app runs; see [Values in .env](https://doc.saymyframe.com/guides/env.md#for-a-provider). - the REST client, [`RestRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/RestRole-class.html): [one implementation](#rest-api) of `RestTransport` of `lib/core/rest/rest_transport.dart`; - CI, [`CiRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/CiRole-class.html): a file in [the format of its host](#ci) with every command of `ciRole.pipelineIn`; - the app icon and the splash screen, [`AppIconRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/AppIconRole-class.html) and [`SplashRole`](https://pub.dev/documentation/smf_contracts/latest/smf_contracts/SplashRole-class.html): [two images](#app-icon-and-splash-screen) in `assets/branding/` for each, and a step that makes the result. When the user presses the back button of the system, a router closes the route on top. It tries `NavigatorState.maybePop` on the navigators that the user sees, the innermost first: a dialog closes before the page below it, and a page of the selected branch of the main navigation before the main navigation, unless a route of the root navigator, such as a dialog, covers the main navigation. With no route to close, the router leaves the button to the system, which closes the app. A press that closes a route is one that the router handled. Otherwise the system takes the button too, and closes the app together with the route. The error screen of a router is a page like any other for the button. A dialog over it closes, and the button throws nothing there. The screen itself closes only if a page is below it, which is up to the provider. With none, the router has no route to close and leaves the button to the system. On its error screen, a router still shows the location that `push()` or `replace()` asks for, and the listeners of the screen hear of it once. `replace()` shows it in place of that screen. `push()` shows it over that screen and completes with the value of its page. A provider that has no page there to push over shows it in place of that screen, as `go()` does, and completes the push with `null` at once. The layout role generates `lib/core/layout/destination.dart` with the class `Destination` and with `appDestinations`, the destinations of the app in the order of the features. The label of a `Destination` is a function of a `BuildContext`, which returns the text of its module in the language of the app, or its English text. So the two providers share the work like this: - A router gives the shell `LayoutRole.appDestinations` as its `destinations` and has a branch for each, in the same order. It renders neither a label nor an icon. The contract harness checks that, in an app with a layout and destinations, the files of the router read `appDestinations` (the rule `router.destinations_shown`). - A layout shows a label with `destination.label(context)` in the `build` of the widget that shows it, as a text, in a tooltip or to the semantics, and keeps nothing of what it returned. The widget then builds again with the new label when the language changes. A layout keeps `destinations`, `currentIndex` and `onSelect` of its `AppShell` public because code that knows only the role reads them, whichever layout provides it. A test of the main navigation does this: it finds a destination among `destinations` by its label and icon, selects it with `onSelect`, as the layout does when the user selects it, and reads the selected one from `currentIndex`. The `body` may stay private, since such code finds what the shell shows in the widget tree. SMF's CI checks the router and the layout in running apps, with every provider of the two roles that SMF has. One test starts the app and goes with `go()` to each location that needs no values, up to the first 20. Each location must show the page of its route on top of the innermost navigator, named after the route, and the screen of the route, with no `ErrorWidget` and no error from Flutter. Other tests check the listeners of the screen, the observers, the back button, also on the error screen, `push()` and `replace()` from that screen, the `StateError` of `push()` and `replace()`, the `config` created once, the guards and the conditions of the routes, the switches between the destinations of the layout, and that the layout shows no label in a language that the app is no longer in. [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) lists these tests. ## The app entry A provider of the app entry owns the native projects, so it has the flavors of the role there. The flavors are constants, `AppEntryRole.flavors`, each an `AppFlavor`, and a module or a tool reads their names and ids from them (`applicationIdIn`, `bundleIdIn`, `xcodeConfigurations`). `AppEntryRole.defaultFlavor` is what `default-flavor` in the pubspec names, and `AppEntryRole.releaseFlavor` has the id of the app itself. The structural rule `app_entry.flavors` checks each native project that the app has: | File | What it has | | --- | --- | | `pubspec.yaml` | `default-flavor`, which names a flavor of the role | | `android/app/build.gradle.kts` | Exactly those flavors in `productFlavors`, each with a dimension and its application id | | `ios/Runner.xcodeproj/project.pbxproj` | The build configurations of each flavor in every configuration list, by the `name` of the object. In the app target they have the bundle id of the flavor and a base, the same for the flavors of a mode. | | The scheme of each flavor | It exists, takes those configurations in each action and runs the pre-action of Flutter | The rule leaves two things to other tests. Only a run of the `flutter` tool shows which flavor is the default, which a test of the role checks in a running app. And a provider may write the name on the device in another form. The template of the role writes the section "Flavors" of the README of the app, so the README of every provider has the tag of `AppEntryRole.readmeSections`. The provider writes a section of its own, `AppEntryRole.flavorProjectsHeading`, on where each flavor is in its native projects. The module rule `app_entry.ios_deployment_target_tag` keeps a literal iOS version out of the template of `project.pbxproj`. Each build configuration of the project has the tag of `AppEntryRole.iosDeploymentTarget` as its `IPHONEOS_DEPLOYMENT_TARGET`, and one of a target has that tag or no such setting, so a version that a module raises reaches every configuration. ## CI The CI role knows what runs and not where. `ciRole.pipelineIn` gives the commands as data, a `CiPipeline`, and a provider writes them in the format of its host, in a file of `RoleOutput.files` of its render hook, since the syntax of such a format may read like a tag of a brick. Each command runs in a POSIX shell at the root of a fresh copy of the repository, on a machine with the Flutter SDK and a JDK, which the provider sets up: | In `CiPipeline` | What the provider does with it | | --- | --- | | The checks | Runs them on each push | | `CiBuild.environments` | Offers them to a developer, who picks one when a build starts, the first by default | | `CiBuild.keys` | Passes each to `CiBuild.prepare` as a variable of the process. A value reaches a command only that way, never in the text of a script. | | `CiBuild.prepare`, `CiBuild.command` | Runs them in that order | | `CiBuild.artifact` | Keeps the file | The structural rule `ci.pipeline_rendered` reads the files of the provider other than Dart files as lines of text, without those that start with `#` or `//`. It looks for each command at the end of a line, and for each environment and each key as a whole word. In the place of the environment, the command and the file each have a reference of the host, or every environment. It sees presence and not structure: a command in the wrong job, or a job that never runs, passes it. So a provider keeps a test that parses its format, as `test/workflow_test.dart` of `smf_github_actions` does, and shows the file in a real run. An app has at most one provider, since a repository lives on one host. The app does not read the role, so the role has no test in a running app. A provider tells in a section of its own in the README of the app how to start a build. ## App icon and splash screen The app icon role and the splash role have no sockets and no Dart symbols, since no module gives them data and no code of the app reads them. Each holds the paths of two images, which every provider generates and the app does not bundle: `AppIconRole.imageFile` and `foregroundFile`, and `SplashRole.lightImageFile` and `darkImageFile`, all in `assets/branding/`. What the images show, the colours around them and the tool that makes the result belong to the provider. One module may provide both roles. The native projects are files of the provider of the app entry, and two bricks cannot generate one file, so a provider makes the icon or the screen in a `PostGenStep`. The rules `app_icon.step` and `splash.step` report a provider with no step that a run without a terminal runs too, which is a step that is neither external nor interactive, has no notice and continues no other step. Mark it `skippable`, so that a tool that fails costs a warning and not the app: ```dart const PostGenStep( ToolRef('dart'), [updateScript], description: 'Making the app icon from assets/branding', skippable: true, ), ``` The template of each role writes its section of the README of the app and its note. The section and the note of the provider tell what the images show and give the command that makes the result again after a change. What reached the native projects shows only once the step has run, so neither the rules nor a snapshot see it: the tests of the two roles read the files of the app as `smf create` left them. ## Roles with a page of their own Four roles, and the guards of the router role, ask more of a provider than fits here: - [Ask the guards in a router](https://doc.saymyframe.com/extending/router-guards.md): what a provider of the router role calls in an app with guards, and what it does with each answer. - [Provide the settings screen](https://doc.saymyframe.com/extending/provide-settings-screen.md): the route of the screen, and the entries that the modules give it. - [Provide the localization](https://doc.saymyframe.com/extending/provide-localization.md): the texts of the app in its languages. - [Provide the theme](https://doc.saymyframe.com/extending/provide-theme.md): the light and the dark theme, and what the role does with the mode. - [Provide sign-in](https://doc.saymyframe.com/extending/provide-auth.md): the service of a provider of the auth role, and what the role does with the session and the mode. # Ask the guards in a router Source: https://doc.saymyframe.com/extending/router-guards A module can keep the user from the rest of the app with a guard, or from the routes that ask for a condition, and it declares the guard as data of the router role. [Guards of routes](https://doc.saymyframe.com/concepts/guards.md) and [Conditions of routes](https://doc.saymyframe.com/concepts/conditions.md) describe what the user then sees. This page is for a module that [provides the router role](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data): what it calls, when, and what it does with each answer. ## The class of the role In an app with guards, the template of the role generates `routeGuards`, `redirectOf()`, `flowIsOver()`, `guardChanges` and the class `GuardedNavigation`, with the classes of its answers, in `lib/core/router/app_router.dart`. The class decides what a router does about the guards and keeps what the gates make it remember. A router creates it once, asks it at two times and does what it answers: 1. The router creates one `GuardedNavigation<L>`, where `L` is how it knows a location that it can show as `go()` does, such as a URI. It gives the class its location `/`, the screen that the app starts on, as `start`, and a function from an `AppLocation` of the navigation to its own location as `locationOf`. 2. Before it shows a location, it calls `asked`. 3. Each time `guardChanges` notifies, it calls `changed`. Routers that ask alike and do what they are answered show the user the same pages at the same time. ## Before a location shows ```dart WhenAsked<L>? asked(String? route, L location, {required Iterable<String?> onTopOf}) ``` The router calls it for the location the app starts on, for each location that `go()`, `push()` or `replace()` of the navigation is asked to show, and for each location that the platform gives it, if it takes any. | Argument | What the router gives | | --- | --- | | `route` | The full name of the route of the location, or `null` for a location that is no route of a module: one that no route matches, and `/`. | | `location` | The location, as the router knows it. | | `onTopOf` | The full names of the routes of the pages that the user can get back to at that time, the same pages that it tells `changed` of. It gives none while it has no page, and none for a location from the platform, which takes the place of the stack. | The router does what the answer says: | Answer | What the router does | | --- | --- | | `null` | It shows the location. | | `ShowInstead(location)` | It shows that location in place of the other, as `go()` to it does. The location is the target of a gate, or `/` for a location in a flow that is over. It takes the whole stack, whichever page the other location was asked from, and such a `push()` completes with `null` at once. | | `ShowOver(location, flow: routes)` | It shows the location over the page on top, as `push()` of it does, so the user can go back from it. The location is the target of a guard that stands for a condition, or a page of the flow of such a guard that was itself asked for with no pages, and `flow` has the full names of the routes of that flow. The router keeps the request waiting, and a `push()` that waits does not complete. | | `ShowNothing()` | It shows nothing and leaves its pages as they are, since the flow of the guard is open already. Such a `push()` completes with `null` at once. | Unless the answer is `null`, or a `ShowOver` of the location itself, the router does not build the screen of the location, and the listeners of the screen do not hear of it. A request that waits is asked about again before its location shows. - The target of a gate also takes the stacks of every branch of the main navigation, so that each branch is back on its destination when the user comes to it again. The location `/` for a flow that is over hides nothing from the user. The router shows it as its `go()` to that location does, and whether the branches that are not selected keep their pages then is up to the router. - Asked with no pages, as for a location from the platform, a router that gets `ShowOver` first shows `/` in place of the stack and then the location of the answer over it. The listeners of the screen hear only of that location. - The class keeps no request. Asked again about a location that it answered `ShowOver` for, with a page of the flow among `onTopOf`, it answers `ShowNothing` for a location that the guard keeps the user from, and `null` for a page of the flow. ### The answer depends on the pages The routes of the flow of a guard that stands for a condition show while the condition does not hold. What `asked` answers for one of them depends on `onTopOf`: | A page of such a flow is asked for | The answer | | --- | --- | | On a page | `null`. The page shows as the code of the app asked: over that page for `push()`, and in place of the stack for `go()`. | | With no pages, as by a link | `ShowOver` of the location itself, with its query, and of the flow. The page opens over `/`, back leads to `/`, and once the condition holds the router closes the flow. A route below the target then has `/` alone below it. | So a router never asks with no pages about a location that it shows over a page, nor about a location that it goes to for a request that it asked about with the pages. Asked so about the target that it shows for a `ShowOver`, the class answers `ShowOver` again, and the router would open the target without end. A router whose redirect runs for each location that it goes to, with no pages, keeps the calls of its own navigation from the class. A router that cannot rule such a call out should fail loudly when it happens, as `go_router` does with a `StateError`, and not open the target again and again. Such a redirect may still run again for the location that it answered with, that of a `ShowInstead` or `/`: the location takes the place of the stack, and the class answers for it as for any other. While a gate with the same flow does not allow, the flow is the gate's, and its page takes the place of the stack. ## The request that waits The request that waits is the one that the router got `ShowOver` for: the location, and whether `go()`, `push()`, `replace()` or the platform asked for it. The router keeps it, not the class, since only the router can complete a `push()`. It keeps one request. When it gets `ShowOver` while a request waits, it drops the earlier one, and a `push()` that waited completes with `null`. The request waits while a page of a route of the `flow` of the answer is among the pages that the user can get back to, so it is still there after a `push()` or a `replace()` inside the flow. It ends in one of three ways: | What ends it | What the router does | | --- | --- | | `changed` answers `ClosePages` without `dropsRequest`, and no page of the flow is left once the router closed the pages. | It makes the request again as it was made, on top of the pages that are left, and asks the class about it again. `push()` shows the location over the page that the flow was opened from, and the first `push()` completes with the value of that page. `go()` shows it in place of the stack, `replace()` in place of the page that the flow was opened from, and a location from the platform as `go()` to it. | | `changed` answers `ClosePages` with `dropsRequest`. | It drops the request, and does not make it on the page below. The pages that close reach below the flow, so the page that the request was made on closes too, as one that asks for another condition, which stopped holding. | | The last page of the flow leaves in any other way: the user goes back from it, or a location takes the place of the stack. | It drops the request, and a `push()` that waited completes with `null`. | When the router makes the request again, the class may answer with the target of another guard, as for a route that asks for two conditions. For a page of the flow that a link asked for, the request that waits is the page itself. Asked about again once the flow closes, it is answered with `/`, where the user is then. The target of a gate takes the place of the stack, and the request goes with the pages of its flow. When that target is a page of the same flow, as for a gate and a guard of a condition with one flow, the request waits on until the target leaves. ## When a guard changes ```dart WhenChanged<L>? changed(Iterable<({String? route, L location, bool pushed})> pages) ``` Each time `guardChanges` notifies, the router calls it with the pages that the user can get back to, the one on top first: those of its root navigator and, in place of the main navigation, those of its selected branch. It leaves out the pages of the other branches. A guard may notify though what it allows did not change. Each page comes with the full name of its route or `null`, with its location, and with `pushed`: whether the router can close the page on its own and leave the pages below it as they are. That is `true` for a page that `push()` showed, and for a page that `replace()` showed in place of such a page. Whether a page that `replace()` showed in place of another page is one is up to the router. A router that has no page yet, as before it shows the location that the app starts on, has none to tell of and shows nothing then. It asks about its first location when it shows it. | Answer | What the router does | | --- | --- | | `null` | It leaves everything as it is: the stack stays, the listeners of the screen hear nothing, and each `push()` still completes with the value of its page. | | `ShowInstead(location)` | It shows the location in place of its whole stack, as for that answer of `asked`, and the target of a gate in place of the stacks of every branch too. That holds whenever the gate allows again: also in the turn in which it stopped allowing, and while the transition to its target is on its way. | | `ClosePages(pages, dropsRequest: ...)` | It closes that many pages on top, each of which it told of as `pushed`, and leaves the pages below them as they are. Each `push()` that showed one of them completes with `null`, at once or when the frame is over. Then it drops the request that waits, with `dropsRequest`, or else makes it again, if no page of its flow is left. | What `ClosePages` asks of a router: - The pages leave at once, whatever the navigator shows over them, such as a dialog. That includes a page that a `push()` of the same turn showed and that the navigator has not built yet. - The listeners of the screen hear of the page that the user ends on. They do not hear of the page below the closed ones when the request shows another page over it, since the user never saw that page come back. - Until the navigator builds again, it may still have the route of a page that the router closed. The code of a screen that closes its own page in that time, or the back button of the system, closes that route and no page of the router, and the router does not fail. The `push()` of such a page may complete with the value that the page closed with. - `ShowOver` and `ClosePages` leave the main navigation and its branches as they are, since no route of the main navigation asks for a condition. With `ShowInstead` from `changed`, two things are up to the router: whether the listeners of the screen hear of a target that no frame showed, and whether the `push()` of a page that the answer takes out of the stack completes, as when `go()` replaces the stack. ## Without a page, and on the error screen A router may have no page to push over or to replace: before it shows its first location, or on an error screen that took the place of its stack. It may then take each request as `go()` to its location, which takes the place of the stack as a location from the platform does. It asks about the location once, with no pages, and such a `push()` completes with `null` at once. The target of a guard that stands for a condition then opens over the location `/`, in place of the error screen too. On its error screen, a router still shows the location that `push()` or `replace()` asks for, and the listeners of the screen hear of it once; see [Provide a role](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data). ## With go_router `go_router` knows a location by its URI. It creates the class with its location `/` and with the path of an `AppLocation`: ```dart title="lib/core/router/app_router_factory.dart" final GuardedNavigation<String> _guards = GuardedNavigation( start: '/', locationOf: (location) => location.path, ); ``` `go()`, `push()` and `replace()` ask once, before they hand a location to go_router, with the routes of the pages that the user can get back to. For `ShowOver` the router pushes the target and keeps the request: how to make it again, and how to end it without showing its location, which for a `push()` completes its future with `null`. ```dart title="lib/core/router/app_router_factory.dart" final answer = _guards.asked( location.routeName, location.path, onTopOf: [for (final page in _pages) page.route], ); switch (answer) { case null: return false; case ShowInstead(location: final shown): _own(() => config.go(shown)); drop?.call(); case ShowNothing(): drop?.call(); case ShowOver(location: final target, :final flow): _open(target, flow, again: again, drop: drop); } return true; ``` The top-level `redirect` of go_router runs inside each call of go_router, and asks with no pages. So the router counts the calls that it makes itself, with `_own`: those with a location that it asked about, or that the class answered, or with pages that are shown already, a refresh of go_router among them. Within them the `redirect` asks nothing: ```dart title="lib/core/router/app_router_factory.dart" R _own<R>(R Function() navigate) { _asking++; try { return navigate(); } finally { _asking--; } } ``` What is left for the `redirect` are the locations that go_router parses on its own: the one the app starts on, those of the platform, and that of a branch of the main navigation that the user selects. Such a location takes the place of the stack, so the router gives no pages. A redirect can only send go_router to another location. So for `ShowOver` the router sends it to `/` and pushes the location of the answer in a microtask, once the parse is over. When the page on top is that location already, as for a second link to a page of a flow, the router puts that page back over `/` and pushes no new one, so the page keeps its state: ```dart title="lib/core/router/app_router_factory.dart" String? _redirect(String? route, String location) { if (_asking > 0) return null; switch (_guards.asked(route, location, onTopOf: const [])) { case null || ShowNothing(): return null; case ShowInstead(location: final shown): return shown; case ShowOver(location: final target, :final flow): _muted = true; final onTop = config.routerDelegate.currentConfiguration.lastOrNull; final kept = onTop is ImperativeRouteMatch && '${onTop.matches.uri}' == target ? onTop : null; void open() { if (_opening != open) return; _opening = null; _muted = false; _open(target, flow, again: () => config.go(location), kept: kept); if (_opening == null) return; _opening = null; throw StateError( 'The redirect of go_router asked the guards about $target, ' 'which the router pushes itself, and would open it without ' 'end: it must ask nothing within a call of the router.', ); } _opening = open; scheduleMicrotask(open); return _guards.start; } } ``` The push of the target is a call of the router's own, so the `redirect` is not asked about it. If it ever were, the class would answer to open the target again, without end, and the router throws a `StateError` then. While go_router has no page of a route, before its first location and on its error screen, the router asks the class nothing itself. `go()`, `push()` and `replace()` give go_router the location as `go()` does, and the `redirect` asks about it, with no pages. The router listens to `guardChanges` itself and tells the class of its pages: ```dart title="lib/core/router/app_router_factory.dart" void _guardsChanged() { final pages = _pages; if (pages.isEmpty) return; switch (_guards.changed(pages)) { case null: break; case ShowInstead(:final location): _own(() => config.go(location)); case ClosePages(pages: final count, :final dropsRequest): _close(count, dropsRequest: dropsRequest); } } ``` It does not hand `guardChanges` to go_router as its `refreshListenable`: a refresh asks only about the location below the pushed pages, and gives each of those pages a new completer. To close pages, it takes them out of the pages of go_router with one `restore()` and completes their pushes once the frame is over. `pop()` would close what the navigator shows on top, such as a dialog over the page. An app without guards has none of these names in `app_router.dart`, so a provider renders this code only when `routerRole.facadeOf(input).guards` is not empty. `go_router` gives its brick the variable `guards` for it, as [its render hook](https://doc.saymyframe.com/extending/role-provider.md#a-provider-that-renders-its-data) shows. [`go_router`](https://doc.saymyframe.com/modules/go-router.md#guards) describes the rest of what the module does. ## What is checked The rule `router.guards_asked` of the contract harness checks that, in an app with guards, the files of the provider create a `GuardedNavigation`, read `guardChanges`, and name the answers `ShowOver` and `ClosePages`. It asks for both answers in every app with guards, also in one whose guards are all gates. So neither a router that knows nothing of the guards nor one that shows every answer in place of its stack can be in an app with a module that needs them. Whether the router does what the class answers, only a running app shows. SMF's CI checks that in running apps, with every provider of the router role that SMF has. It also runs the same tests on routers with a known bug, such as one whose `replace()` leaves the stack as it is, or one that drops the request that waits when the pages of the flow close, and each must fail on its bug. [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) lists these tests. # Provide the settings screen Source: https://doc.saymyframe.com/extending/provide-settings-screen The settings screen role is provided by a module with a route that shows the screen, so the role requires the router. The modules of the app, and the templates of roles, give the role the entries of the screen, and the provider shows them. [How settings work](https://doc.saymyframe.com/concepts/settings.md#the-settings-screen) describes the role, and [Add a setting](https://doc.saymyframe.com/extending/settings.md) the side of a module with an entry. ## The module and its provider This is what `settings`, a feature, contributes: ```dart @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution( settingsBundle, vars: localizationRole.varsOf(id, _texts), ), localizationRole.data(_texts), routerRole.data( const RoutesData([ Route( '/', name: _route, screen: ScreenRef( 'SettingsScreen', import: ImportRef.app('features/settings/settings_screen.dart'), ), destination: Destination( label: _titleText, icon: Fragment( 'Icons.settings', imports: [ ImportRef('package:flutter/material.dart', show: ['Icons']), ], ), ), ), ]), ), settingsScreenRole.data(const SettingsScreenRoute(_route)), AppEntryRole.agentSections.entry( settingsScreenRole.description, AgentNote(agentNote), ), ]; ``` The title of the screen is a text of the module, `_titleText`, which is the label of its destination too. Its provider renders the entries of the role, each with an import of its file, and tells the brick whether the app has any: ```dart final class _SettingsProvider extends RoleProvider<SettingsData> { const _SettingsProvider(); @override Role<SettingsData> get role => settingsScreenRole; /// Two variables of the brick of the screen: /// - `entries`, the widgets of the entries as the items of a constant /// list, one on a line, in the order of the role, with the imports of /// their files, each with a prefix of its own: `entry0` for the first /// file, `entry1` for the next. Without entries, the variable has no /// code, and its line of the template goes away. /// - `with_entries`, whether the app has an entry. The template has the /// group of the entries in an app with one, and the note of a screen /// without settings in an app with none, so no app gets the code of /// the other screen. @override RoleOutput render(RoleHookInput<SettingsData> input) { // The import of each file of an entry, with its prefix, by the path of // the file. final files = <String, ImportRef>{}; final items = <String>[]; for (final entry in settingsScreenRole.entriesIn(input)) { final widget = entry.widget; // The template of the role rejects an entry whose widget is not in a // file of the app, so each has an import. final import = widget.import!; final prefix = files .putIfAbsent( import.uri, () => import.withPrefix('entry${files.length}'), ) .prefix; items.add(' ${widget.codeWith(prefix)}(),'); } return RoleOutput( vars: { 'with_entries': items.isNotEmpty, 'entries': Fragment(items.join('\n'), imports: [...files.values]), }, ); } } ``` The template of the screen reads the entries as a fragment variable, inside a constant list. That list is in the section of `with_entries`, so only an app with entries gets the group: ```dart title="bricks/settings/__brick__/lib/features/settings/settings_screen.dart" bottom: false,{{#with_entries}} child: ListView( padding: const EdgeInsets.fromLTRB(16, 20, 16, 32), children: [ title, const SizedBox(height: 20), const _Group( children: [{{/with_entries}} {{{entries}}} {{#with_entries}} ], ), ], ),{{/with_entries}}{{^with_entries}} child: CustomScrollView( ``` An app without entries gets what follows `{{^with_entries}}` instead: a note that tells the developer of the app that it has no settings yet, with the path of the file of the screen. The provider knows whether the app has entries when it renders them, so each app gets the code of its own screen and nothing of the other. `_Group` is a class of the same file, a card with the entries one below the other and a line between them. [`settings`](https://doc.saymyframe.com/modules/settings.md#the-settings) shows the file of an app. ## What every provider promises - It names exactly one route of its own as the screen, with `SettingsScreenRoute`. The route needs no values, so that code which knows only the role can go to the screen. - The screen shows every entry of `settingsScreenRole.entriesIn(input)` once, in that order: the entries of the modules in the order the modules were chosen, then those of the templates of roles. - It shows the entries one below the other in a list that scrolls, on a `Material`. It sets the width of each entry, the same for every entry between the same left and right edges, and puts no limit on its height. - It creates the widget of each entry in a file other than that of the widget, through an import of that file with a prefix that no import of another file has, such as `entry0`. So widgets of the same name in the files of different modules do not clash, with each other or with the names of the file of the provider. How the user gets to the screen is up to the provider. `settings` makes its route a destination of the main navigation. ## What is checked `smf create` checks the route before it generates an app. The contract harness also checks that the files of the provider create the widget of every entry through such an import. SMF's CI checks the rest in running apps: the route shows the screen, and the screen shows each entry once, in order, in a list that scrolls; see [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time). # Provide the localization Source: https://doc.saymyframe.com/extending/provide-localization The localization role gets [the texts](https://doc.saymyframe.com/extending/texts.md) of the modules and chooses the languages of the app. Its template generates the languages, the language that the user chose and what the root of the app needs to follow it. A provider keeps the texts and renders them. [Texts and languages](https://doc.saymyframe.com/concepts/localization.md) describes the role. ## What a provider generates - It generates `lib/core/l10n/l10n.dart` with the extension `AppTexts` on `BuildContext`, whose getter `l10n` returns an object with a `String` getter for each text of `localizationRole.textsIn(input)`, named by `AppText.getter`. - Each getter returns the text in the language of the context, or in English when the text has no translation into that language. - It renders the texts in the languages of `localizationRole.localesIn(input)` only. - `context.l10n` works in every context below the root of the app, in the language that the root is in, also once that language changes. - A provider that loads its texts with a delegate adds the delegate to the `localizationsDelegates` of the root, and the delegate supports each language of `appLocales`. One that reads the locale of the context itself needs none. The provider adds no language to the root. `supportedLocales` takes the items of one contributor, and in an app with the role that is the template of the role. ## With gen-l10n of Flutter How the texts are kept is the provider's choice. [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) keeps them in ARB files, one for each language, and leaves the code that reads them to gen-l10n of Flutter. The number of the files depends on the languages of the app, so its render hook generates them: ```dart @override RoleOutput render(RoleHookInput<TextsData> input) { final texts = localizationRole.textsIn(input); return RoleOutput( files: { for (final language in localizationRole.localesIn(input)) '${GenL10nModule.arbDirectory}/app_$language.arb': _arbOf(language, texts), }, ); } ``` `_arbOf` writes each text that is in the language under the name of its getter. In an app with `settings` and `material_theme`, the file of Ukrainian has the title of the settings screen, the two texts of the fallback start screen of `flutter_core`, which an app that no route starts has, as this one, and the texts of the entries of the theme role and of the localization role: ```json title="lib/l10n/app_uk.arb" { "@@locale": "uk", "settingsTitle": "ΠΠ°Π»Π°ΡˆΡ‚ΡƒΠ²Π°Π½Π½Ρ", "flutterCoreFallbackHint": "Π‘Ρ‚Π°Ρ€Ρ‚ΠΎΠ²ΠΎΠ³ΠΎ Π΅ΠΊΡ€Π°Π½Π° Ρ‰Π΅ Π½Π΅ΠΌΠ°Ρ”. Π”ΠΎΠ΄Π°ΠΉΡ‚Π΅ Ρ„Ρ–Ρ‡Ρƒ Π· ΠΌΠ°Ρ€ΡˆΡ€ΡƒΡ‚ΠΎΠΌ Π°Π±ΠΎ Π·Π°ΠΌΡ–Π½Ρ–Ρ‚ΡŒ Ρ†Π΅ΠΉ Π΅ΠΊΡ€Π°Π½.", "flutterCoreFallbackCopied": "Π‘ΠΊΠΎΠΏΡ–ΠΉΠΎΠ²Π°Π½ΠΎ", "themeTitle": "Π’Π΅ΠΌΠ°", "themeSystem": "БистСмна", "themeLight": "Π‘Π²Ρ–Ρ‚Π»Π°", "themeDark": "Π’Π΅ΠΌΠ½Π°", "localizationLanguage": "Мова", "localizationSystem": "Π―ΠΊ Ρƒ систСмі" } ``` The brick of the module has what every app gets: `l10n.yaml`, and `lib/core/l10n/l10n.dart` with the extension, whose getter returns the class that gen-l10n generates: ```dart AppLocalizations get l10n => AppLocalizations.of(this); ``` The module also turns the generation on in the pubspec and gives the root of the app the delegate of that class: ```dart const PubspecContribution.flutter(generate: true), // The code that gen-l10n generates imports intl, in the version // that flutter_localizations of the Flutter SDK pins. const PubspecContribution.hosted('intl', 'any'), const SocketContribution.arg( AppEntryRole.appArgs, 'localizationsDelegates', Fragment( 'AppLocalizations.delegate', imports: [ImportRef.app('l10n/app_localizations.dart')], ), ), ``` A provider checks what only it knows in its `validate` hook. The class that gen-l10n generates has members of its own, such as `supportedLocales`, so `gen_l10n` reports a text whose getter would have the name of one of them. A provider that keeps its texts in Dart code renders a getter for each text into its brick instead, as a fragment variable of its render hook. The fixtures of `smf_pipeline` have such a provider, with a delegate written by hand. See [Files of render hooks](https://doc.saymyframe.com/extending/templates.md#files-of-render-hooks) for the rules of the files that a hook generates. ## What the role does itself The role owns everything that is the same with every provider, so a provider leaves it alone: - the list of the languages, `appLocales`, and the language that the user chose, `appLocale`, which the app remembers in its preferences; - the `locale` and the `supportedLocales` of the root; - in an app with a settings screen, the entry in which the user chooses the language; - the section "Languages" of the README of the app, and the note of the role for coding agents, which tell where the languages are and each place that a new language goes into. So a provider tells in a README section of its own, and in its note, only where its texts are, how to add one, and what its texts need for a new language. The role requires the preferences role, and a provider requires what its role requires. So an app with the provider has a module that provides the preferences, and the registry of the tests of the provider has one too, as that of `smf_gen_l10n` has `SharedPreferencesModule`. ## What is checked The contract harness checks that the provider generates the extension, and that one of its files names the getter of every text of the app. So the tests of a module with texts need not look into the files of a provider. SMF's CI checks the rest in running apps, with every provider of the role that SMF has: the app shows each of its texts in each of its languages, in English where a translation is missing, follows the language of the device, and remembers the language that the user chose. [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) lists these tests. # Provide the theme Source: https://doc.saymyframe.com/extending/provide-theme The theme role splits the theme between its provider and its template. A provider owns the look: the light and the dark theme of the app. The template of the role owns the theme mode that the user selects, the same with every provider. [How settings work](https://doc.saymyframe.com/concepts/settings.md#the-theme-mode-a-setting-of-a-role) describes the mode, and [Theme](https://doc.saymyframe.com/guides/theme.md) what the app has. ## The two functions A provider generates two functions in `lib/core/theme/app_theme.dart`. Each takes the `BuildContext` of the root of the app and returns a `ThemeData`: `createLightTheme` one whose brightness is `Brightness.light`, and `createDarkTheme` one whose brightness is `Brightness.dark`. This file of a brick is all that a provider needs. It derives both themes from one color: ```dart title="bricks/seed_theme/__brick__/lib/core/theme/app_theme.dart" import 'package:flutter/material.dart'; /// The colour that the light and the dark theme of the app derive their /// colours from. Change it to give the app another look. const Color seedColor = Colors.teal; /// The light theme of the app. /// /// The root of the app calls it each time it builds, so a change of this /// file shows on a hot reload. [context] is the context of the root, above /// its `MaterialApp`: it has neither the theme nor the localizations of the /// app. ThemeData createLightTheme(BuildContext context) => _themeOf(Brightness.light); /// The dark theme of the app; see [createLightTheme]. ThemeData createDarkTheme(BuildContext context) => _themeOf(Brightness.dark); /// The Material 3 theme of [brightness] in the colours of [seedColor]. What /// both themes of the app share goes here, such as the shape of its /// buttons. ThemeData _themeOf(Brightness brightness) => ThemeData( colorScheme: ColorScheme.fromSeed( seedColor: seedColor, brightness: brightness, ), ); ``` The developer of the app edits this file for another look, so its comments say where each thing is changed. A module whose brick has this file is a plain provider: ```dart final class SeedThemeModule extends SmfModule { /// Creates the module. const SeedThemeModule(); /// The id of the module. static const id = ModuleId('seed_theme'); @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Light and dark Material 3 themes from one seed colour', kind: ModuleKinds.infrastructure, providers: [RoleProvider.plain(themeRole)], ); @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(seedThemeBundle), ]; } ``` ## A provider with a font The built-in [`material_theme`](https://doc.saymyframe.com/modules/material-theme.md) is a plain provider too. Its file is longer: a palette, text styles and the themes of the components. Its themes are in a font that the app bundles. The brick has the files of the font and their license in `assets/fonts/geist/`, and the module declares them in the pubspec of the app, next to its brick and its note for coding agents: ```dart @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(materialThemeBundle), PubspecContribution.flutter( assets: const [fontLicenseFile], fonts: [ PubspecFont(fontFamily, [ for (final MapEntry(key: weight, value: file) in fontFiles.entries) PubspecFontAsset(file, weight: weight), ]), ], ), AppEntryRole.agentSections.entry( themeRole.description, AgentNote(agentNote), ), ]; ``` `fontFiles` maps each weight of the font to its file in the app, and `fontLicenseFile` is the license. With the files in the brick, the app gets no package for the font and loads none from the network. The license is an asset of the app, so that each copy of the app has it with the font. The note tells a coding agent where the colors and the font of the themes are, and what a change of the file must keep; see [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). ## What the role does itself The template of the role does the rest, the same with every provider. It gives the root `MaterialApp` its `theme`, its `darkTheme` and its `themeMode`, keeps the theme mode that the user selects, saves it in the preferences and restores it, and gives the settings screen an entry that selects it. So a provider: - keeps no mode of its own and adds no entry for the mode; - sets none of the three arguments of the root, each of which takes one value. `smf create` stops with an error on a module that sets one of them in an app with the role; - requires what the role requires, the preferences role. So an app with the provider has a module that provides the preferences, and the registry of the tests of the provider has one too. ## The context of the functions The context that the two functions get is the one of the root widget: below the root wrappers and above the root `MaterialApp`, so it has neither the theme nor the localizations of the app. A provider whose look is fixed leaves the context alone, as `material_theme` does. A provider whose look depends on state of its own, such as a color that the user picks, puts an inherited widget with that state among the root wrappers and reads it from the context in the two functions. The root rebuilds in the new look when that widget notifies. For a setting of its look, such a provider contributes an entry of its own to the settings screen, as [Add a setting](https://doc.saymyframe.com/extending/settings.md) shows. ## Tests The tests of a provider select a mode with `appThemeMode.choose(mode)` and read it from `appThemeMode.value`, whichever module provides the role; see [Theme](https://doc.saymyframe.com/guides/theme.md#in-tests). The contract harness checks that a provider generates the symbols its role requires and follows the rules of the role. See [Test a module](https://doc.saymyframe.com/extending/testing.md). SMF's CI checks the theme in running apps, with every provider of the role that SMF has: the root takes each mode that code chooses, the screens get a light theme in the light mode and a dark one in the dark mode, with the color schemes that the two functions return, and the next start has the mode that was saved. [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) lists these tests. # Provide sign-in Source: https://doc.saymyframe.com/extending/provide-auth The auth role splits sign-in between its provider and its template. A provider keeps the accounts of the users and knows who is signed in on the device, such as a backend with authentication. The template of the role owns what is the same with every provider: the session of the app, the mode, the list of the ways to sign in, and what happens to an anonymous user who gets an account. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md) describes what the app has. ## The service The template generates `lib/core/auth/auth_service.dart` with what a provider implements and what its calls fail with: | In the file | What it is | | --- | --- | | `AuthService` | The interface that a provider implements. | | `AuthUser` | A user as the provider knows them: a `uid`, which stays the same for as long as the user exists, `isAnonymous`, an `email` or `null`, and the `issuers` of the identities of the user at identity providers. | | `SignInCredential` | The credential of a way to sign in, a sealed class. `IdTokenCredential` is the one so far: the `issuer`, the `idToken`, and the `rawNonce`, the `authorizationCode` and the name of the user, when the identity provider gives them. | | `AuthFailure` | The failure of a call, the only thing that such a call throws: a `reason` and, for the developer of the app, a `developerHint` or `null`. | | `AuthFailureReason` | Why a call failed. | This is the interface, without its comments: ```dart title="lib/core/auth/auth_service.dart" abstract interface class AuthService { AuthUser? get currentUser; Stream<AuthUser?> get userChanges; Future<void> signIn({required String email, required String password}); Future<void> signUp({required String email, required String password}); Future<void> linkPassword({required String email, required String password}); Future<void> signInWith(SignInCredential credential); Future<void> linkWith(SignInCredential credential); Future<void> signInAnonymously(); Future<void> sendPasswordReset(String email); Future<void> signOut(); Future<void> deleteAccount({SignInCredential? fresh}); } ``` The code of the app does not call it. It signs in through `appSession`, which calls this service. ## The module A provider contributes its implementation as data of the role, an `AuthImplementation`, much as the providers of the other [service roles](https://doc.saymyframe.com/extending/role-provider.md#a-service-events-analytics-crash-reporting) contribute a `RoleImplementation`. The data of the auth role is an `AuthData`: the `AuthImplementation` of the provider, or a `SignInMethod` of a module with a [way to sign in](#ways-to-sign-in). This is the built-in [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md): ```dart @override ModuleDescriptor get descriptor => const ModuleDescriptor( id: id, description: 'Firebase Authentication with firebase_auth', kind: ModuleKinds.infrastructure, dependsOn: {FirebaseCoreModule.id}, uses: {localizationRole}, providers: [_FirebaseAuthProvider()], ); @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution( firebaseAuthBundle, vars: { 'email_language': const RoleVar( localizationRole, present: _emailLanguage, absent: '', ), // For the script that enables the ways to sign in: the file // that it reads the mode of the app from, how the auth role // says to read it, the mode with anonymous users, and the // Firebase CLI that it asks for. 'session_file': AuthRole.sessionFile, 'mode_declaration': modeDeclarationCode, 'anonymous_mode': AuthMode.anonymous.name, 'minimum_firebase_cli': firstFirebaseCliWithSignIn, }, ), const PubspecContribution.hosted('firebase_auth', '^6.7.0'), authRole.data( const AuthImplementation( type: TypeRef('FirebaseAuthService', import: _file), create: FactoryRef('createFirebaseAuthService', import: _file), ), ), const Preflight([firebaseCliWithSignIn]), enableSignIn, AppEntryRole.agentSections.entry( authRole.description, AgentNote(agentNote), ), ]; ``` - A provider contributes one implementation. Its function is in the file of the implementation and takes no arguments. An implementation that is created asynchronously uses `AuthImplementation.async`, and `initAuth()` of the role awaits it. - What the service keeps to is the same in every mode of the app. A provider that renders something by the mode reads the mode in its render hook, with `authRole.modeIn(input)`. `firebase_auth` has a provider of its own, `_FirebaseAuthProvider`, for the ways to sign in of the app: its `validate` hook refuses a way to sign in that it cannot take, and its render hook writes the README section of the module and gives the script of the app the ways to sign in that it sets up. A tool of the app that follows the mode reads it from the app; see [a tool that reads the mode](#a-tool-that-reads-the-mode). - The brick of `firebase_auth` reads `email_language`, a [variable that depends on a role](https://doc.saymyframe.com/extending/templates.md#variables-that-depend-on-a-role). In an app with the localization role it is the code that gives Firebase the language of the app, and elsewhere it is empty. - The `Preflight` and `enableSignIn` are the check and the step with which the module enables the sign-in methods in the Firebase project after generation; see [a step with a notice](https://doc.saymyframe.com/extending/infrastructure-module.md#a-step-with-a-notice). - A provider tells in a README section of its own what its side needs for a mode, such as how anonymous users are enabled. The role writes the section "Sign-in", whose heading is `AuthRole.readmeHeading`, and the section of a provider can refer to it. - The note of the provider goes under `authRole.description` in the guide for coding agents, after the note of the role; see [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). The role uses the router role and the localization role, and a provider uses what its role uses. So the hooks of a provider may read the routes and the guards of the app, and the contract harness builds the apps of a provider with each router of its registry and without one, and with the localization role and without it. Put a router and a provider of the localization into the registry of the tests of a provider. ## Ways to sign in A module that requires the role, or its provider, may give it a `SignInMethod`: a way to sign in with an identity provider, such as Google. It has the label and the icon of its button, the platforms that it works on, the function of the module that asks the identity provider for a credential, the issuer of the tokens of the identity provider, whether a deletion asks it again (`revokesOnDeletion`), what it is for the App Store, and what it `needs` of the backend, such as the SHA of the keys of the Android app. The template lists the ways to sign in of the app in `appSignInMethods`, and a provider reads them in its hooks with `authRole.methodsIn(input)`. [`google_sign_in`](https://doc.saymyframe.com/modules/google-sign-in.md) and [`apple_sign_in`](https://doc.saymyframe.com/modules/apple-sign-in.md) give such ways. A provider takes the credentials of the ways to sign in that its backend takes: - It meets what each way to sign in `needs` of its backend, such as with a script of the app, or tells in its section of the README how to. - What no command can set up, it lists as [steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#steps-that-depend-on-the-data-of-a-role) from its `manualSteps` hook, as `firebase_auth` does for Apple and for the SHA of the keys of a release. - It reports in its `validate` hook a way to sign in whose identity provider its backend does not take, with the module of the way to sign in as the origin, so that `smf create` leaves that module out. - Its service fails a credential that it does not take with `notConfigured`, with the issuer in the hint. The module rule `auth.methods` checks the ways to sign in of a module: only a module that requires or provides the role gives one, with a label, platforms, an issuer of an https URL, an icon and a function in files that the bricks of the module generate, and each issuer once. The structural rule `auth.method_functions` checks that the function is a top-level function of the files of the module that takes no arguments, returns a `Future` of a credential that may be `null`, and whose file does not use `appSession`. `auth.method_icons` checks that the icon is a class of the files of the module with a `const` unnamed constructor that takes no arguments. ## A tool that reads the mode A provider whose side has to be set up for the mode may give the app a tool for that, a script that `dart` runs. `firebase_auth` generates one, `tool/enable_firebase_sign_in.dart`, which enables anonymous users in the Firebase project only in the mode `anonymous`. Such a tool cannot take the mode from the render hook of the provider: that is the mode that the app was generated in, and it is stale from the first time the developer of the app changes `authMode`. It cannot import the file of the session either, which imports Flutter. So it reads the declaration from the text of that file, and the role says how: | | | | --- | --- | | `AuthRole.modeDeclaration` | The source of a regular expression for a search over the lines of the file, as `RegExp(AuthRole.modeDeclaration, multiLine: true)`. Each match is a comment of the file, or a declaration of `authMode` that starts its line and has a mode as its value. Only a declaration has the first group, the name of its mode. | | `authRole.modeWrittenIn(source)` | The mode that the text of the file declares, or `null` when the text does not tell it: it has no declaration that the expression takes, or more than one. | The file tells the mode when exactly one match has the first group. A tool stops otherwise, and does not guess. - The expression takes the declaration as the template writes it, `const AuthMode authMode = AuthMode.required;`, and as a developer may leave it: without the type, with `final`, with its value on the next line, and with a comment after it. - It takes no value that is not the name of an `AuthMode`, no computed value, no declaration within a comment, and none that does not start its line. - The comment of `authMode` in the app tells the developer to keep the declaration in that form. A script of the app has only the libraries of Dart, so the expression goes into it as code. `firebase_auth` gives its brick the expression as a variable, and the files of the module stay the same in every mode. ## What the role does itself The template of the role does the rest, the same with every provider: - It generates `lib/core/auth/app_session.dart` with `appSession`, the session of the app, the constant `authMode`, and `initAuth()`, which creates the service with the function of the provider and starts the session with it. `bootstrap()` awaits `initAuth()` in its platform phase, so who is signed in is known before the first frame. - The session runs its calls one after another and turns every error that is no `AuthFailure` into one, with the reason `unknown` and the error as its `developerHint`. - For an anonymous user, the session calls `linkPassword` in place of `signUp`, so that the user keeps the id. Before an anonymous user signs in to an account that exists already, it takes the data of the guest, and it gives that data to the account afterwards, as `lib/core/auth/guest_data.dart` of the app says. - `appSession.signInWith` gives an anonymous user the identity of a credential with `linkWith`, so the user keeps the id. When that fails with `credentialInUse` or `accountExistsWithOtherMethod`, it signs in to the account that has the identity with `signInWith` and the identical credential object, moving the data of the guest. A user of an account, or someone signed out, signs in with `signInWith` at once. - For an account with a way to sign in that `revokesOnDeletion` and works on the platform, `appSession.deleteAccount()` calls the function of that way to sign in itself and gives the credential to `deleteAccount(fresh:)`. When the function returns `null`, the call deletes nothing. - It renders `appSignInMethods` and warns, as `auth.no_equivalent_sign_in`, of an iOS app with a login service of a third party and no way to sign in that the App Store takes as its equivalent. - In the mode `anonymous`, the session calls `signInAnonymously` when the app starts without a user, waits for it for at most 3 seconds, and tries again each time the user comes back to the app and after each call that leaves nobody signed in. - It asks for the mode, writes it into the app, and writes the section "Sign-in" of the README of the app and the note of the role in the guide for coding agents. - It publishes `AuthRole.account`, the [condition](https://doc.saymyframe.com/concepts/conditions.md) of a route whose screen is only for the user of an account, and warns when routes ask for it and no guard of the app stands for it. So a provider keeps no session of its own and declares no guard. A widget of a provider signs in through `appSession` too. ## What every provider keeps to The contract of `AuthService` is in the comments of `lib/core/auth/auth_service.dart`. It is the same in every mode of the app, whatever the provider renders by the mode: - The function of the implementation returns a service whose `currentUser` is the user of the device already, without a request to the server. It may be called again, and the service that it returns then has the user who is signed in now. A test runs `initAuth()` again to see what the next launch of the app finds. - When a call completes, `currentUser` is its result. `userChanges`, a broadcast stream, tells of every change of `currentUser`, also of one that no call made, and when it tells of a user, `currentUser` is that user. An error that the stream sends changes nothing: the session reports it with `FlutterError.reportError` and goes on listening. - Every failure is an `AuthFailure`, and every call ends. When the server does not answer, the call fails with the reason `network`. - `signIn` is also called while a user is signed in, an anonymous one or the user of another account, and `signUp` while the user of another account is. The user of the call then replaces that user on the device. - A wrong password and an address without an account are both `invalidCredentials`, and `sendPasswordReset` completes whether the address has an account or not. So nobody learns from the app which addresses have an account. - `signUp` and `linkPassword` with an address that has an account fail with `emailInUse` and change nothing. - A call that fails leaves the user who is signed in as that user was. An anonymous user stays signed in when `linkPassword` fails, and so does whoever is signed in when `signIn` or `signUp` fails. - `signInAnonymously` creates a user with an id of its own, and `linkPassword` and `linkWith` keep the id of the user. - `linkWith` of an identity that another user has fails with `credentialInUse`, and of one whose email address has an account of another user with `accountExistsWithOtherMethod`, and changes nothing. It keeps what its backend answered for that credential object, such as a credential to sign in with, without holding the token longer than needed. The session passes the identical object to `signInWith`, which uses that answer, or the credential itself when the backend gave nothing, since an identity provider may take a credential only once. `firebase_auth` keeps the answer of Firebase in an `Expando` keyed by the credential object. - A credential whose identity provider the provider does not take fails with `notConfigured`, with the issuer in the hint. - `deleteAccount(fresh:)` signs the user in again with the credential first, and revokes the tokens of the identity provider where it can. A credential of another user fails with `invalidCredentials`, and a revocation that fails with `notConfigured`, and neither deletes anything. - `currentUser` lists the `issuers` of the identities of the user. - `deleteAccount` deletes the user who is signed in, an anonymous one too, and signs out. It succeeds for a user who has just signed in, and for an anonymous user who was just created. For a user who signed in longer ago, such as one whom the service found on the device, it may fail with `recentSignInRequired`, and it succeeds once the user has signed in again. The role has no call that asks for the password again. - `linkPassword` and `deleteAccount` are calls for the user who is signed in. Made when nobody is signed in, such a call fails with `recentSignInRequired`. Made for a user whose session has ended on the server, it signs that user out on the device first and then fails with the same reason. That is the one case in which a call that fails changes who is signed in. | Reason | When a call fails with it | | --- | --- | | `invalidCredentials` | The email address and the password match no account. | | `emailInUse` | The email address has an account already. | | `credentialInUse` | The identity of a credential belongs to another user, in `linkWith`. | | `accountExistsWithOtherMethod` | The email address of the identity of a credential has an account of another user. | | `weakPassword` | The provider takes no password as weak as this one. | | `invalidEmail` | The text is no email address. | | `userDisabled` | The account is disabled. | | `tooManyAttempts` | The provider takes no more attempts for a while. | | `network` | The device did not reach the provider. | | `recentSignInRequired` | The call needs a user who signed in a short while ago, or the session of the user has ended on the server. | | `notConfigured` | Sign-in is not set up at the provider, such as a way to sign in that is not enabled there. The `developerHint` explains the mistake in the setup. | | `unknown` | Anything else. The `developerHint` has the error. | A package may promise less than the role, and the implementation then makes up the difference. The firebase_auth package keeps a deleted user as its current one until the platform tells it of the sign-out, so `FirebaseAuthService` signs out after it deleted a user. [`firebase_auth`](https://doc.saymyframe.com/modules/firebase-auth.md#what-the-service-adds-to-the-package) lists what else it does. ## Rules The structural rules of the role read what each Dart file of an app imports and calls: | Rule | What it requires | | --- | --- | | `auth.factory_calls` | No file of a module, and none of the template of another role, calls `createAuthService()`. Of such files, only those of the implementation of the provider, the files of its class and of its function, import or export the file of `AuthService`. | | `auth.start_calls` | Only the file of `bootstrap()` calls `initAuth()`, and no file of a module or of the template of another role calls `appSession.start()`. | | `auth.implementation_factories` | The function of the implementation is in its file and takes no arguments. | | `auth.method_functions`, `auth.method_icons` | The function and the icon of every way to sign in; see [ways to sign in](#ways-to-sign-in). | The module rule `services.implementations`, which the role shares with the other service roles, checks that a provider, and only a provider, contributes one implementation. The rules do not see a `part` file of a library that imports the file of the session, a file that reaches that file through an export of another file of the app, or `appSession` under another name, such as a variable that it was assigned to. ## Tests The contract harness checks the rules above, and builds the apps of a provider in each mode of the role; see [Test a module](https://doc.saymyframe.com/extending/testing.md#the-modes-of-a-role). Only a running app shows whether a provider keeps to the contract of the service. SMF's CI checks that in running apps, in every mode, with every provider of the role that SMF has. The test of the role calls the service of the provider through `createAuthService()`, takes `appSession` through a sign-up, a sign-out, a sign-in and the deletion of the account, and runs `initAuth()` again to see what the next start finds. CI runs the same test on two providers with a known bug, and it must fail on each: one that returns its service before it has read who is signed in on the device, and one that gives an anonymous user a new id in `linkPassword()`. In an app with ways to sign in, a second test, `auth_methods`, checks the credentials: what `signInWith`, `linkWith` and `deleteAccount(fresh:)` of the service do with a credential of each issuer of the app, that `userChanges` tells of each change that they make, and what the session does with the function of each way to sign in. It must fail on a third provider with a known bug, whose `linkWith` gives an anonymous user a new id. [Contributing](https://doc.saymyframe.com/contributing.md#the-roles-at-run-time) lists these tests. The mocks of a provider take test tokens in the tests of an app, whatever their issuer among those of the app: - A test token is a JSON Web Token without a signature, whose header has `alg` none and whose payload has `iss`, the issuer, `sub`, the identity at the identity provider, maybe `email`, and the `nonce` of its request, if the request had one. A token of a request without a nonce has none, as Google sign-in started without one gets it. - The nonce of a token is the `rawNonce` of its credential, or the SHA-256 hash of that `rawNonce` in lowercase hexadecimal, as a way to sign in whose request has the hash gets it, such as Sign in with Apple. Where its backend checks the nonce, a provider refuses a token whose nonce is neither. - A token with a nonce may be taken once: a provider refuses a token whose nonce it took already with `invalidCredentials`. The one exception is the credential object that `linkWith` refused just before, which `signInWith` takes with what the provider kept for it. - A credential of the issuer of a way to sign in that `revokesOnDeletion` has an `authorizationCode` of its own. The mocks of the module of a way to sign in issue such tokens, of one identity of their own and the same each time. The tests that a provider keeps for what only it does use the implementation of its own module, as those of `firebase_auth` use `createFirebaseAuthService()`, and check what reaches its platform side. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#in-tests) describes what a test of the session can do. # Define a role Source: https://doc.saymyframe.com/extending/new-role A role describes a part of an app that more than one module could implement, so that other modules can count on it without naming the implementation. The built-in roles live in `smf_contracts`. A role of yours lives in a package of its own, which its providers and the modules that use it depend on. Make a part a role when other modules count on it, even if a single module provides it today, so that another provider can join later without a change to the modules that use the part. The sockets of a module are for what only makes sense with that one module, and only the modules that depend on it directly fill them; see [Write an infrastructure module](https://doc.saymyframe.com/extending/infrastructure-module.md#building-on-another-module). The examples come from the fixtures of `smf_pipeline`, which define two roles outside `smf_contracts`. Continuous integration generates apps with them and analyzes those apps. ## The role class A role is a subclass of `Role<D>` with a single constant instance. `D` is the type of the data that modules give the role, and a role that takes no data uses `NoDsl`. ```dart /// The clock role; see [ClockRole]. const clockRole = ClockRole._(); /// The clock of the app, with the time zones the modules ask for as data /// and the ticks of the modules as a socket. final class ClockRole extends Role<String> { const ClockRole._(); /// Statements that run on every tick, in `tick()`. static const ticks = SocketRef<CodeSocket>.role( clockRole, 'ticks', CodeSocket(), ); /// `Clock createClock()`, which every provider generates. static const createClock = RequiredFunction( 'createClock', path: 'lib/core/clock/clock_factory.dart', returnType: 'Clock', ); @override String get id => 'clock'; @override String get description => 'Clock'; @override RoleCardinality get cardinality => RoleCardinality.atMostOne; @override List<SocketRef> get sockets => const [ticks]; @override RoleInterface get interface => const RoleInterface( files: ['lib/core/clock/clock.dart'], symbols: [createClock], ); @override RoleTemplate<String> get template => const _ClockTemplate(); } ``` | Member | What it declares | | --- | --- | | `id` | A lower snake_case id, unique among the roles and modules of a command. It names the presence flag `has_clock`, the tags of the role's sockets, and the owner `role:clock` of the template's files. | | `description` | The name of the role in the questions of `smf create`, such as "Clock: which module provides it?". The messages of `smf create` name the role by it, followed by "role", in lower case unless it starts with an acronym, such as "the clock role". | | `cardinality` | `exactlyOne`, `atMostOne` or `many` providers in an app. A role with exactly one provider is added to every app. | | `requires`, `uses` | Roles that must be present with this one, and roles it works with when present. The hooks of the role and of its providers can read their data. Every provider requires and uses them too. | | `sockets`, `socketFamilies` | The places where other modules put code (see [Sockets and contributions](https://doc.saymyframe.com/concepts/sockets.md)). A family has one socket per key, such as the annotations of each screen of the router. | | `interface` | The files that the role's template generates, and the symbols that every provider must generate, such as `createClock()`. `providerFiles` lists files that every provider must generate and that no symbol can name, such as the images of the app icon role. | | `options` | Options of `smf create` that the role reads, such as `--start` of the router. An option whose every value makes another app is a [mode option](#a-mode-option). | | `template` | The code of the role that does not depend on its provider. | | `moduleRules`, `structuralRules` | Checks of the modules and of the generated code. | The symbols are functions, classes and extensions at the top level of the file at their `path`. A function or a class is callable the way other code calls it: with its `positionalArguments` and `namedParameters`, and no other required parameters. A `RequiredFunction` also returns its `returnType`, if it has one. The parameters of a `RequiredClass` are those of its unnamed constructor, which is `const` when `constConstructor` is set, and the class declares each of its `getters` itself, as a public instance field or getter, since other code reads them from its instances. An inherited member does not count. The layout role requires `AppShell` this way, with the getters `destinations`, `currentIndex` and `onSelect`. A `RequiredExtension` is an extension on the type that its `on` names, which declares each of its `getters` as an instance getter. Other code never calls an extension. It names the extension only to show or to hide it in an import, and reads the getters from the objects that the extension is on. The localization role requires the extension `AppTexts` on `BuildContext` this way, with the getter `l10n`, so that every module reads a text as `context.l10n.<getter>`. The contract harness checks the symbols in the app of every provider. `openToAllModules` makes the sockets and symbols of a role usable by every module without declaring it. Only the app entry is open. Keep a role of yours closed, so that a module that uses it has to say so. ## Data A module that declares the role gives it data in the role's type: ```dart clockRole.data("Europe/Kyiv's zone"), ``` Data applies only when the role is present, and only its hooks see it, so a module that only uses the role can contribute data unconditionally. The hooks get the data of every module, in the order the modules were chosen, with the module that contributed each. Choose a type that describes what modules need rather than how a provider implements it, the way the router takes the routes of a feature and not go_router code. ## The template The template contributes the files of the role's interface and renders what depends on the data. Its hooks run at four stages of the pipeline: | Hook | Stage | Does | | --- | --- | --- | | `contribute(context)` | Collection | Returns the template's own contributions, such as the brick with the interface. | | `validate(input)` | Validation | Checks the data of all modules together and returns problems. | | `manualSteps(input)` | Validation | Returns the [steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#steps-that-depend-on-the-data-of-a-role) that depend on the data, such as a step in a web console that only some of the data needs. | | `choose(context)` | Choices | Asks the user, or reads the role's options, for a decision the data leaves open. | | `render(input)` | Rendering | Returns fragments for sockets, variables for the template's bricks, and files whose paths depend on the data. | ```dart final class _ClockTemplate extends RoleTemplate<String> { const _ClockTemplate(); @override List<Contribution> contribute(ModuleContext context) => [BrickContribution(clockRoleBundle)]; @override RoleOutput render(RoleHookInput<String> input) => RoleOutput( vars: { 'zones': [ for (final data in input.data) SmfNames.dartString(data.value), ].join(', '), }, ); } ``` The template's brick holds the interface and the tag of the role's socket: ```dart title="bricks/clock_role/__brick__/lib/core/clock/clock.dart" /// The clock of the app. abstract interface class Clock { /// The time zones the modules of the app asked for. List<String> get zones; } /// The time zones the modules of the app asked for. const clockZones = <String>[{{{zones}}}]; /// Runs the ticks of the modules of the app. void tick() { {{{smf_clock__ticks}}} } ``` The hooks of different roles never see each other's results, because all data is collected before `validate` runs. A hook reads only the data of its own role and of the roles its role requires or uses. A brick has the same files in every app. When the number of the files, or their paths, depend on the data of the role or on its choice, the render hook returns them in `RoleOutput.files`, each as its text by its path in the app; see [Files of render hooks](https://doc.saymyframe.com/extending/templates.md#files-of-render-hooks). ### What a template contributes A template contributes like a module. Besides its bricks, it can put code into the sockets of the app entry and of the roles that its role requires or uses, give those roles data, and add dependencies. The template of the theme role keeps the theme mode this way, whichever module provides the theme: ```dart @override List<Contribution> contribute(ModuleContext context) => [ BrickContribution(themeRoleBundle), AppEntryRole.agentSections.entry( themeRole.description, AgentNote.ofRole(_agentNote), ), // ... the scope around the root, and its theme, darkTheme and themeMode. const SocketContribution.item( PreferencesRole.restorers, Fragment('restoreAppThemeMode', imports: [_themeMode]), ), // The entry of the settings screen, with its texts: only an app with // a settings screen gets the file of the entry, and only then does // the app need the texts. BrickContribution( themeRoleSettingBundle, when: const {settingsScreenRole}, ), settingsScreenRole.data( const SettingsEntry( widget: TypeRef( 'ThemeModeSetting', import: ImportRef.app('core/theme/theme_mode_setting.dart'), ), ), ), localizationRole.data( TextsData([..._texts.values]), when: const {settingsScreenRole}, ), ]; ``` - The role lists the preferences role in `requires`, and the settings screen role and the localization role in `uses`, so its template may contribute to them. - A file that only some apps have is a brick of its own, contributed with `when`, as the entry of the settings screen is here. - The template reads its texts with `localizationRole.expressionOf` in its render hook; see [Texts](https://doc.saymyframe.com/extending/texts.md#texts-of-the-template-of-a-role). - `AgentNote.ofRole` adds the note of the role to the guide for coding agents of the app, under the description of the role. It tells what holds whichever module provides the role: where the files of the role are, how code uses it, and what code must not do. It names no provider and no package, which a test checks with [`roleNoteProblems`](https://doc.saymyframe.com/extending/testing.md#the-notes-of-roles). Only the template of a role contributes such a note, and a provider adds a note of its own under the same heading; see [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents). [How settings work](https://doc.saymyframe.com/concepts/settings.md#the-theme-mode-a-setting-of-a-role) describes the theme role as an example, and [Provide the theme](https://doc.saymyframe.com/extending/provide-theme.md) what is left for its provider. ## Choices and options When the data leaves a decision open, `choose` makes it. It reads the role's options and, in a run that can ask, asks the user. The router chooses the start screen this way: its `choose` takes `--start` when given and returns the only start candidate when there is one. Otherwise it asks, or, in a run without a terminal, throws an `SmfUsageException` that names the option. A role whose `choose` asks must also implement `optionsOf(choice)`, which returns the option values that make the same choice without asking, such as `--start /home`. The contract harness answers the questions of a role like a user who presses Enter, then checks that these options reproduce the answer in a run without a terminal, so choices must compare by value. What a role chooses reaches the render hooks of its template and of its providers, as `RoleHookInput.choice`. The contributions of a module are the same whatever the role chose, but for a brick or data of a role under a [condition on the choice](#a-condition-on-a-choice). ### Warnings A choice may leave the app other than the user may expect, such as an app that no route starts. The hook then reports a warning through `RoleChoiceContext.warn`, with a code of its own role: ```dart /// The code of the warning that no route can start the app, which then /// starts on the fallback start screen of the app entry role: the app has /// routes, but none is a start candidate and `--start` names none. static const noStartWarning = 'router.no_start'; ``` ```dart context.warn( SmfIssue.warning( 'No route is marked as a start candidate, so the app starts on ' 'its fallback screen. Choose a start route with ' '--${RouterRole.startOption.name}.', code: RouterRole.noStartWarning, ), ); ``` - A code is the id of the role, a dot and a name in lower snake_case, so that it says which role reported the warning and two roles never report the same code. The role publishes each code as a constant, and a test or a tool names a warning by its code rather than by its message. The codes that start with `pipeline.` are the pipeline's own. - The pipeline stops on a warning with a code of another role or of another form. It reports the warnings of a hook as warnings of the template of the role, once the hook has chosen, and `smf create --strict` stops on them before the app is rendered; see [lenient and strict](https://doc.saymyframe.com/guides/smf-create.md#lenient-and-strict). - A warning that depends on the data alone comes from `validate` instead, which runs before the machine is checked. Its `SmfIssue.warning` takes a code too. - A hook does not warn through the logger of its environment, whose warnings have no code: the contract harness reports that as an error of the template. A warning about the machine, `SmfIssue.machineWarning`, is for the checks of the pipeline alone. ### A condition on a choice Some files belong only in the apps where a role chose something, such as a screen that only an app without a start route needs. `when` tells only which roles an app has, so a role publishes a condition on its choice as a constant instead, a `ChoiceCondition`. The router publishes `RouterRole.noStartRoute`, which holds in an app that no route starts, and in an app without a router. The clock role of the fixtures could publish one for its hours: ```dart static const twelveHours = ChoiceCondition( clockRole, 'the clock shows 12 hours', holdsFor: _showsTwelveHours, withoutRole: false, ); bool _showsTwelveHours(Object? choice) => choice == '12'; ``` A module that uses the clock then contributes the files of a dial with 12 hours only to the apps that need them, with `BrickContribution(dialBundle, whenChosen: {ClockRole.twelveHours})`. A `BrickContribution` and data of a role take `whenChosen`, and so does a symbol of the interface of a role. `AppEntryRole.fallbackStartScreen` is required only where `RouterRole.noStartRoute` holds, and an app where it does not hold must have no file at its path. So every provider of the app entry contributes the screen under that condition, as `flutter_core` does. - A condition names a role that the contributor provides, requires or uses, as `when` does, and for the template of a role the role itself or a role that it requires or uses. - Data of a role takes no condition of the same role, which chooses from its data. Conditions on the data of roles must not form a cycle, since neither role could choose first. - A brick with conditions holds no tag of a socket: an app where the conditions do not hold leaves the brick out, and what the socket got would be lost with it. - The contract harness answers the questions of a role as a user who presses Enter. So it checks both sides of a condition only when the data of the modules or a mode option drives the choice. ### A mode option Some options change what kind of app is generated: an app that every user signs in to is another app than one that lets a guest in. A role declares such an option as a mode option, `RoleOption.mode`, with a closed list of values. The clock role of the fixtures has one for the hours that its clock shows: ```dart /// `--clock-hours`, how many hours the clock shows: 24, the default, or /// 12. static const hoursOption = RoleOption.mode( name: 'clock-hours', help: 'How many hours the clock of the app shows: 24, the default, or ' '12.', values: ['24', '12'], ); ``` With a mode option, the role states four things, and the contract harness holds its template to them: | What the role states | What it means for the template | | --- | --- | | The code of the app depends on the value. | The render hooks of the template and of the providers read the choice. | | The first value is the default, the value of an app that got none. | `choose` takes the value that the option gives, and the first one when the option is not given. Without a terminal it neither fails nor asks for the lack of the option, and at its question a user who presses Enter gets the first value too. | | The option reproduces every choice. | `optionsOf` gives the option with its value for every choice, also for one that the template made without asking. | | A run in a terminal and a run without one make the same choice. | The choices compare by value. | So no run needs the option, and a script written before the role had it generates the same app. This is the template of the clock role: ```dart @override Future<Object?> choose(RoleChoiceContext<String> context) async { const option = ClockRole.hoursOption; final values = option.allowed!; final given = context.option(option.name); if (given != null) return given; final environment = context.environment; if (!environment.interactive) return values.first; return environment.prompter.select( 'How many hours does the clock show?', values, defaultValue: values.first, ); } @override Map<String, String> optionsOf(Object? choice) => {ClockRole.hoursOption.name: choice! as String}; ``` The value reaches the code of the app in three ways: - The template of the role reads the choice in its render hook and writes it into a file of the role as a constant, here `clockHours`. - A provider reads it in its render hook, through a function that the role offers, here `clockRole.hoursIn(input)`, and renders the code of that value alone. - A module that is no provider has no hook, so its code is the same in every app. It reads the constant when the app runs and branches on it. Every value gets apps in the tests. The harness builds one more app of each provider of the role for each value after the first; see [Test a module](https://doc.saymyframe.com/extending/testing.md#the-modes-of-a-role). The values become part of the names of those apps. So a command refuses a registry with a mode option that has fewer than two values, a value twice, or a value that is not of lower-case letters and digits with single hyphens between them; see [a command of your own](https://doc.saymyframe.com/extending/publishing.md#a-command-of-your-own). Among the built-in roles, the auth role has a mode option, `--auth-mode`, with the values `required`, `guest` and `anonymous`. Its template writes the choice into the app as the constant `authMode`; see [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#the-mode). ## Rules Module rules run in the validation stage, for every module that declares the role, over the role's data and the module's contributions. The router checks there that the routes of a module have valid paths and parameters, and that the template of every screen has its annotation tags. Structural rules run in the contract harness, over the text of every generated file and an index of every Dart file with its imports, declarations, calls, property accesses and constructors. A call comes with the declaration and the member it is in, and a method with its parameters. The DI role checks there that only composition files call `resolve`, and the app entry role that the root `MaterialApp` is created in the `build` of a widget. A structural rule sees the data of its own role. With `StructuralRuleInput.inputOf(role)` it also reads what the hooks of another role of the app get, when that role requires or uses the role of the rule. The localization role does this to tell which texts the template of such a role may read: its own, and those in the data that the modules give it. `inputOf` throws for a role that does not build on the role of the rule, and for a role that the app lacks. A rule is a constant with an id, a sentence that says what it requires, and a top-level function that returns problems. A problem names the module at fault, so that `smf create` can leave that module out. A role can also have rules for the modules of a kind, such as the file where they may resolve services. The role defines each as a subclass of `KindRule`, and a kind lists those that its modules follow in `ModuleKind.roleRules`. A check of the role reads the one it needs from the kind of a module with `ruleOf<T>()`, which returns `null` when the kind lists none. The pipeline applies none of these rules itself. The DI role defines `CompositionFile` this way, and `ModuleKinds.feature` lists `CompositionFile('lib/features/<id>/<id>_composition.dart')`. ## Conditions for routes A role that knows something that only some screens of an app need can publish it as a [condition for routes](https://doc.saymyframe.com/concepts/conditions.md), a constant of its class. The badge role of the fixtures publishes two: ```dart /// What a user needs for the routes of the holders of a badge. A module /// that requires the role says whether the user holds one, with a guard /// of the routes that stands for the condition. static const holder = RouteCondition(badgeRole, 'holder'); ``` A feature then asks for the condition on a route, and a module that requires or provides the role declares the guard that stands for it. The two know the role and not each other; see [Write a feature module](https://doc.saymyframe.com/extending/feature-module.md#a-route-that-asks-for-a-condition). - The role generates nothing for a condition. In the app, the guard has the names of the routes that ask, which the router role collects. - The function of the guard is in a file of the module that declares the guard. The template of the router role imports the files of the modules that give it data, and no file of the template of another role. So the role offers what such a function returns, as the auth role offers `appSession.hasAccount`, and the module wraps it in a function of its own. - An app may have no guard for a condition. Its routes that ask then show like any other, and the router role reports nothing. A role that wants to warn of such an app requires or uses the router role. Its hooks then read the routes and the guards of the app through `routerRole.facadeOf(input)`. The auth role does so in the `validate` hook of its template: ```dart List<SmfIssue> _openAccountRoutes(RoleHookInput<RoleImplementation> input) { final facade = routerRole.facadeOf(input); final asking = facade.routesAsking(AuthRole.account); if (asking.isEmpty || facade.guardFor(AuthRole.account) != null) { return const []; } // ... a warning that names each route of `asking`. } ``` A role that uses the router role this way makes every provider of it use the router role too. So the contract harness builds the apps of such a provider with each router of its registry, and without one. ## Providers and users of the role A provider lists `RoleProvider.plain(clockRole)` in its providers when its bricks alone implement the role, and subclasses `RoleProvider<String>` to validate the data or render it (see [Provide a role](https://doc.saymyframe.com/extending/role-provider.md)). A module that uses the role declares it in `uses`. It names the role in the `when` of the contributions whose code refers to the role's symbols. Its templates refer to those symbols only inside `{{#has_clock}}`, or through [a variable whose code depends on the role](https://doc.saymyframe.com/extending/templates.md#variables-that-depend-on-a-role). The fixtures define a second role, `badgeRole`, and a module that uses both adds this line to start-up only in an app with a badge: ```dart SocketContribution.code( AppEntryRole.bootstrapLate, Fragment( 'debugPrint(createBadge().labels.join());', imports: [ const ImportRef('package:flutter/foundation.dart'), BadgeRole.createBadge.importRef, ], ), when: const {badgeRole}, ), ``` # Templates Source: https://doc.saymyframe.com/extending/templates The files a module adds to an app are [mason](https://pub.dev/packages/mason) templates, bundled into Dart, and the pipeline renders them in memory with mustache. A template can use the variables below, and the pipeline checks the rules that follow. Most of these rules exist so that a module never breaks an app it cannot see. ## Variables A template can read: | Variable | Value | | --- | --- | | `app_name` | The package name of the app, such as `my_app`. mason's case lambdas work on it: `{{app_name.titleCase()}}` is `My App`. | | `org_name` | The organization, such as `com.example`. | | `has_<role>` | `true` when the role is present. It is set for the roles the brick's owner provides, requires or uses, and for the app entry. | | socket tags | The rendered contributions of a socket, such as `{{{smf_app_entry__bootstrap_late}}}`. | | variables of render hooks | What the owner's render hooks return in `RoleOutput.vars`. | | the brick's own variables | The `vars` of its `BrickContribution`: plain data, or code that depends on the presence of a role. | Mustache renders a variable that none of these sets as nothing, so the pipeline reports it. The brick's own variables and the variables of render hooks cannot take the names that the pipeline or mason sets: `app_name`, `org_name`, `smf_…`, `has_…`, the case lambdas of mason, such as `snakeCase`, and its brace variables, `__LEFT_CURLY_BRACKET__` and `__RIGHT_CURLY_BRACKET__`. Mustache escapes a variable in two braces for HTML, so code and paths with a slash go in three: `{{{name}}}`. ## Presence flags Code that refers to a role the module only uses goes inside the section of its presence flag. `flutter_core` switches the root widget on the router this way: ```dart MaterialApp{{#has_router}}.router{{/has_router}}( title: '{{app_name.titleCase()}}', {{#has_router}}routerConfig: appRouter.config,{{/has_router}}{{^has_router}}home: const FallbackStartScreen(),{{/has_router}} ``` An import that only one branch needs goes into the same section: ```dart {{#has_router}}import 'core/router/app_router.dart';{{/has_router}}{{^has_router}}import 'core/app/fallback_start_screen.dart';{{/has_router}} ``` A flag is set only for the roles the owner declares, and the pipeline reports a section over a flag it does not set. A flag tells only whether a role is in the app. A file that belongs only in the apps where a role chose something goes into a brick of its own, contributed with `whenChosen`. The fallback start screen is such a file: without a router, the condition `RouterRole.noStartRoute` holds, so the root widget above, in an app without a router, always has the screen that it imports; see [a condition on a choice](https://doc.saymyframe.com/extending/new-role.md#a-condition-on-a-choice). ## Variables that depend on a role A template whose code differs with a role needs two branches under the presence flag of the role, around the code and again around its import. A variable of the brick with a `RoleVar` does the same with one line of the template. It has the code for an app with the role and the code for an app without it. The fixtures of `smf_pipeline` have a module that reads the time zones of a clock role this way: ```dart BrickContribution( fakeClockUserBundle, vars: { // One line of the template for the apps with the clock and for // those without it; only the first get the import. 'clock_zones': RoleVar( clockRole, present: Fragment( 'createClock().zones', imports: [ClockRole.createClock.importRef], ), absent: 'const <String>[]', ), }, ), ``` ```dart List<String> clockUserZones() => {{{clock_zones}}}; ``` In an app with the clock, the function returns `createClock().zones` and the file imports the file of `createClock()`. In an app without it, the function returns `const <String>[]`. The pipeline takes the value by the presence of the role, as it applies a contribution by its `when`. - The role is one that the contributor provides, requires or uses. - Each value is code: a `Fragment` with the imports that the code needs, or a string of code that needs none. A `RoleVar` holds no plain data for mustache, such as a list or a boolean. A template tests the presence of a role with its presence flag. - The variable is a fragment variable in every app, whichever value the app gets. A template reads it as it is, `{{{clock_zones}}}`, and not in a path. When either value has imports, only a Dart library may read it. The pipeline adds the imports of the value that the app gets to every Dart file of the brick that reads the variable. - A template reads it outside every mustache section, the section of the presence flag of another role included. Code that needs a second role goes into a brick of its own, contributed with `when` of that role. - A line that holds nothing but the variable goes away in an app whose value has no code. - Only the whole value of a variable of a brick is a `RoleVar`: it is no item of a list or a map. The variables of a render hook take none, since a hook asks for the presence of a role with `input.has(role)`. `localizationRole.varsOf` makes such variables for the texts of a module: `context.l10n.<getter>` in an app with the localization role, and the English text in an app without it. See [Texts](https://doc.saymyframe.com/extending/texts.md). ## Socket tags A template marks a socket with its tag in three braces, `{{{smf_<owner>__<name>}}}`: - A tag stands outside mustache sections. The socket renders whatever the app has, and its contributions carry their own `when`. - A socket whose contributions carry imports, such as a code socket, has its tag in exactly one Dart file, which gets the imports. Only the tag of a socket for one value, such as the minimum iOS version, may appear several times. - Both tags of a wrapper, `…_open` and `…_close`, are in the same file, the opening one first. - The tag of a socket that renders whole lines, such as the native sockets and the README sections of the app entry, stands alone at the start of its line. - A tag must not come right after a `{`, which mustache would read as part of the tag. Put the parameters of a constructor on lines of their own, as the tags of parameter annotations need. - A line that holds nothing but a tag that gets nothing goes away with it, so an empty socket leaves no blank line. The owner of a socket must hold its tag in its templates: the role's template or its provider for a socket of a role, and the module for a socket of its own. The tag of a member of a family, such as the annotations of a screen, goes into the file of the module whose data creates it. ## Variables of render hooks A render hook returns variables for the bricks of its owner in `RoleOutput.vars`. They are plain data, such as strings, numbers, booleans and lists and maps of them, or a `Fragment` of code with imports: - A template reads a fragment variable as it is, `{{{routes}}}`, outside mustache sections. A path cannot read one. - A fragment variable with imports can be read only by a Dart library, not by a part file or a file that is not Dart. The pipeline adds the imports to every file of the owner that reads it. - A line that holds nothing but a fragment variable without code goes away. - A fragment variable that no template of its owner reads is an error, since its code would be lost. - A variable that two hooks of one owner, or a hook and a brick of the owner, both set is an error. ## Files of render hooks A brick has the same files in every app. A file whose path depends on the data of a role or on its choice, such as one file for each item that the modules give the role, comes from a render hook instead, of the template of the role or of its provider. The hook returns it in `RoleOutput.files`, as the text of the file by its path from the root of the app, with forward slashes. [`gen_l10n`](https://doc.saymyframe.com/modules/gen-l10n.md) generates the ARB file of each language of the app this way. In the fixtures of `smf_pipeline`, the provider of a clock role generates a Dart file for each time zone that the modules ask for, and gives its brick the imports of those files: ```dart @override RoleOutput render(RoleHookInput<String> input) { final zones = [ for (final (index, data) in input.data.indexed) (number: index + 1, name: data.value), ]; return RoleOutput( vars: { 'zone_constants': Fragment( [for (final zone in zones) 'clockZone${zone.number}'].join(', '), imports: [ for (final zone in zones) ImportRef.app('core/clock/zones/zone_${zone.number}.dart'), ], ), }, files: { for (final zone in zones) 'lib/core/clock/zones/zone_${zone.number}.dart': '/// A time zone that a module of the app asked for (fixture).\n' 'const clockZone${zone.number} = ' '${SmfNames.dartString(zone.name)};\n', }, ); } ``` The pipeline takes such a file as it is, text and path. It renders no mustache in it, fills no tag of a socket and adds no import, and mason does not read it. Once the app is written, `dart fix` and `dart format` go over a Dart file among them as over the rest of the app. Otherwise it is a file of the app like those of the bricks: - Its owner is the owner of the hook, the template of the role or the module of the provider, and the contract harness, with its checks of imports, sees it like any other file. - The path is inside the app, and is not of a file that belongs to one machine or one build. - The file of a provider is where the kind of its module may generate files. - Every file of the app is generated once. A path that a brick or another hook generates too is an error, also when the paths differ only in case. The path comes from data, which the author of the hook does not see as the author of a brick sees its paths. So two more rules hold: - Every machine can write the file. The path has no control character or line break and none of `< > : " | ? *`, which Windows allows in no name of a file, and no segment of it ends with a dot or a space. - A path of the app is a file or a directory, not both. A file where another file of the app has a directory, or inside what is a file of the app, is an error, whatever the case of the paths. What every app of the owner has stays in a brick. ## Imports A fragment never imports anything itself. It lists the imports it needs, and the pipeline adds them to the file that holds the tag, merged with the imports of other fragments and sorted. `ImportRef.app('core/router/app_router.dart')` imports a file of the app by its path below `lib/`. After rendering, the pipeline runs `dart fix` for unused and duplicate imports, so a template may import a library that only some of its branches use. ## Paths The path of a file in a brick is its path in the app. A path may use variables, such as the directory of the Kotlin package of the app, `{{{android_package_path}}}`, but no mustache sections or partials. Files that only some apps get go into a brick of their own, which the module contributes with `when` or in a variant. Files whose number or paths depend on the data of a role come from [a render hook](#files-of-render-hooks). Every file of the app has exactly one owner, so two bricks, or a brick and a render hook, must not generate the same path. A brick must not contain files that belong to one machine or one build, such as `.dart_tool/`, `build/`, `GeneratedPluginRegistrant` files, `.iml` files or signing keys, and the pipeline rejects them. ## What mason would change - mason removes a backslash that comes right before a line break or a non-ASCII character, in templates and in everything it renders into them. The pipeline rejects such a backslash in fragments and variables. - The pipeline rejects a template that changes the mustache delimiters or includes a partial. - mason copies a text file without any tag as it is, and a binary file too. - Bricks have no hooks, and the pipeline rejects a bundle with mason hooks. # Test a module Source: https://doc.saymyframe.com/extending/testing `smf_pipeline` has a library for the tests of modules, `package:smf_pipeline/testing.dart`, with three tools. The contract harness generates every app that matters for a module in memory and checks it against the rules of the module model. `ModulePackage` checks what the package of a module imports and depends on, and `roleClassNameProblems` checks that its code takes the names of the classes of roles from the roles. The built-in modules test themselves with the harness and `ModulePackage`, and the tests of the CLI run `roleClassNameProblems` over all of them. Use all three for yours. A package that defines a role has a fourth, `roleNoteProblems`, for the note of the role in the guide for coding agents. ## The contract harness ```dart title="test/counter_module_test.dart" import 'package:smf_bloc/smf_bloc.dart'; import 'package:smf_counter/smf_counter.dart'; import 'package:smf_flutter_core/smf_flutter_core.dart'; import 'package:smf_gen_l10n/smf_gen_l10n.dart'; import 'package:smf_get_it/smf_get_it.dart'; import 'package:smf_go_router/smf_go_router.dart'; import 'package:smf_pipeline/smf_pipeline.dart'; import 'package:smf_pipeline/testing.dart'; import 'package:smf_riverpod/smf_riverpod.dart'; import 'package:smf_shared_preferences/smf_shared_preferences.dart'; import 'package:test/test.dart'; void main() { test('every app of the module follows the rules of its roles', () async { final harness = ContractHarness( ModuleRegistry(const [ FlutterCoreModule(), GoRouterModule(), GetItModule(), BlocModule(), RiverpodModule(), // The localization, which the counter uses for the label of its // tab, and the preferences that the localization requires. GenL10nModule(), SharedPreferencesModule(), CounterModule(), ]), ); final results = await harness.checkAll(); for (final result in results) { expect(result.errors, isEmpty, reason: '${result.contractCase}'); } }); } ``` The registry has a module for the localization, which the counter uses for the label of its tab, and one for the preferences, which the localization requires. Without them the harness builds no app of the counter with that role, and a counter that lists the role and forgets to give it the label passes. With them the test reports the mistake: "The module gives the router role the text "label" in its data, but not the localization role, so the app would show it in English in every language." `checkAll()` builds a case for every module and every role of the registry. For a module, it builds an app for every combination of a provider of the role of its variants and a provider of each role it requires. It repeats this for each subset of the roles that the module only uses, the largest first, with a provider of each role of the subset in the combination too. A combination that would give the app two providers of a role that takes one is left out, such as one with another router for a module that depends on `go_router`. When no combination for a subset can be in an app with the module, the harness keeps them all, and their cases report why. A case is named after its module, the provider of each role that has several in the registry, and the roles of its subset. For the counter above, the cases are `counter (bloc)` and `counter (riverpod)`, without the localization that it only uses, and `counter (bloc) with localization` and `counter (riverpod) with localization`. If the counter also used the analytics role, and the registry had two providers of it, one of its cases would be `counter (bloc, firebase_analytics) with analytics`. It also builds a case of the module with each provider in the registry that brings a package which the module adds, itself or in a variant, when the two can be in one app (see [the packages of a provider](https://doc.saymyframe.com/extending/role-provider.md#the-packages-of-a-provider)). The case is named `<module> with <provider>`, such as `banner with bloc` for a module without variants that adds `flutter_bloc`. When the provider provides another role than that of the module's variants, the case is `<module> (<provider of the variant>) with <provider>`, one for each variant that adds the package, or for the first variant when only the module itself adds it. A case whose app another case builds already is left out. For each case, the harness runs the stages of the pipeline up to rendering, the way a run without a terminal that skips external setup would. It answers the questions of the roles like a user who presses Enter, and renders the app in memory. Then it checks, among other things: - the rules of the module's kind, the access rules of sockets and roles, and the roles in `when`; - the module rules of every role, and its structural rules over the parsed Dart files of the app; - that every provider generates the symbols its role requires, and no file at the path of a symbol whose condition on a choice does not hold in the app, such as the fallback start screen of the app entry in an app that a route starts; - the tags of the sockets in the templates, and templates that mustache would copy with their braces; - that every import finds its file and every imported package is a dependency of the app; - that a module imports only the files it may use: its own, those of the modules it depends on directly and those of its roles. The imports of a template count for the module of the template, and an import that the pipeline adds for a fragment counts for the module of the fragment, as the errors say with "in the template of …" and "for a fragment of …"; - that only what a render hook of a role gives imports the files of the modules that give the role data, such as the screens that a router routes: a fragment of the hook, or a file that the hook generates. That holds for the template of a role and for its providers. The template of a brick gets no such allowance, and neither does a contribution for a fragment of its own, since both are the same whatever the modules give the role; - that a module which imports or exports the package of a provider of a role in the app, in a template or for a fragment, adds that package itself, even when it depends on the provider. A provider of a role may import, for a fragment or in a file that its render hook generates, the package that a module which gives the role data adds, as the data may need it; - that no file of the app, of a brick or of a render hook, is at a path where code generation or the localizations of Flutter write their files once the app is rendered; - that each path that the guide for coding agents of the app names, below a top-level directory of a Flutter project or to a Dart file, is a file or a directory of the app. The files that a render hook generates are files of the app like those of the bricks, and the harness checks them the same way. The result of a case also has the warnings about what its app is made of, in `ContractResult.warnings`, each with its code. The harness makes the choices of every app once more without a terminal, and reports a role whose warnings differ there. It also reports a `choose` hook that warns through the logger, whose warnings have no code, and a structural rule that warns. So a test of a module can expect the warnings of an app by their codes, such as `router.no_start` for an app of a feature that marks no route as a start screen: ```dart expect( result.warnings.map((warning) => warning.code), [RouterRole.noStartWarning], ); ``` What the registry holds decides what the harness can check, so put these modules into it: - `FlutterCoreModule`, the app entry that every app needs; - every module that your module depends on, which the registry requires anyway; - every provider of a role your module requires or uses that you want it checked with, since the harness builds an app with each, such as `SharedPreferencesModule` for a module that keeps a setting, `SettingsModule` for one with a row on the settings screen and `GenL10nModule` for one with texts. Such a provider needs what it requires in the registry too: `SettingsModule` a router, such as `GoRouterModule`, and `GenL10nModule` the preferences. [Add a setting](https://doc.saymyframe.com/extending/settings.md#test-the-module) has such a registry; - every provider that your module has a variant for, which the registry requires as well; - the provider of every package that your module adds and that a provider of a role brings, such as `RiverpodModule` for a module that adds `flutter_riverpod`. SMF allows the package of a provider only in a variant for that provider or with a dependency on it, and `smf create` checks this only in apps that have the provider. With the provider in the registry, `checkAll()` builds such an app of your module, so your tests find the mistake rather than a user of your module. `harness.uncheckedProviders()` lists, one line each, the providers that no case checks a module with. Each is a provider of a role that a module of the registry requires or uses, and it can be in an app with the module, but no app of the module's cases has it as the provider of that role. That happens when the apps with the provider do not resolve, such as when no module of the registry provides a role that the provider requires. Expect the list to be empty, as the tests of the CLI do. Each module then stays checked with every provider of its roles, also when a role gets another provider: ```dart expect(await harness.uncheckedProviders(), isEmpty); ``` ## The modes of a role A role can have a [mode option](https://doc.saymyframe.com/extending/new-role.md#a-mode-option), each value of which makes another app, as `--auth-mode` of the auth role does. For such a role, `checkAll()` builds one more case of each provider of the role for each value of the option after the first. It is the first case of the provider, which has every role that the role uses, with the value among the options of the case, and its name ends with `--<option>=<value>`. With `firebase_auth` and a router in the registry, these are `auth by firebase_auth with router --auth-mode=guest` and `auth by firebase_auth with router --auth-mode=anonymous`. The other cases leave the option out, so their apps have its first value. So the tests of a provider of such a role render its hook for every value, and a second provider gets these cases without a change of the tests. The harness reads the options from the roles of its registry and names no role itself. In every app with such a role that it renders, the harness makes the choices twice: in a terminal, where it answers as a user who presses Enter, and without one, as `smf create --no-input` makes them. It reports a role: - whose choice with a value of the option is not that value, or whose choice without the option is not the first value; - whose two choices differ; - that fails or asks in the run without a terminal. It also reports a value that a case gives an option which does not take it, since the command line would refuse it. `harness.casesOfModes()` has the cases of the apps with every module, those of `casesOfAll()`, once more for each other combination of the values of the mode options of the roles of each app. SMF's CI generates apps from them; see [Contributing](https://doc.saymyframe.com/contributing.md#generated-apps). An option that you give every case, with `ContractHarness(registry, roleOptions: {...})`, has that value in every app and no cases of its own. ## Checking one app `harness.check(case)` builds one app and returns its result, whose `app` holds the rendered files: ```dart final result = await ContractHarness(registry).check( const ContractCase('counter', requested: [CounterModule.id, BlocModule.id]), ); final screen = result.app!.files['lib/features/counter/counter_screen.dart']!; ``` `ContractCase` takes the modules to request, the provider to pick for a role with several, and the values of role options in `roleOptions`, such as `{'start': '/counter'}` or `{'auth-mode': 'guest'}`. Check the rendered code as code rather than as text, by parsing it with the analyzer and looking for the declarations and calls you expect. Your module does not know which module provides a role, and its tests should not either. So they check what the module gives a role through the role, and not in the files that the provider of the role renders: `lib/core/router/app_router_factory.dart` of the router, `lib/core/di/dependencies.dart` of the DI container, `lib/core/layout/app_shell.dart` of the layout, `lib/core/l10n/l10n.dart` and the files of the texts, such as the ARB files of `gen_l10n`, the screen of the module that provides the settings screen, and `lib/bootstrap.dart`, `lib/main.dart` and `lib/app.dart`, into which the provider of the app entry renders the start-up and the root of the app. Another provider renders them differently. The result gives two views of the app that do not depend on the provider: - `result.hook` is the `RoleHookRequest` of the app: the data of the roles, the roles that are present, the context of the harness and the choices of the roles, as the hooks of the roles got them when the harness rendered the app. A role builds the input of its hooks from it with `hookInput`, so a test reads the data as every provider of the role gets it. `diRole.graphOf(diRole.hookInput(result.hook!))` has the registrations of the services, `routerRole.startIn(routerRole.hookInput(result.hook!))` the route that the router role chose to start the app on, and `layoutRole.destinationsIn(layoutRole.hookInput(result.hook!))` the destinations of the main navigation. In the same way, `settingsScreenRole.entriesIn` has the entries of the settings screen, in the order the screen shows them, `localizationRole.textsIn` the texts of the app with their getters, `localizationRole.localesIn` its languages, and `authRole.modeIn` the sign-in mode that the auth role chose. - `result.app!.socketOrders` has the contributions of every socket that got any, in the order that the pipeline rendered them into the tags of the socket, including the fragments of the render hooks. What the modules and the templates of the roles put into the platform phase of the start-up is in `socketOrders[AppEntryRole.bootstrapPlatform]`, whichever module renders `bootstrap()`. ```dart final registrations = diRole.graphOf(diRole.hookInput(result.hook!)).registrations; final platform = result.app!.socketOrders[AppEntryRole.bootstrapPlatform]!; final startUp = [ for (final collected in platform.contributions) (collected.contribution as SocketContribution).fragment!.code, ]; ``` `result.app!.entriesOf(socket)` gives what a keyed socket got, in the order the socket got it: the contributor, the key and the value of each entry. With it a test reads the notes of the guide for coding agents, each with the heading of its section, without reading `AGENTS.md`. This finds the note of the preferences role in the app of a result: ```dart final ofRole = [ for (final (origin, _, note) in result.app!.entriesOf(AppEntryRole.agentSections)) if (origin == const RoleTemplateOrigin(preferencesRole)) note.text, ].single; ``` The tests of the built-in modules check where the note of their module is: in the section of its role, after the note of the role, or in a section of its own. For the names of code that a note tells agents to use, they check that the note gives each name in inline code and that a file of the app declares or uses it, with `DartFileIndexer` of `package:smf_pipeline/testing.dart`. What a sentence of a note says about the code, only a test of that code can pin. `result.manualSteps` has the steps by hand of the app, each once with its contributors, in the order that its README lists them; see [Steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#in-tests). When a test compares the app of your module with the app without it, the files of the providers of its roles differ too, since they render the data of your module. Tell those files apart by their owner rather than by their paths: a rendered file whose `owner` is a module among `result.resolution!.providersOf(role)` belongs to a provider of that role. A module whose tests need a main navigation, but which is not a feature itself, can declare small features and a layout of its own in `test/`, as `smf_firebase_analytics` does in `test/support/navigation.dart`. ## The rules of a module package ```dart title="test/architecture_test.dart" import 'package:smf_pipeline/testing.dart'; import 'package:test/test.dart'; void main() { test('the package follows the rules of a module package', () { expect( const ModulePackage( 'smf_counter', dependencies: {'mason'}, testModules: { 'smf_bloc', 'smf_flutter_core', 'smf_gen_l10n', 'smf_get_it', 'smf_go_router', 'smf_riverpod', 'smf_shared_preferences', }, ).problems(), isEmpty, ); }); } ``` `problems()` reads the package in the current directory, which is the package's own when `dart test` runs, and reports every package and import that breaks a rule: - The code in `lib/` imports only the module model of `smf_contracts`, its own files, the public libraries of its `dependencies`, and libraries of Dart that do not reach the machine, which rules out `dart:io`. - Of the module packages, the tests use only the module model, the package itself, its dependencies, `smf_pipeline` and the `testModules`. - The package depends on `smf_contracts` and its `dependencies` and on nothing else. Its dev dependencies among the module packages are `smf_pipeline` and the `testModules`. The module packages are `smf_contracts`, `smf_pipeline` and every package that depends on `smf_contracts`, whatever its name. `problems()` recognizes them by their pubspecs, which it finds through the package config that `dart pub get` writes, in the directory of the package or in the root of its workspace. When the package config is missing, or the pubspec of a package that it has to check, the problems ask you to run `dart pub get`. pub.dev resolves the dev dependencies of a package when it analyzes it, so the dev dependencies between module packages must not form a cycle. When two modules would need each other in their tests, one of them tests with a small provider of its own in `test/`. ## The names of the classes of roles A role can require a class, such as the `AppShell` that every layout generates, or the `Destination` that the template of the layout role generates. A module that generates code which creates such a class takes the name from the role, as in `'${LayoutRole.appShell.name}('`, so that the generated code follows the role. `roleClassNameProblems(roles)` reads the package in the current directory and the module packages it depends on, and reports each string in their `lib/` that spells out the name of a class of those roles followed by `(`, with its path and line: ```dart test('the code takes the names of the classes of roles from the roles', () { expect(roleClassNameProblems(ModuleRegistry(modules).roles), isEmpty); }); ``` Here `modules` are the modules of the registry of your tests. Comments, code outside strings, such as the `Destination(...)` of a route, and the bundles in `lib/bundles/`, which the bricks generate, do not count. `roleClassNameProblems` finds the module packages as `ModulePackage` does, and asks you to run `dart pub get` when the package config is missing. ## The notes of roles The template of a role adds the note of the role to the [guide for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents), and the note has to hold whichever modules provide the roles. A package that defines such a role checks it with `roleNoteProblems`, in the apps of the results of the harness: ```dart test('the notes of the roles name nothing of their providers', () async { final results = await ContractHarness(ModuleRegistry(modules)).checkAll(); expect( roleNoteProblems( results, AppEntryRole.agentSections, textOf: (note) => note.text, ), isEmpty, ); }); ``` The check holds each note of a role against the providers of every role in those apps, and against the modules that they depend on. The note may have none of their ids or packages. In its code, it may name nothing that only their files declare, and no file that only they generate. What the roles guarantee is free, such as the symbols of their interfaces. The check knows a module only from the generated files, so it takes a name of Flutter that only files with one package have for a name of that package. Pass such a name in `allowed` with the reason, as in `allowed: {'NavigatorObserver': 'A class of Flutter.'}`. Do the same when a line is about a note of `smf_contracts`, which you cannot change. The check also reports an entry of `allowed` that excuses nothing. ## Beyond the harness The harness renders apps but does not build them. To see your module in a real app, generate apps with your command, as [Extending SMF](https://doc.saymyframe.com/extending.md#how-a-module-reaches-an-app) shows, with each state manager and each provider your module works with, and run `flutter analyze` on them. SMF's CI does this for the built-in modules. A module with a [guard](https://doc.saymyframe.com/extending/feature-module.md#a-guard) keeps the user from every other screen until its guard allows. So a test that starts an app with the module sees only the flow of the guard, unless it first puts what the guard reads into the state that allows, as a test in an app with [`onboarding`](https://doc.saymyframe.com/modules/onboarding.md#in-tests) does. A module whose guard asks for an account opens it for such a test by signing an account up before the app starts, as the tests of the apps with [`sign_in`](https://doc.saymyframe.com/modules/sign-in.md) do. A call of `appSession` made before the start-up waits for it, and the start-up completes after such calls. So the test calls `appSession.signUp()` before `bootstrap()`, without awaiting it, and the app starts with that account. It makes the call outside the body of a test, as in a `setUpAll`: made in the body of a widget test, the call waits in the fake time of that body, and a start-up that runs in real time never completes. [Sign-in](https://doc.saymyframe.com/guides/sign-in.md#in-tests) has more on tests of the session. A test that starts an app runs as its default flavor, `dev`, since `flutter test` takes no `--flavor`. A test of a module with a Firebase service needs a mock of the platform side of that service, and the options of `dev` stay a placeholder otherwise. A module that makes requests goes through `appRest`, and a test of it gets a local server from `RestTestServer` of `test/core/rest/rest_test_server.dart`, or scripts the answers with `appRest.use(transport: …)`. [REST API](https://doc.saymyframe.com/guides/rest.md#in-tests) tells what `flutter test` does to a request. A module with a `PostGenStep` that writes into the native projects, as a provider of the app icon does, shows the result only once the step has run. Neither the rules nor a snapshot see it, so its tests read the files of an app that `smf create` generated, as an app test of its module. A module that remembers a setting has more to show in a running app: that a choice is saved, and that the next launch reads it. [Preferences and settings](https://doc.saymyframe.com/guides/preferences.md#in-tests) describes both checks, which hold whichever module provides the preferences. A module whose generated code is plain Dart can go further in its tests. It can write the rendered files to a temporary directory with the packages of the tests, analyze them and run them in the Dart VM. The tests of `smf_get_it` and `smf_event_bus` run the generated services with the real get_it and event_bus this way. ### The state of a variant The state of a screen is close to plain Dart even when the screen is not: a cubit or a notifier uses little of Flutter. So the tests of a feature with [variants](https://doc.saymyframe.com/extending/feature-module.md#a-look-that-the-variants-share) can run the state of each variant with the Dart SDK alone, as the tests of `smf_sign_in` do: - They write the Dart files of a rendered app to a temporary directory, with stand-ins for what the state uses of Flutter, such as `ChangeNotifier` and `ValueListenable` of the foundation library. - The package of each state manager is a stand-in too, which exports the package it builds on: `flutter_bloc` exports `package:bloc/bloc.dart`, and `flutter_riverpod` exports `package:riverpod/riverpod.dart`. Both are plain Dart, and the package of the module has them as dev dependencies. - A script of the test imports the state of a screen and no widget, gives the session a service that it scripts, and runs in the Dart VM. The same scenarios run with each variant: a call that is on its way, a failure, a second call, a user who leaves the screen. So the tests of the package need no Flutter SDK. The widgets need more of Flutter than a stand-in gives, so the analyzer checks them, and they run in the tests of generated apps. # Rules for modules Source: https://doc.saymyframe.com/extending/rules Use this checklist when you write or review a module. The pipeline or the contract harness checks most of these rules. The others keep modules independent, which is what lets any combination of them work. ## Independence - A module knows only the modules in its `dependsOn`, and the roles it provides, requires or uses. It never learns which other modules the app has. - A module never refers to what another module generates, such as a class, a file or a package, unless it depends on that module. Prefer a role whenever one describes what you need. - `contribute` depends only on the `ModuleContext`. What depends on another role goes into contributions with `when`, and what depends on the provider of a role goes into variants. - Code that refers to the symbols of a role the module only uses goes into contributions that name the role in `when`, and into templates only inside `{{#has_<role>}}` or as the value of a variable for an app with the role (`RoleVar`). Data for the role and code for its sockets apply only when the role is present, so they need no `when`. - The contributions of a module are the same whatever a role chose. A module that is no provider reads the mode of a role, such as `authMode` of the auth role, from the constant that the role generates, when the app runs. - Generated widgets talk only to their state, a Cubit or a provider, and never to the DI container or another service directly. ## The descriptor - The id is lower snake_case, unique among the modules of a command, different from the id of every role, and not `pipeline`. As a Dart name in lowerCamelCase, as in `context.nav.<id>`, it must not be a member of `Object`, such as `hashCode`. - Declare the id once, as a `static const` of the module class, and let other modules refer to that constant in `dependsOn`, so that the dependency is a pub dependency too. - `dependsOn` points one way. No module depends on itself, and the dependencies do not form a cycle. - A module has one provider object per role it provides, and does not also require or use a role it provides. - A module of a kind that must provide a role, such as a layout, provides it. - `selectedByDefault` is for a module with no role that a new app should have, such as a start screen. A run in a terminal offers it selected among the modules of its kind. It says nothing for a module that provides a role, where Enter takes the first provider, and a run without a terminal never takes a module that it was not given. - Variants are for a role that an app has at most one of, never for a role the module provides, and every key is the id of a module of the command that provides that role. Infrastructure has no variants. ## Kinds - A feature keeps its files in `lib/features/<id>/`, declares at least one route, and resolves services only in its composition file, `lib/features/<id>/<id>_composition.dart`. A feature that resolves services requires the DI role. - Infrastructure declares no routes, generates nothing in `lib/features/`, has no variants, and never resolves services. Its registrations list the services their factories take in `FactoryRef.deps`. - A layout provides the layout role, keeps its files in `lib/core/layout/` and declares no routes. Its `AppShell` keeps `destinations`, `currentIndex` and `onSelect` as public fields or getters, which code that knows only the role reads. It shows the label of a destination with `destination.label(context)` in the `build` of the widget that shows it, and keeps nothing of what it returned. - A kind of your own lists the file where its modules may resolve services as a `CompositionFile` in its `roleRules`, and a module that resolves services there requires the DI role. The modules of a kind without one resolve no services. ## Routes and screens - Paths are lowercase segments or `:<name>` parameters. A top-level path starts with `/` and is relative to the feature, and a child's path is relative to its parent. - Route and parameter names are lowerCamelCase. No route or parameter takes the name of a member of `Object`, such as `hashCode`, or of a `dart:core` type written in lowercase, such as `int`, and no parameter is named `key`, `path`, `parent`, `chain` or `routeName`. - Declare a route with a fixed segment before a route with a parameter in its place, so that the parameter does not take its locations. - The unnamed constructor of every screen is `const` and takes each parameter of its route as a named parameter of the same name. Its template has the tag of the screen's annotations before the class, and the tag of each parameter's annotations before the parameter. - Every screen is an UpperCamelCase class in a file of the app, which the route imports with `ImportRef.app`, without a prefix or `show`. A screen belongs to one route. - The label of a destination is a `LocalizedText`. A module that lists the localization role gives the role the same text, and a module that does not gives the label its English text alone. - A provider of the router gives the shell of the layout `appDestinations` of the layout role, and renders neither a label nor an icon of a destination. - A feature navigates only to its own routes and to those of the features it depends on. - A provider of the app entry builds the root of the app as a `MaterialApp`, or as a `MaterialApp.router` when the app has a router, so that every screen finds the theme and `MaterialLocalizations` above it. It creates the root in the `build` of a widget that `main()` runs inside the root wrappers, so that the arguments of the root can read the context below them. Its templates have the tags of `appBuilder` in the `builder` of the root in every app, since the app entry role puts a widget there itself, and `smf create` stops on a provider without them. ## Guards - A guard has a lowerCamelCase name of its own among the guards of its module. Its function is a top-level function of a file of the app that takes no arguments and returns a `ValueListenable<bool>`. - The value of a guard is known once `bootstrap()` has run, and it changes outside the build of a frame. - The target of a guard is a top-level route of its module that needs no values and is outside the main navigation. No route of its flow is a start candidate, and none asks for a condition. - A guard has the stage that its flow belongs to: `GuardStage.welcome` when the flow needs to know nothing of the user, and `GuardStage.identity` when it asks or needs to know who the user is. A guard that needs to know who the user is without asking it itself, as that of a subscription, allows while it cannot tell: the app may ask it before the guard that asks. - A guard whose next user should not come back to where the last one was, as after a sign-out, sets `resumes: false`. - A guard without a condition is a gate over the whole app. A guard with a condition keeps the user only from the routes that ask for it. Its module requires or provides the role of the condition and declares one guard for it at most. - Two guards with one flow, such as a gate and a guard of a condition that show the same target, read one notifier. - The routes of a flow show only while a guard with that flow does not allow. No code navigates into the flow of a gate: its module changes what the guard reads, and the router shows the target. - A screen neither closes itself nor navigates after it changed what a guard reads. The router has done both by then. - A route asks only for conditions of the roles that its module requires, uses or provides. Such a route is outside the main navigation and the flows of the guards of the module, and neither it nor a route below it is a start candidate. - A provider of the router asks the guards of an app that has them through the `GuardedNavigation` of the role, with the routes of the pages that the location is asked for on top of, and tells it of its pages when `guardChanges` notifies. It does what the class answers, `ShowInstead`, `ShowOver`, `ShowNothing` or `ClosePages`, and keeps the request that waits for a flow. - The answer depends on those pages. So a provider of the router never asks with no pages about a location that it shows over a page, nor about one that it goes to for a request that it asked about with the pages. A router whose redirect runs for its own navigation keeps those calls from the class. - A link to a page of the flow of a guard that stands for a condition opens that page over the screen that the app starts on. A screen opens such a page with `push()`. ## Sign-in - The code of a module, and of the template of another role, reaches sign-in only through `appSession`. It calls neither `createAuthService()` nor `initAuth()` nor `appSession.start()`, and it does not import the file of `AuthService`. - The mode of the app gates nothing on its own. A module with the screens of sign-in declares the guards, with functions of its own that return `appSession.allowsApp` and `appSession.hasAccount`. - A route whose screen is only for the user of an account asks for the condition `AuthRole.account`, and its module lists the auth role. - A provider of the auth role contributes exactly one `AuthImplementation` of `AuthService`, whose function is in its file and takes no arguments. Of its files, only those of the class and of the function of that implementation import the file of `AuthService`: a widget of a provider signs in through `appSession` too. - Every call of the service of a provider fails only with an `AuthFailure`, and what the service keeps to is the same in every mode of the app. - A tool of the app that follows the mode, such as a script of a provider that `dart` runs, reads it from the text of the file of the session, with `AuthRole.modeDeclaration`. It stops when the file does not tell the mode. - A way to sign in comes from a module that requires or provides the auth role, as a `SignInMethod` with a label, platforms, an issuer of an https URL, and an icon and a function in files of the module. Each issuer is the way to sign in of one module. The function returns a `Future` of a credential that may be `null`, takes no arguments and does not use `appSession`. The icon is a class with a `const` unnamed constructor without arguments. - A provider of the auth role reports in `validate` a way to sign in whose identity provider its backend does not take, and its service fails such a credential with `notConfigured`. ## Settings and preferences - The preferences are for settings, not for secrets. A token, a password, an API key or an encryption key never goes there: a secret belongs in the secure storage of the platform. - A module gets the preferences through a restorer that it gives `PreferencesRole.restorers`, or, in an app with a DI container, as a dependency of the factory of a service. It never calls `createAppPreferences()` or `initPreferences()`. - A restorer is synchronous and awaits nothing. It keeps the current value when nothing is saved under its key, keeps the preferences for the writes of its module, and may run more than once. - A key is `<module id>.<setting>`. - Widgets read and change a setting through the state of its module, never through the preferences. - The widget of a settings entry is a class in a file of its contributor, with a `const` unnamed constructor that requires no arguments. A module that only uses the settings screen role generates that file in a brick with `when: {settingsScreenRole}`. - A provider of the settings screen names one route of its own that needs no values as the screen. The screen shows every entry once, in the order of the role, and the provider creates the widget of each through an import of its file with a prefix of its own. - A provider of the theme generates `createLightTheme(context)` and `createDarkTheme(context)`, and keeps no theme mode of its own. In an app with the theme role, no module sets `theme`, `darkTheme` or `themeMode` of the root. ## Onboarding, notifications and push messages - A step of the onboarding comes from a module that uses the onboarding screen role, as an `OnboardingStep` with a lowerCamelCase name of its own among the steps of the module and an icon. Its `run` and `showIf` are top-level functions of files of the module: `run` takes the `BuildContext` of the onboarding screen and returns a `Future`, and `showIf` takes no arguments and returns a `bool` at once, without side effects. See [Add a step to the onboarding](https://doc.saymyframe.com/extending/onboarding-steps.md). - A provider of the onboarding screen names one route of its own that needs no values as the screen, and a file of it reads `appOnboardingSteps`. - Code reaches notifications only through `appNotifications`, and push messages only through `appPush`. It calls neither `createNotificationsService()` nor `createPushService()`, nor `initNotifications()`, `initPush()` or the `start()` of either. - A notification of the app has an id from 0 up. A notification with an owner names it under `notificationOwnerKey` and has a negative id. - A provider of the push role never asks for the permission to show notifications. ## Purchases and values in .env - Code reaches the purchases only through `appPurchases`. It calls neither `createPurchasesService()` nor `initPurchases()` nor `appPurchases.start()`, and only the files of the implementation of the provider import the file of `PurchasesService` (`purchases.factory_calls`, `purchases.start_calls`). - A provider of the purchases role contributes exactly one `RoleImplementation` of `PurchasesService`, whose function is in its file and takes no arguments (`purchases.implementation_factories`). Every call of its service fails only with a `PurchasesFailure`, and without what it needs, such as a key, with `notConfigured` and a hint. - A route whose screen is only for a user with premium access asks for the condition `PurchasesRole.premium`, and its module lists the purchases role. A module that requires the role stands for the condition with a guard of the stage `identity` whose function returns `appPurchases.hasPremium`. - A key of `.env` is an `EnvKey` of the module whose code reads it, or of the template of a role for a value that the template reads. Its name is in UPPER_SNAKE_CASE, of two words or more, starts with the id of the module or the role in upper case and an underscore, and never starts with `FLUTTER_`. Its description is one line of at most 100 characters without a backslash. Each key has a getter of its own (`env.keys`). - The files of a module read only its own keys and those of the modules it depends on, and the files of the template of a role read only the keys of that template (`env.key_access`). A provider of the role declares a getter of `AppEnv` for every key (`env.keys_rendered`), and only a provider gives the role tool arguments, at most once. - No secret goes into `.env`: every value ends up in the app, where anyone can read it. ## REST API, CI, the app icon and the splash screen - Code reaches the REST API only through `appRest`. No module calls `createRestTransport()`, and only the files of the implementation of the provider import the file of `RestTransport` (`rest.factory_calls`). No module calls `appRest.use()`, which is for tests (`rest.use_calls`). - A provider of the REST role contributes one `RoleImplementation` of `RestTransport`, created with the app, whose function is in its file and takes no arguments (`rest.implementation_factories`). - A provider of the CI role has, in its files other than Dart files and outside their comments, each command of the checks and of the preparation of a build at the end of a line, the command of the build and the file that it keeps, each with something that stands for the environment or once for every environment, and each environment and each key as a whole word (`ci.pipeline_rendered`). A value reaches a command only as a variable of the process. - A provider of the app icon role or of the splash role generates the two images of the role and has a `PostGenStep` that makes the result and that a run without a terminal runs too: neither external nor interactive, with no notice, and continuing no other step (`app_icon.step`, `splash.step`). ## Flavors - A module reads the names and the ids of the flavors from `AppEntryRole.flavors`, and writes none out. - A provider of the app entry has those flavors in each native project of the app, and `default-flavor` in the pubspec names one of them (`app_entry.flavors`). - In the template of `ios/Runner.xcodeproj/project.pbxproj` of a provider, each build configuration of the project has the tag of the minimum iOS version as its `IPHONEOS_DEPLOYMENT_TARGET`, and one of a target has that tag or no such setting (`app_entry.ios_deployment_target_tag`). - The README of a provider has the tag of `AppEntryRole.readmeSections`, since the template of the role writes the section on the flavors there. - A step that has to follow every run of a tool, for every flavor, is a Dart file of a directory that a script of the app runs, and not a `PostGenStep`, which runs once. See [Continuing a step](https://doc.saymyframe.com/extending/infrastructure-module.md#continuing-a-step). ## Warnings - A role reports a warning about what the app is made of with a code of its own, `<role id>.<name>`, which it publishes as a constant. A `choose` hook reports it with `RoleChoiceContext.warn`, never through the logger, and a structural rule reports no warning. ## Texts - A text that a user sees is a `LocalizedText` that its module gives the localization role, and a template reads it through a variable of `localizationRole.varsOf`. - The name of a text is a lowerCamelCase identifier of its own among the texts of the module. A text has an English text, translations by the code of their language, and no braces, and neither the English text nor a translation is blank. - A text in the data of another role, such as the label of a destination, is a text of the module too. Two such texts of one name are the same text: the app reads a text of a module by its name. - A template reads a text variable in three braces, outside mustache sections, where a `BuildContext context` below the root of the app is in scope, and not inside a `const` expression. - Code reads only the texts of its module and of the modules it depends on. The template of a role reads its own texts, and the texts in the data that the modules give its role or a role that it requires or uses, such as the labels of the destinations. - A module brings no delegate for texts of its own and adds no language to the root of the app. - A provider of the localization role renders a getter for every text of the app, in the languages of the app, with the English text where a translation is missing. ## Notes for coding agents - A note tells what the code of the app does not show. A module that provides a role adds its note under the description of the role, and a module without a role under a heading of its own. - A note is true in every app that has it. It names a file of the app by its path from the root of the app, and only a file that the app has. What it tells of a file that only some apps have is a contribution of its own, with the role of that file in its `when`. - Only the template of a role contributes `AgentNote.ofRole`, and such a note names no provider and no package. A provider that wraps a package or a tool opens its note with a line that names it, such as "With `go_router`:". ## Services - A registration's factory is a top-level function of its file that takes the services in `deps`. A dispose function takes the service. - A provider of the DI role renders every registration: its files call or tear off the factory of each registration and its dispose function. The contract harness checks this in the apps of every provider. - A provider of a service role contributes exactly one `RoleImplementation`, whose function takes no arguments. Only the DI container calls the functions that create the services of roles. The auth role, the notifications role, the push role and the purchases role register nothing in the container: code reaches them through `appSession`, `appNotifications`, `appPush` and `appPurchases`. ## Packages - The code in `lib/` imports only the module model of `smf_contracts`, its own files and the public libraries of its dependencies. It does not import `dart:io`, `dart:isolate`, `dart:ffi` or `dart:mirrors`. - The package of a provider of a role, such as `flutter_riverpod` of `riverpod`, goes into another module only through its variant for that provider, with the constraint `any`, or through a dependency on the provider. - A module that imports or exports the package of a provider adds that package itself, even when it depends on the provider. A provider of a role may import, for a fragment or in a file that its render hook generates, the package that a module which gives the role data adds. - A provider brings a package when it adds the package outside a variant with a constraint other than `any`, and the package is then the provider's. A package that no provider brings is shared, and every module that needs it adds it. A provider brings only the packages that implement its role and adds a shared package, such as `collection`, which Flutter pins, with `any`. See [The packages of a provider](https://doc.saymyframe.com/extending/role-provider.md#the-packages-of-a-provider). - Declare `PubspecContribution.environment` only when your package needs a newer Dart or Flutter than the app has anyway. - Dev dependencies between module packages do not form a cycle. ## Templates - Socket tags go in three braces, outside mustache sections, and a socket that carries imports has its tag in one Dart file. - Code and paths with slashes go in three braces, and no backslash comes right before a line break or a non-ASCII character. - Bricks have no mason hooks, partials or changes of the delimiters, and every file has one owner. - A variable with a `RoleVar` holds code for an app with a role and code for one without it. A template reads it in three braces, outside mustache sections. - A file that a render hook generates has a path inside the app that every machine can write, and no brick or other hook generates the same file. - Code that goes into `lib/bootstrap.dart`, through the phases of start-up or `topLevel`, imports neither `material` nor `cupertino`. - A brick with a condition on a choice, `whenChosen`, holds no socket tag. - A component of the Android manifest is declared once, by one module. The Swift statements of `iosAppDelegateLaunch` take no imports and are indented by four spaces, and the components by eight. See [Templates](https://doc.saymyframe.com/extending/templates.md) for the full list. ## The machine and commands - A preflight check only reads the machine. It never installs anything, logs in, asks the user or changes files other than its temporary files, and it never shows output that may hold a secret. - A check may need a tool that a check of a module that its module depends on installs, since those checks run first. It counts on no check of any other module. - A check is `required` only when the app cannot work without it. - A step after generation does not write the absolute path of its working directory into the app. It is `skippable` when the app is complete without it, `interactive` when it talks to the user, `external` when it needs something outside the app, and it `needs` the checks without which it would fail. - A step that does more than its description says tells the user in its `notice`, one line that reads on its own. Such a step is `skippable`, since the user may decline it. - A module continues, with `followUpOf`, only its own steps and those of the modules it depends on directly, which publish the ids of their steps as constants of their module classes. A step that continues another has no `when` of its own. The `id` of a step names the module that contributes it, and no other step of the app has that id. - On Windows, an argument of a batch file such as `dart.bat` has no `^`, `<`, `>`, `%`, `&`, `|` or `"`. - A step that only the developer of the app can do is a `ManualStep` of the module, published as a constant of its module class, or of a role when contributors that do not know each other share it. Its id never changes, and its title is one short line. A step that depends on the data of a role comes from the `manualSteps` hook, without `when`. An entitlement that only a paid Apple Developer team signs goes in with `AppEntryRole.paidTeamEntitlement`. See [Steps by hand](https://doc.saymyframe.com/extending/infrastructure-module.md#steps-by-hand). ## Tests - The tests of the module run the contract harness over a registry with `flutter_core`, the modules it depends on, every provider of a role it requires or uses that it should be checked with, and every provider it has a variant for. `uncheckedProviders()` of the harness is empty. - When the module adds the package of a provider of a role, the registry has that provider too, and `checkAll()` then checks an app of the module with it. - The tests check what the module gives a role through the role, in `result.hook` and `result.app!.socketOrders`, and not in the files that the provider of another role renders. That holds for its routes, its services, its settings entries and its texts alike. - The tests check the package with `ModulePackage`, and with `roleClassNameProblems` that its code takes the names of the classes of roles from the roles. See [Test a module](https://doc.saymyframe.com/extending/testing.md). # Publish and use a module Source: https://doc.saymyframe.com/extending/publishing ## Publish the package A module is a Dart package, so you publish it on pub.dev like any other, with `dart pub publish`. Before you publish: - bundle the bricks again and commit the bundles in `lib/bundles/`, which the package needs; - run the tests with the contract harness, `ModulePackage` and `roleClassNameProblems` (see [Test a module](https://doc.saymyframe.com/extending/testing.md)); - depend on the version of `smf_contracts` that the module is written for, such as `smf_contracts: ^0.8.0`; - publish the packages that your package depends on first, such as the package of a module in your `dependsOn` or of a role of your own, since a package on pub.dev can depend only on packages that are on pub.dev. ## A command of your own `smf` offers the modules in its own list. A command of your own adds your modules to that list. Create a small package that depends on `smf_flutter_cli` and on your module: ```yaml title="pubspec.yaml" name: my_smf description: smf with the counter feature. version: 0.1.0 publish_to: none environment: sdk: ^3.12.0 executables: my_smf: dependencies: smf_counter: ^0.1.0 smf_flutter_cli: ^0.8.0 ``` ```dart title="bin/my_smf.dart" import 'dart:io'; import 'package:smf_counter/smf_counter.dart'; import 'package:smf_flutter_cli/smf_flutter_cli.dart'; Future<void> main(List<String> arguments) async { final code = await runCli( arguments, modules: const [...smfModules, CounterModule()], ); await Future.wait<void>([stdout.flush(), stderr.flush()]); exit(code); } ``` `runCli` is the command line of `smf`. It takes the arguments, runs the pipeline on this machine with the modules you give it, and returns the exit code. `smfModules` is the list of the built-in modules, in the order in which the questions of `smf create` offer them, and your modules come after them. Run the command from the package, or activate it globally like any Dart command-line tool: ```bash dart run bin/my_smf.dart create my_app -m home,counter,bottom_tabs,bloc ``` The command has every option and question of `smf create`, and its help calls it `smf`. With `runCli(..., banner: false)`, it leaves out the note with links to the SMF community that follows a created app. The list of modules must form a valid registry, which the command checks before it parses the command line: - a module of the list provides the app entry, as `flutter_core` does; - the ids of modules and roles are unique, and every module in a `dependsOn` is in the list; - every key of a module's variants is a module of the list that provides the role. A command with a registry that breaks these rules prints the problems and exits with code 70. ## Propose it for SMF A module that many apps need, or a new provider of a built-in role, can become part of SMF itself. Open an issue first to agree on what the module does and how it fits the roles. See [Contributing](https://doc.saymyframe.com/contributing.md). # Contributing Source: https://doc.saymyframe.com/contributing SMF is developed in the open at [saymyframe/smf_flutter_cli](https://github.com/saymyframe/smf_flutter_cli). Bug reports and ideas go to [GitHub Issues](https://github.com/saymyframe/smf_flutter_cli/issues), and questions are welcome on [Discord](https://saymyframe.com/discord). This page is an overview, and the repository has the details. [CONTRIBUTING.md](https://github.com/saymyframe/smf_flutter_cli/blob/main/CONTRIBUTING.md) describes the process, and [AGENTS.md](https://github.com/saymyframe/smf_flutter_cli/blob/main/AGENTS.md) describes the layout, the rules and the conventions. AGENTS.md is written for coding agents, but it serves people just as well. ## The repository The repository is a Dart pub workspace managed with [Melos](https://melos.invertase.dev). Every package is versioned and published on its own. ```text packages/ smf_contracts/ the module model: modules, roles, sockets, contributions smf_pipeline/ the stages of smf create and the contract harness fixture_registry/ apps from the fixtures: their snapshots, their matrix and app tests, the app of several providers, and the apps of the providers with a known bug test/fixtures/ fake modules for features that no real module uses yet, and providers of roles with a known bug smf_modules/ smf_<module>/ the modules: flutter_core, go_router, home, ... smf_flutter_cli/ the smf command: its modules and the machine tools/ bundling of bricks, the banlist, the version of the CLI, the coverage check, and tests of the package graph and of CI ``` Dependencies point one way: `smf_contracts` ← `smf_pipeline` and the modules ← `smf_flutter_cli`. The pipeline knows no module and no concrete role, and modules use `smf_pipeline` only in their tests. ## Set up CI pins Dart 3.12.2, and the output of the formatter depends on the version, so use that Dart, with Flutter 3.44.2 for the apps. Then run: ```bash dart pub global activate melos dart pub global activate mason_cli melos bootstrap ``` `melos bootstrap` resolves the workspace and bundles every brick into `lib/bundles/` with the Mason CLI. The bundles are generated, so change the brick, bundle it again and commit both. CI fails when a committed bundle differs from its brick. ## Checks ```bash melos run check ``` runs, in this order: | Script | Checks | | --- | --- | | `melos run format:check` | The formatting of the Dart code of every package, its `app_tests/` and `example/` included, and of `tools/`. `melos run format` formats it. | | `melos run analyze` | `dart analyze --fatal-infos --fatal-warnings` in every package and in `tools/`. | | `melos run banlist` | That no file uses what the repository bans; see `tools/banlist.dart`. It bans, among other things, the names that the module model replaced, reading the `workspace:` key of the root `pubspec.yaml` by hand anywhere but in `tools/workspace_members.dart`, and, in the tests of a module, the paths and constants of the files that the provider of another role renders, such as `lib/core/di/dependencies.dart` or `lib/bootstrap.dart`. | | `melos run test` | The tests of every package and of `tools/`. The tests in `tools/` also check that the published packages, dev dependencies included, do not depend on each other in a cycle. pub.dev resolves the dev dependencies of a package when it analyzes it. | CI also measures coverage. The tests must run every line and take every branch of `lib/` in every package. To check it locally, install the coverage tool once with `dart pub global activate coverage`, then run: ```bash melos run test:coverage melos run coverage:check ``` `coverage:check` names each line and branch that no test reaches, as `path:line`. Code that no test can run, such as the terminal of a user, goes between `// coverage:ignore-start` and `// coverage:ignore-end`, with the reason in a comment. When a test of a package or of `tools/` fails in CI, the page of the run lists it at the top as an annotation with the name of the test, its message, and its file and line. Every run of tests in the workflows writes a JSON report to `build/test-results/` of the directory it runs in. A later step of each job with tests, which runs even when a step failed or the job was cancelled, reads those reports with `tools/test_annotations.dart` and prints an annotation for each test that failed, or that started and never finished. A test in `tools/` fails when a run of tests in a workflow writes no report, when two runs of a job write the same report, and when no later step of the job runs the tool with `if: always()`. Tests are hermetic. They use no network and no Flutter SDK, and they remove their temporary directories. A test of a tool that the app gets, such as the script of `firebase_auth` that enables the sign-in methods, runs it with a stand-in for the command that it calls, here the Firebase CLI. A few tests need more and skip themselves without it. The test of `smf_flutter_core` that compares its brick with an app that `flutter create` wrote needs that app, which the CI job `Brick of flutter_core` creates with the pinned Flutter. Two others run only in the jobs on macOS and Windows, described [below](#macos-and-windows). Two more run only when CI gives them an app that it configures with Firebase, described in [Starting the apps](#starting-the-apps): one of `smf_firebase_core`, which configures the app, and one of `smf_firebase_crashlytics`, which then fixes its build phase for Crashlytics on iOS. A test of generated code parses or analyzes it rather than comparing strings. A bug that a change finds but does not fix gets a test of the correct behavior, marked `skip: 'Bug: <description>'`. ## Snapshots The CLI and the fixture registry keep snapshots of the apps they generate, in `packages/smf_flutter_cli/test/snapshots/` and `packages/smf_pipeline/fixture_registry/test/snapshots/`. When a change alters what an app renders, update the snapshots and review their diff: ```bash cd packages/smf_flutter_cli SMF_UPDATE_SNAPSHOTS=1 dart test test/snapshot_test.dart ``` The CLI keeps no snapshot of an app with every module for another value of a mode option, such as another sign-in mode. The snapshot of the app of the provider of the role for that value shows what the value changes. ## Notes for coding agents Every module that the CLI offers has a note in the guide for coding agents of the apps with it, and so does every role with a template. `test/agent_notes_test.dart` of `smf_flutter_cli` fails on one without a note. A module or a role with nothing to tell a coding agent is listed in that test with the reason, and so is a module whose only note is for the apps with another role. The same test runs `roleNoteProblems` over the modules of the CLI, and the test of that name in the fixture registry runs it over the fixtures, so that the note of a role names nothing of a module that provides a role. [Notes for coding agents](https://doc.saymyframe.com/extending/infrastructure-module.md#notes-for-coding-agents) has the rules of a note, and [Test a module](https://doc.saymyframe.com/extending/testing.md#the-notes-of-roles) describes the check. ## Generated apps Besides the job of the checks above, CI has jobs with Flutter, which run with the pinned Flutter 3.44.2 on pushes to `main` and on pull requests into it. They generate apps with the matrix tool of each registry: `packages/smf_flutter_cli/tool/matrix.dart` for the modules of the CLI, and `packages/smf_pipeline/fixture_registry/tool/matrix.dart` for the fixture modules. The matrix of a registry has the apps of the contract harness for its modules, and the apps with every module, one for each combination of the providers of the roles that take one, such as one for each state manager. The tool generates each app with `smf create --no-input --skip-external-setup --no-dart-fix --strict` and runs `flutter analyze` on it. `--no-dart-fix`, a hidden option, skips the full `dart fix` of the app. Some apps of the matrix warn about what they are made of on purpose, such as an app of a module that marks no route as a start screen, and `--strict` stops on such a warning. The contract harness records the codes of the warnings of each app, and the tool allows each of them with `--allow-warning=<code>`, another hidden option. So a warning that the harness did not find stops the job. The tests of the matrices declare which apps warn, so a new warning in any app fails them too. No app with every module warns. Then it copies into the app the tests that apply to it, from the `app_tests/` directories of the packages, adds the packages these tests use with `flutter pub add dev:…`, runs `flutter analyze` again and then `flutter test`. These tests check what only a running app shows, such as the start-up of Firebase with the platform side of its plugins mocked, and they are not part of the apps that `smf create` generates. `flutter test` runs them next to the widget test of `StatusBarIcons`, which the app entry role gives every generated app. See [App tests](#app-tests). The number of apps with every module is the product of the numbers of providers of those roles, so it grows fast. The matrix generates a pairwise covering of them: every pair of providers of two different roles that fit in one app is in one of its apps, and so is every module. The tool still renders every combination in memory with the contract harness, and a combination with errors fails the run. A role with a mode option makes another app for each of its values, as the auth role does with `--auth-mode`. So a matrix has each app with every module once more for every combination of the values of the mode options of its roles, except the combination of the first values, which is that app itself. Such an app has the modules of the app with the first values, and its name ends with its values, as in `every module (bloc) --auth-mode=guest`. For a covering, the value of a mode option is one more thing that an app has, as the provider of a role is: a pairwise covering takes the apps that have, between them, each other value with each provider of a role that has several, and with each value of another mode option. An app with the first value of a mode option gets no value of it on the command line. The role chooses the first value without the option, so CI generates the app as a user without the option does. ### The plan of CI CI spreads the apps over many jobs by a plan. The job `Plan` runs the matrix tools with `--plan`, which print the plan as JSON. It has the covering of the apps with every module that the matrices check, `pairwise`, as `combinations`, and these lists: - `shards`: the shards of each matrix, one for about each 24 apps that its jobs check, about 20 minutes each; - `apps`: a pairwise covering of the apps with every module of the CLI; - `start`: a pairwise covering of the apps with every module of the CLI but the modules whose steps need an external service, such as Firebase, and the modules that need them; - `entries`: the app with every module of the CLI for each provider of the app entry, the role whose provider owns the native projects and their configuration. The apps of the other values of a mode option count for `shards`, and they are never in `apps`, `start` or `entries`. So the apps that CI builds for a platform or starts on a device have the first value of every mode option. The values differ in Dart code only, which the jobs of the matrices check. Each job of this table takes one shard or one app of the plan from its matrix: | Job | Takes | Does | | --- | --- | --- | | `Generated apps (<registry>, <shard>)` | a shard of `shards` | Checks its share of the matrix of its registry, `real` for the modules of the CLI or `fixtures`, in a directory with a space in its name. Then it checks its share of the apps with every module again, in a directory whose name has letters beyond ASCII too. | | `Android (<app>)` | an app of `apps` | Builds the app with `flutter build apk --debug`, and runs the commands of the CI of the app in a clone of it. | | `iOS (<app>)` | an app of `apps` | Builds the app for the iOS simulator. | | `Windows (<app>)` | an app of `apps` | Checks the app as the matrix does, and generates it once more as a user does. | | `Android start (<app>)`, `iOS start (<app>)` | an app of `start` | Starts the app on an Android emulator or on an iOS simulator. The first app of `start` starts once more on Android as a release app; see [Starting the apps](#starting-the-apps). | | `iOS archive (<app>)` | an app of `entries` | Archives the app with the build phase for Crashlytics. | | `Android with Firebase (<app>)`, `iOS with Firebase (<app>)` | an app of `entries` | Configures the app with Firebase and starts it. On Android it also sends the app a push message and checks that it arrives. | The other jobs have no matrix: `Generated apps (several providers)` and `Generated apps (broken providers)`, described in [App tests](#app-tests), `macOS` and `Windows`, which run the tests of the packages, `Brick of flutter_core`, which compares the brick of `flutter_core` with the app of `flutter create`, and `Firebase key`, which tells the jobs with Firebase whether the key of the Firebase project of CI is there. A job shows its app in its name, such as `Android (every module (riverpod))`, and the matrix tool generates the app with `--create --app`, named after the providers other than the first of their roles, such as `android_app_riverpod`. So a new provider or module changes the plan, not the workflows, and a job that takes its app or shard from the plan does not take longer as the apps get more: only the number of jobs grows. What Gradle and Swift Package Manager download for the native builds goes into caches of the repository. Each cache is keyed by what the app of a job builds with and by the week, and serves every version of Flutter. A job restores the cache of its app, or else the newest one of an earlier week or of another app, and the runs on `main` save the cache of an app when its build added more than 100 MB to what the job restored. Maven Central answers 403 to a runner that downloads too much, so the jobs that build for Android also take what Gradle would download from Maven Central from the mirror that Google keeps, through the init script `.github/gradle/maven_central_mirror.gradle`. ### Running the matrix locally To run the matrices locally, with `flutter` on the `PATH`: ```bash dart run packages/smf_flutter_cli/tool/matrix.dart /tmp/smf_apps dart run packages/smf_pipeline/fixture_registry/tool/matrix.dart /tmp/smf_fixture_apps ``` To check only some apps of the matrix, name them after the directory: ```bash dart run packages/smf_flutter_cli/tool/matrix.dart /tmp/smf_apps 'go_router with layout' ``` These options go before the directory: | Option | Checks | | --- | --- | | `--every-module` | Only the apps with every module, one for each combination of providers. It leaves out the apps of the other values of a mode option. | | `--combinations 3-wise`, `--combinations all` | A covering of every triple of providers of three roles, or every combination, of the apps with every module, rather than a pairwise covering. The values of the mode options count as the providers do. | | `--app '<name>'` | With `--every-module`, only the app with every module of that name, such as `'every module (riverpod)'`, as a job of CI does. | | `--shard <i>/<n>` | Only the share `i` of `n` of the apps, as a job of CI does. | `--plan` alone prints the plan, and `--plan --every-combination` the plan of the nightly run with the latest Flutter. `--create` generates apps with every module without checking them, for the native builds and the starts. It takes a directory and a name, names each app after the providers other than the first of their roles, such as `my_app` and `my_app_riverpod`, and passes the arguments after the name to `smf create`. It generates a pairwise covering of the apps with every module, or the apps of `--combinations` or `--app`, and none of the apps of the other values of a mode option. With `--without-external-steps` after `--create`, it leaves out the modules whose steps need an external service, and the modules that need them, so the apps start as they are generated. ```bash dart run packages/smf_flutter_cli/tool/matrix.dart --create --without-external-steps /tmp/smf_start start_app ``` In a directory whose path has letters beyond ASCII, the matrix analyzes the apps with `dart analyze --fatal-infos`, because `flutter analyze` of Flutter 3.44 and 3.47 fails in such a directory on every system. To run the CLI from source: ```bash cd packages/smf_flutter_cli dart run bin/smf_flutter.dart create my_app -o /tmp/out --org com.example --no-input --on-conflict replace ``` ## App tests Each directory right in the `app_tests/` of a package holds the tests of one `MatrixAppTest`. The package of each matrix tool registers them in its `lib/matrix_app_tests.dart`, each with the apps it `appliesTo`: `smfAppTests()` of `smf_flutter_cli` for the CLI and its modules, and `fixtureAppTests()` of `fixture_registry` for the fixture modules. A test that applies to no app fails the run, and `test/matrix_app_tests_test.dart` of the package fails on it without Flutter. A test in `tools/` fails when no matrix tool lists a directory of app tests, because its tests would never run. `app_tests/` stays out of the analysis of its package, of its published archive and of SonarCloud, but `melos run format` formats it. Give each `testWidgets` there an explicit `timeout`. In the files of a test, `{{app_name}}` becomes the name of the package of the app, and `{{<key>}}` a value of `MatrixAppTest.values`. A test that needs to know what the modules of an app give a role, such as the services they register, gets files that the matrix writes next to it from the data of the roles of the app, with `MatrixAppTest.generatedFiles`. The start check of the CLI, described in [Starting the apps](#starting-the-apps), applies to every app, so the matrix analyzes it in each of them, and `flutter test` runs in each of them. The tests check roles, not the modules that happen to provide them today: - A test that a package of modules keeps applies only to the apps with its modules. What it needs of the other modules of an app comes from the roles of the app through `MatrixApp.hook`, such as whether the app has a router and the route it starts on. - A test of the contract of a role, such as the listeners of the screen of the router role, names the role in `MatrixAppTest.roles` and selects its apps by the roles of the app, never by the ids of the modules that provide it. The run fails when such a test applies to no app of a provider of its role, or would select other apps, take other values or generate other files with another id in place of that of a provider. - The run also fails when a role that the tests of a registry must check, in `MatrixAppTests.testedRoles`, has no test. So a new router gets the tests of the router role without a change of the tests. - A test of what only one provider does, such as a refresh of go_router, names no role and selects the apps of that provider by its id, as an exception that `tools/app_tests_test.dart` lists. - A test takes the mode of its app from the choice of the role, with a function of the role over `MatrixApp.hook`, such as `authRole.modeIn`. It reads neither the name of the app nor the options that the matrix generates it with. The run fails on a test that does something else once an app has another name or no options, and says what the test read. | Matrix | Roles that its tests must check | | --- | --- | | The CLI | Router, DI, events, preferences, values in .env, localization, theme, authentication, notifications, push messages, purchases, app entry, settings screen | | The fixtures | Router, DI, events, preferences, values in .env, localization, theme, authentication, notifications, push messages, purchases, app entry, layout, onboarding screen | | The app of several providers | Analytics, crash reporting, onboarding screen | The fixture registry has every module of the CLI that provides the router or the layout role, so its tests of those roles run with each of them. Tests in `tools/` also fail when: - an app test that a package of modules keeps applies to an app without those modules; - a matrix tool selects the apps of a test, fills the values of its files or generates files for it by the id of a module that the test does not know; - a matrix tool imports a package of modules whose app tests it does not register; - a file of `app_tests/` imports a file of the app that neither a role nor a brick of its own modules generates; - an app test calls a function of a role that an app can have several providers of, such as `createCrashReporter()`, unless it tests the contract of that role. The call reaches every provider, and only the tests of each provider know what it does there, so the test of Crashlytics calls `createCrashlyticsCrashReporter()` instead. A test of the role names the role in `MatrixAppTest.roles`, lives in a package of no module, such as the fixture registry, and looks only at what reaches the providers that its package knows. A module whose start-up or services call a platform channel keeps the mocks of its platform side with its app tests, as a function in a file in `test/`, and declares the function in `MatrixAppTest.mocks`, as the Firebase modules and `shared_preferences` do. The matrix writes `test/flutter_test_config.dart` into each app with such tests. Before the tests of each test file, it sets up the mocks of every test that applies to the app, so the tests of any module can run the start-up of the whole app. A module with a guard of the routes opens the guard in those mocks, since the tests of the other modules expect the screens that the guard would keep them from, and the walk of the routes fails on a guard that does not allow, by its name. The mocks of `onboarding` finish the onboarding before the app starts, with `onboardingStatus.complete()`, unless a test file of the onboarding itself tells them to leave it alone. The mocks of `sign_in`, whose guards ask for an account, sign one up: a call of `appSession.signUp()` made before the app starts, which nothing awaits, gives the app that account before its first frame. So every test file of every module in an app with `sign_in` starts with an account signed in, and both guards allow. The two test files of the module that go through a first launch tell the mocks to sign nobody up. The mocks of `firebase_auth` are a backend in memory that starts with no account and nobody signed in, so every test of the app sees a first launch. The firebase_auth plugin brings no mocks for tests, so they answer the messages of the plugin themselves. A widget test that starts the app runs `main()` in `tester.runAsync`, so that a start-up that waits for a timer or for input and output does not keep the fake time of the test waiting forever. The test fails on an error of `main()`, which `runAsync` would only report to `FlutterError.onError`. Once `main()` returns, it puts back `FlutterError.onError`, `PlatformDispatcher.instance.onError` and `ErrorWidget.builder`, which a start-up may replace, as crash reporting replaces the handlers of errors. `startApp` in `fixture_registry/app_tests/router_screens/test/screens.dart` does all of this. The app tests of the modules of the CLI must pass whatever else an app has. The job `Generated apps (several providers)` runs them in the app with every module of the registry of several providers, `severalProvidersModules()` of the fixture registry. The app has: - each module of the CLI that provides a role an app can have several providers of, such as crash reporting, next to fixture providers of the same roles, whose start-up and services call platform channels of their own; - a fixture provider of both roles that notes each call it gets, and a fixture whose start-up waits for a timer; - `get_it`, the fixture events and `shared_preferences`, for the tests of the DI, events and preferences roles; - `settings` with two fixtures that have a setting, for the tests of the settings screen role. The widgets of the two settings have one class name, so the app analyzes only if the screen imports the file of each with a prefix of its own; - `material_theme`, for the tests of the theme role, and the fixture texts, a provider of the localization role; - `onboarding` and `home`, for the app tests that the two modules keep. The mocks of the first finish the onboarding for the other tests of the app, and the test of the second runs in an app that starts on the screen of another feature. The fixture steps give the onboarding two steps, for the test of the onboarding screen role; - `local_notifications` and `firebase_messaging`, for the app tests that the two modules keep and for the tests of the notifications role and of the push role, whose step of the onboarding and entry of the settings screen show there too; - `google_sign_in` and `apple_sign_in`, for the app tests that the two modules keep and for the test of the ways to sign in of the auth role; - `firebase_auth`, for the app test that the module keeps and for the test of the auth role, in the default mode of the role; - `revenuecat`, with `dart_define`, whose values it reads, for the app test that the module keeps and for the tests of the purchases role: of the role, of the users of the session and of the row that restores purchases; - `paywall`, for the app tests that the module keeps, which buy over the purchases of `revenuecat`. Its row Subscription shows on the settings screen, and its step of the onboarding comes after the fixture steps and the step of the notifications; - `sign_in`, for the app test that the module keeps, and with it `bloc` and `riverpod`, since a registry has every provider that one of its modules has a variant for. The registry has such an app for each of the two state managers, and the tool checks the first. The app is also where the tests of the analytics and crash reporting roles run; see [The roles at run time](#the-roles-at-run-time). A test of the fixture registry fails when such a module of the CLI is missing from the registry. The tool checks its one app and takes no names of apps: ```bash dart run packages/smf_pipeline/fixture_registry/tool/several_providers_matrix.dart /tmp/smf_several_providers ``` ### The roles at run time The contract harness checks the files of an app. The matrices check what a provider of a role does in a running app, with tests of the role in the apps of every provider of the role that their registry has: | Role | Tests | What they check | | --- | --- | --- | | Router | `router_walk` of the CLI | The test starts the app with `main()` and goes with `go()` to each location that needs no values, up to the first 20. Each location shows the page of its route on top of the innermost navigator, named after the route, and the screen of the route, with no `ErrorWidget` and no error from Flutter. Every guard of the routes has to allow, so that the walk reaches every route outside the flows, and the test fails on one that does not, by its name. The flows are over then, so for a location of a flow the walk expects the screen that the app starts on. | | Router, layout | the tests of the fixture registry | The listeners of the screen, each called on its own, the observers of each navigator, the back button of the system, the fallback screen, the `StateError` of `push()` and `replace()` with a location of the main navigation, the `config` created once, and the switches between the destinations of the layout. On the screen that the router shows for a location that it cannot show, the back button throws nothing and closes a dialog over it, and `push()` and `replace()` from that screen show their location, of which the listeners hear once. `go()` out of the main navigation and back to a destination throws nothing, in one turn too. In each language of the app, `label(context)` of every destination returns the text of its module in that language, and the layout shows no label in a language that the app is no longer in: as a text, in a tooltip or to the semantics. | | Router: guards | `router_guards`, `router_guards_fallback`, `layout_guards` and `router_walk_guards` of the fixture registry | While a gate does not allow, the router shows its target in place of the location that the app starts on, and of each location outside the flow of the guard that `go()`, `push()` or `replace()` asks for. The target is then the only page, and such a `push()` completes with `null`. When a guard starts or stops allowing, the router shows what the role answers: the target, in place of the pages that the guard keeps the user from, or, once the guards allow, the latest location that was asked for, the location below the pushed pages, or the screen that the app starts on. The routes of a flow show only while a guard with that flow does not allow: once it is over, a location of the flow shows the screen that the app starts on. The router asks the guards by stage, whatever the order of the modules. Once a guard that does not bring the user back stopped allowing, the user comes to the screen that the app starts on. A notification of a guard that changes nothing leaves the stack as it is. The guards hold over the fallback screen of the app entry too. With a layout the user comes back to the destination that a pushed page was opened from, and each branch is back on its destination, also when a gate closes and opens in one turn. The walk holds with a guard closed and then open. | | Router: conditions | `router_conditions`, `router_flow_opens` and `layout_guards` of the fixture registry | While a condition does not hold, `go()`, `push()` and `replace()` of a route that asks for it open the target of its guard over the page that the user is on, and the router builds no screen of that route. Back returns to that page, and such a `push()` completes with `null`. Once the condition holds, the router closes the flow and does what was asked. A further request shows nothing while the flow is open, and the first one waits. A route that asks for two conditions opens the flow of each guard in turn, and a location from the platform opens the flow over the screen that the app starts on. A link to a page of the flow itself opens that page over the screen that the app starts on, and back leads there. One request opens the target once, and the router throws nothing later, as from a microtask. When the condition stops holding, the router closes the pages that ask for it. A gate decides for every route, and the tests pin the known limit: a location that asks for the condition and is asked for behind a gate is lost when the gate allows first. With a layout, the flow opens over the main navigation, which stays below it. The listeners of the screen hear only of the pages that the user saw. | | DI | `di_role` of the CLI, `di_disposal` of the fixture registry | After the start-up, every registered service resolves, a singleton or lazy singleton to the same instance each time. None resolves after `resetDependencies()`, and all resolve again after `registerDependencies()`. `resetDependencies()` disposes of the services of the fixtures in the reverse order of their registration and creates no lazy singleton just to dispose of it. | | Events | `events_role` of the CLI | Each listener of a type gets each event of that type once, in the order the events were fired, and a listener of an unrelated type gets neither the event nor an error. The stream of `on<T>()` has only the events fired after it is listened to, and a cancelled subscription gets no more events. | | Preferences | `preferences_role` of the CLI, `preferences_restorers` of the fixture registry | A value of each type is read back as it was saved, and as `null` by the reads of the other types, which do not throw. A removed key has no value, and a write replaces what its key had, a value of another type too. The preferences keep a copy of a list they are given, and a read returns a copy of it. The next start, `initPreferences()` again, reads what was saved and nothing that was removed. The start-up gives each restorer the preferences once, a setting that nothing saved keeps the value it had, and a restorer that throws keeps no other from restoring and does not stop the start. | | Settings screen | `settings_screen_role` of the CLI | The route that the provider names shows the screen. The screen shows every entry once, one below the other in the order of the role, each on a `Material`, in a list that scrolls. It sets the width of each entry, the same for every entry, and puts no limit on its height. | | Localization | `localization_role` and `language_setting` of the CLI | The root of the app supports the languages of the app and no other, with a delegate of each kind of localizations for each. Once the user chose a language with `appLocale.choose()`, the app is in it, and each text reads in it: its translation, or its English text. While the user chose none, the app is in the language that the device prefers among its own, and in its first one when the device asks for none of them. A choice is saved under the key of the role and removed when the app follows the device again, and the next start restores the language that was saved. In an app with a settings screen, the entry of the language shows the choice as the value of its row. A tap opens a sheet over the main navigation, with each language of the app and the languages of the device, and the one check mark on the chosen option. A tap on an option closes the sheet and chooses it. On a small phone with a large text size, the choice is below the title of the entry, and the sheet scrolls to its last option. | | Theme, app entry | `theme_role` and `theme_setting` of the CLI | The root `MaterialApp` takes each mode that `appThemeMode.choose()` chooses. The screen below it gets a light theme in the light mode and a dark one in the dark mode, with the color schemes that the two functions of the provider return, and in the mode of the device the theme that the device asks for. Around the navigator of the app, the root asks the system for dark icons of the status bar on a light theme and for light ones on a dark theme. A choice is saved under the key of the role, and the next start has the mode that was saved. The root rebuilds when the mode changes, whichever module provides the app entry. In an app with a settings screen, the entry of the theme mode shows once and offers each mode, with its icon above its name and the mode of the app selected, and a tap on a mode chooses it. On a small phone with a large text size, the names of the modes grow only by half and stay in the control of the entry. | | Authentication | `auth_role` and `auth_methods` of the CLI | The constant `authMode` of the app is the mode that the role chose, and the test expects what that mode says, so the same files hold in an app of each mode. On the service of the provider, when a call completes, `currentUser` is its result. A wrong password and an address without an account both fail with `invalidCredentials`, and a sign-up with an address that has an account fails with `emailInUse`. A call that fails leaves whoever is signed in. Each anonymous user has an id of its own and keeps it with an account, a deletion removes the account, and `userChanges` tells each listener of every change. `appSession` goes through a sign-up, a sign-out, a sign-in and the deletion of the account as its mode says, and only an app in the mode `anonymous` signs a user in when the user comes back to it. The next start, `initAuth()` again, has the user of the device as soon as it is over. An account that is signed up before the app starts is signed in when `bootstrap()` is over. In an app with ways to sign in, `signInWith()` of a new identity creates its user and of a known one finds it, `linkWith()` gives an anonymous user the identity with the same id, or fails with `credentialInUse` or `accountExistsWithOtherMethod`, after which `signInWith()` of the identical credential signs in to the user that has it. `deleteAccount(fresh:)` with a credential of another user deletes nothing. Through each way to sign in, `appSession` gives an anonymous user the identity, and deletes an account after a start, asking a way to sign in that revokes on deletion for a new credential. | | Onboarding screen | `onboarding_screen_role` of the fixture registry | Each label of a step returns the text of its contributor in each language of the app. The screen shows each step on a page of its own, in the order of the role, with no other page between two steps: its icon, its title as a header for a screen reader, its text and its buttons. A swipe past a step calls no action. A tap on the action calls it once, and the buttons of the step take no tap until its future completes. Then the next page shows, also when the action fails, and its error reaches the handlers of the errors of the app. The second button of a step shows the next page without the action, and on no other page. A step that shows stays once its condition would leave it out, and a new screen leaves out a step whose condition does not hold. | | Notifications | `notifications_role`, `notifications_setting` and `notifications_step` of the CLI | The permission is `notAsked` until the app asks. A request asks only while the app may not show notifications, and saves that it asked once the user answered. Two requests at once ask once, and on a system without a question the request opens the settings of the system. A tap on a notification of the app reaches every listener of `appNotifications.taps`, and a tap on a notification of an owner only that owner. On the service of the provider, one request turns the notifications on, a scheduled notification is listed until it is cancelled or a notification with its id is shown, and the next start still has what was scheduled and the permission. In an app with a settings screen, the entry shows Off or On in each language, a tap asks while the app has not asked and opens the settings of the system after that. In an app with an onboarding, its step shows only while the app has not asked, and its action makes the request alone. | | Push messages | `push_role` of the CLI | The address is `null` until the service gives one, follows each new address and stays the same at the next start. Each message in the foreground reaches `appPush.messages` once. Where the platform does not show a message, the app shows one with a title or a body as one notification owned by the role, whose tap reaches `appPush.taps` and not `appNotifications.taps`. The message whose tap launched the app is `appPush.launchMessage` and not among the taps. The provider never asks for the permission to show notifications. | | Values in .env | `env_role` of the CLI, `env_variables` of the fixture registry | For a key with a value in `.env`, in either form of a value, the getter of `AppEnv` returns that value, and for a key that `.env` leaves empty or lacks, it returns `null`. The test parses the `.env` of the app and gives no value itself: the tests of `revenuecat` and `paywall` give their keys values of the tests in `.env`, and the fixture registry gives a key a value in quotes, leaves one empty and removes one. | | Purchases | `purchases_role`, `purchases_session`, `purchases_device` and `purchases_setting` of the CLI | A fresh user who buys a plan has premium access, for good or until a time after the purchase, a free trial when the plan has one, and the listeners hear of it once. A restore gives the access that the service gives right after it. The next start gives the same user the same access. A fresh user has nothing, and the purchases of each user stay apart. With sign-in, in each mode of the auth role, a purchase without an account stays with a new account after a sign-up, and the next user after a sign-out has none of it. Without what it needs, the provider leaves the app without purchases, and nothing reaches the handlers of the uncaught errors. The row Restore purchases restores once on a tap and shows what it found, in each language of the app. | | App entry: flavors | `flavors` of the CLI | `flutter test`, a command without `--flavor`, gives the app the default flavor. The start on a device shows what a command without `--flavor` builds, and the release start that `--flavor` reaches the app. | | REST API | `rest_role` and `rest_session` of the CLI, `rest_consumer` of the fixture registry | A request reaches a local server as it was given. Each status has its reason, `GET` and `HEAD` repeat and other methods do not, a timeout and a cancel end a call, and redirects keep what may go where. In an app with sign-in, the token goes only to the origin of the address, and a 401 refreshes it once. `rest_consumer` goes through a small state of a screen on the role. | | App icon | `app_icon_role` of the CLI | The sources have the sizes of the role, the first without alpha and the second with it, and what the step of the provider left in the native files is the icon that each platform reads. | | Splash screen | `splash_role` of the CLI | The step of the provider left a screen in the native files, from the activity that the launcher starts to the resource that Android picks at each version and in each mode. | | Analytics, crash reporting | `analytics_role` and `crash_reporting_role` of the fixture registry | In the app of several providers, every provider gets each call of the service of the role once, and every crash reporter gets each error that nothing catches once. A provider that throws or fails keeps no other from the call, and its failure reaches neither the code that called nor the handlers of errors. Each analytics provider gets its own copy of the parameters, and a provider whose factory or start fails is left out. | A test of a role knows only the role. The matrix writes what the test needs to know of the modules of an app next to it, from the data of the roles of the app, such as the services that the modules register, the locations of their routes or their texts in each language. - The matrix of the CLI runs its tests in every app with the role, and the test of the DI role in those whose modules register services. - The matrix of the fixtures runs them only in some of its apps: the tests of the events role, of the preferences role and of the localization role and the walk in its apps with every module, which run `flutter test` for other tests anyway, and the test of the DI role in its apps whose services have every lifetime. It runs the test of the auth role in every app with the role, which a fixture sign-in with accounts in memory provides there. - The walk, the check of the services of the DI role, the checks of the preferences, the check of the languages, the checks of the notifications and of the push messages, and the check of the purchases, which only read, use no test framework, so the start check also runs them on devices; see [Starting the apps](#starting-the-apps). The tests of the settings screen have no such probe, since the walk goes to the screen on a device. The tests of the auth role have none either, since nobody can sign in on a device, and neither have the tests of the onboarding screen, of the entry of the notifications and of their step, whose action would leave the question of the system over the app on a device. - Under `flutter test`, the flows of the guards are over, so the walk shows none of their screens. Those are for the tests of the module of each guard. - The test of the auth role calls the service of the provider itself, through `createAuthService()`, since the contract of the service is what it checks. The tests of a module go through `appSession`, as the code of the module does. The tests of the guards run in the apps of the fixtures that have the two fixture features with guards. One has two gates that a test closes and opens, and that are open otherwise, and two guards that stand for the conditions of a fixture role, which routes of another fixture feature ask for. The other has a gate of the later stage that does not bring the user back. Both depend on one of the two fixture state managers, so the apps with every fixture come with guards and without them, and the other tests of the router and of the layout run in both. In the apps without, the routes that ask for a condition have no guard that stands for it, and show like any other route. For the walk, the matrix writes more next to the locations of an app: `shownFor()`, which gives the page and the screen that the role says the router shows for a location, `startOfApp`, the screen that the app starts on, and `closedGuards()`, the names of the guards that do not allow. No test can open a guard on a device, such as one that asks for a signed-in user. So the probe of the walk holds there whichever guards allow. For a location that a guard keeps the user from, it expects the page and the screen of the target of that guard, and for any other location in a flow that is over, the screen that the app starts on. In an app with `sign_in` in the mode `required`, the gate does not allow on a device. The walk then shows the three screens of the sign-in and expects the sign-in in place of every other location. A module keeps the tests of what only it does. The test of `shared_preferences` checks that a value that the preferences of the module save reaches the package under the same key and with the same type, that a number is read only as the type that it was saved as, and that a list is read in the form that each platform returns it in. The test of `settings` puts the app into each language that the module has its title in: the screen shows the title in that language, as its header for a screen reader. Below the title, the screen shows one group, a card with a line between each two entries, or, in an app whose modules have no setting, the note for the developer of the app. The note names the file of the screen, a tap on the path copies it, and on a small phone with a large text size the screen scrolls and shows the path in full. The screen has a back button, in an app bar, only on top of another screen, where the button leads back. The test of `onboarding` starts the app as its first launch finds it, with nothing saved: the app shows the onboarding and does not build the screen that it starts on, and Skip and Get started, the button on the last page, save `onboarding.completed` and show that screen. The marks of the pages and the buttons follow the page, and in an app that asks for less motion, Next shows the last page at once. Both pages show their texts in each language of the app, with their titles as headers for a screen reader, on a small phone with a large text size too, where the letters and the number in the cell of a page keep their size. Started with the onboarding finished, the app never builds the onboarding, and `go()`, `push()` and `replace()` of its route show the screen that the app starts on: only `onboardingStatus.restart()` shows it again. Its probe goes through the onboarding on a device. The test of `firebase_auth` uses the service of the module on the real Firebase packages, over mocks that answer the messages of the plugin. It checks what each call sends to Firebase, the reason of the role for each code of Firebase in the form of Android and of iOS, with the command of the script that enables a way to sign in in the hint of `notConfigured`, the language of the message of a password reset, and the user whom a start finds on the device. Its probe checks on a device that the session of the app has the user that the plugin has. The test of `home` goes to the start screen in each language of the app: the screen names the app, shows the mark from the image that the app bundles, and has the card and the three steps, each one button for a screen reader, and a tap on a step copies its path. It shows each greeting at its first and its last hour, the card in a light and in a dark theme, and the parts of the screen as they come in, at once in an app that asks for less motion. On a small phone with a large text size, nothing overflows and the list scrolls to each step. The test of `sign_in` runs in every app with the module, in each mode of the auth role: its files read `authMode` of the app and expect what that mode says. Two of its five files go on with the provider of the auth role of the app, from a first launch and from a link to the sign-in. In the mode `required` the app shows the sign-in in place of the screen that it starts on, a sign-up shows that screen, and a sign-out shows the sign-in again. In the other modes the sign-in opens over a screen, and after a sign-in the user is on that same page. The other three give the session a service of the test, which fails a call with a reason or holds it back. They check the entry of the settings screen and the screen of the account with its sheet, what a form says and does while its call is on its way, the text of each reason of a failure in each language of the app, and the screens on a small phone with a large text size and with a keyboard. The test has no probe: nobody can sign in on a device. The modules of the notifications, of the push messages and of the ways to sign in keep tests of their own too. The test of `onboarding` goes through the pages of the steps of an app, with Skip and the second button of a step, on a small phone with a large text size too. The test of `local_notifications` checks what each call of the service sends to the plugin on Android and on iOS, the taps and the tap that launched the app, over mocks that answer the method channel of the plugin. The test of `firebase_messaging` does the same over mocks of its own plugin, with the presentation options on iOS, the first address on iOS once the device gets its token of APNs, and data that is not a string as its JSON. The tests of `google_sign_in` and `apple_sign_in` run the real packages over mocks that issue test tokens: the credential, the outcome of each answer of the identity provider, the platforms of the way to sign in and its icon. The test of `sign_in` checks the buttons of the ways to sign in of the app on Android and on iOS, with the providers and the mocks of the app, and the texts of a deletion that a way to sign in refused. The fixture registry keeps the tests of what only go_router does: the back button of the system on its error screen, `push()` and `replace()` while go_router has no page of a route, a main navigation that comes back as a new one after a `go()` out of it, a refresh of its routes while the flow of a condition is open, a second link to the page on top, and the calls of go_router that the router makes itself. It also keeps the test of the bar that `bottom_tabs` draws: what each tab says to a screen reader, the tick of a tap, the color and the size of the selected tab, the screen of a destination that fades in, no motion for a user who asks for less, and large text. A test shows that a setting is remembered by writing its key through `AppPreferences`, running `initPreferences()` again and reading the state, and that it is saved by reading the key after a choice. Running `initPreferences()` again right after a choice proves nothing, since memory has the value already. ### Broken providers A test of a role that passes whatever the provider does checks nothing. So the fixture package `fake_broken` has providers of roles with one known bug each, which `brokenProviders()` in `fixture_registry/lib/broken_providers.dart` lists with their bugs: | Role | The bug of each provider | | --- | --- | | Router, the screens | Six routers: they tell the listeners of the same screen again, stop at a listener that throws, push a location of the main navigation over a page over it, create their `config` again, show another screen in the page of a route, or throw when the back button of the system has no route to close. | | Router, the guards | Three routers: they ask the guards only as the app starts and when one of them changes, do not show what the guards answer when one of them changes, or leave the stack as it is when a guard keeps the user from the location of a `replace()`. | | Router, the conditions | Five routers: they tell the guards of a pushed page under the route of the location below it, ask about a location by the name of its top-level route, show the target of a guard that stands for a condition in place of the stack, or drop the request that waits when the pages of its flow close. The fifth is a go_router whose redirect asks the guards within the calls of the router. | | Router, the main navigation and the guards | Three routers: they leave the selected branch its pages when they show what the guards answer, leave the pages of every branch where they are, or keep the navigators of the branches when the main navigation leaves the stack. | | Layout | Two layouts: an `AppShell` that gives only its first destination to the code that reads them, and one that keeps the labels of its tabs from its first build, in the language of before. | | Events | A service whose `on<T>()` gives a listener the events of every type. | | Preferences | Three providers: writes that never reach the disk, lists that are never copied, and reads that cast the value to the type they ask for. | | Localization | Two providers: a delegate that supports English only, and texts that are always in the first language of the app. | | Theme | A `createDarkTheme()` that returns the light theme. | | App entry | A root that keeps the `MaterialApp` that it built first, so it does not follow the theme mode. | | Authentication | Three providers: one returns its service before it has read who is signed in on the device, one gives an anonymous user a new id when the user gets an account with a password, and one does so when the user gets the identity of a way to sign in. | | Onboarding screen | An onboarding that never asks a step whether to show it. | | Notifications | A provider that forgets the scheduled notifications each time it opens. | | Push messages | A provider that gives the device a new address at each start. | | Purchases | A provider that keeps the purchases in one field for every user together. | | Values in .env | An `AppEnv` that returns an empty value as an empty text rather than `null`. | | DI | A container that registers one service only in a condition that is false when the app runs. | | Settings screen | A screen that creates the widget of every entry and shows all of them but the last. | | Analytics | A service that notes each call twice. | | Crash reporting | A reporter whose start takes the handler of the errors of Flutter for a report of its own. | Each keeps the rules that the contract harness checks, so only a running app shows its bug, and none is in a registry of apps that must work. The app of a broken provider gets no role option, so that each role chooses as it does for an app that got none. A provider whose bug the tests show in full only in another mode of a role names the option, as the fixture sign-in that gives an anonymous user a new id does with `--auth-mode=anonymous`. The job `Generated apps (broken providers)` checks the tests with them: 1. It generates for each provider a small app with only the modules that its tests need. 2. It adds the app tests of the fixtures and of the app of several providers that apply to the app, and runs `flutter analyze` and `flutter test`. 3. Each test of the role that the registry names for the bug must fail, first on the expectation with the reason that the registry gives, and every other test of the app must pass. So the job fails when a test of a role passes whatever the provider does, or fails for another reason. The job does the same for the apps of `brokenModuleApps()`, whose tests must fail for what a module does and not for the bug of a provider: in the app of the fixture gates that start closed, which nothing opens for the tests, the test of the walk must fail on the guards, by their names. A test of the fixture registry checks the registry without Flutter. Among other things, each expected failure names a test that the app has, and a reason that the test file writes, or a file that it imports by a relative path. A reason is a real piece of that text: it has to match at least twelve characters that the file itself writes. A test of the fixture registry fails when a role whose contract the app tests check has no broken provider, unless `brokenProviderExemptions` exempts it with a reason. The Build workflow runs the job, and the nightly run only with the latest Flutter. To run it locally: ```bash dart run packages/smf_pipeline/fixture_registry/tool/broken_providers_matrix.dart /tmp/smf_broken_providers ``` ## macOS and Windows The jobs `macOS` and `Windows` run the tests of every package and of `tools/` on the runners of GitHub, with Flutter 3.44.2. A test of something that only one system does runs only there, marked `@TestOn('mac-os')` or `testOn: 'windows'`: on macOS, the Ruby of the machine and its gem xcodeproj; on Windows, the batch files that the CLI runs without a shell. The jobs on macOS generate their apps in a directory whose name has a space and letters beyond ASCII. `iOS archive (<app>)` archives its app with `flutter build ipa --no-codesign`, in `test/crashlytics_archive_test.dart` of `smf_firebase_crashlytics`, which takes the app from `SMF_CRASHLYTICS_APP` and skips an app without Crashlytics. Before the archive, the test adds the build phase for Crashlytics with the gem xcodeproj, as `flutterfire configure` does, and fixes the phase with the command from the Crashlytics section of the README of the app. GitHub runs only a few macOS jobs of a repository at a time, so the jobs `iOS (<app>)` and `iOS start (<app>)` run two at a time. `Windows (<app>)` checks its app as the matrix does, in a directory with a space in its name and then in one whose name has letters beyond ASCII too. Then it generates the app once more as a user does, with the full `dart fix`, in a directory whose name has letters beyond ASCII, and analyzes and tests it. SMF generates the apps in `%TEMP%` and moves them to another drive. The job `Windows` also runs the FlutterFire CLI through `dart.bat`, as SMF does, and checks that `smf create --explain` finds it for the app of each provider of the app entry whose modules need it. The job `Firebase CLI install (Windows)` of the Build workflow runs the PowerShell script that installs the Firebase CLI, for real. The script changes the machine, so its test runs only when `SMF_INSTALL_FIREBASE_CLI` is `1`. ## Starting the apps CI also starts apps, on an Android emulator and on an iOS simulator. A check that the CLI keeps in `app_tests/start/integration_test/start_check.dart` becomes the entry of the app. It runs the `main()` of the app, takes back the error handlers that crash reporting installs, waits for the first screen to settle and checks that the root widget of the app shows it without an error. It writes `passed`, or `failed:` and the problems, to the file `smf_start_check` in the temporary directory of the app, and prints `SMF_START_CHECK:` with the same line. It knows no module, only `main()` in `lib/main.dart`, which the app entry role puts into every app whichever module provides it, and a `WidgetsApp` at the root, which `MaterialApp` and `CupertinoApp` build. So an app with another provider of the app entry role gets the same check. Once the first screen settled, the check also runs the probes of the tests of the app, those of its roles and of its modules, one after another and for at most a minute in all, and adds their problems to its line. A probe depends on no other: it holds whichever probes ran before it, and whichever guards of the routes allow. | Probe of | What it does on the device | | --- | --- | | `router_walk` | Goes to each location of the app that needs no values. It expects the target of a guard for each location that the guard keeps the user from, and the screen that the app starts on for any other location in a flow that is over. | | `di_role` | Resolves each service of the app, a singleton or lazy singleton twice, without calling it, since on a device the apps with Firebase use a real project. | | `preferences_role` | Saves values under keys of its own, reads them back and removes them. | | `shared_preferences` | Opens the preferences again and reads back what it saved, as the platform returns it. | | `localization_role` | Checks the texts in the language that it finds, goes through the first languages of the app, and puts back the choice that it found. | | `firebase_auth` | Reads the user that the session of the app has and the user that the plugin has, which must agree: nobody, an anonymous user or the user of an account, with the same id. It signs nobody in and makes no request, so it holds in every mode and without a network. | | `notifications_role` | Reads the permission of the app and what the provider says, which must agree, and that the service lists what is scheduled and that no tap on a notification launched the app. | | `local_notifications` | Checks that the channel of the app on Android has its name and a high importance. | | `push_role` | Checks that no tap on a message launched the app, and that the app has the address that the provider gives, once it has one. | | `purchases_role` | Reads the access of the app and the access that the service of the provider gives, which must agree. A failure because purchases are not set up, or the store does not answer, is no problem while the app shows no premium access, so the probe holds on a device without keys. | | `revenuecat` | Checks that RevenueCat is configured exactly when the service of the app has a key. Then the access of the app is premium exactly when the entitlement `premium` is active, and the plans of the app are the packages of the current offering. | | `firebase_messaging` | Checks that the address of the app, once it has one, is the registration token that the Firebase SDK has on the device. It then asks the script for a push message to that address, and waits for it; see below. | | `onboarding` | Reads whether the onboarding is finished, in the preferences and in the app, which must agree. If it is not finished, it goes to the route of the onboarding, which must show its screen, and finishes it as the button of its last page does: the preferences must have that saved, and the router must leave the screen. | A test declares its probe in `MatrixAppTest.startProbe`: a function in its `integration_test/` that goes through the running app without a test framework and returns what is wrong. The matrix tool lists the probes of the tests that it adds to an app in `integration_test/start_probes.dart`, so the check knows none of them itself. The check prints the probes that it ran to the log of the device, with the time each took, so the log shows them even when the check passes. `.github/scripts/start_app.sh` builds a debug app with the check as its entry, installs and launches it with `adb` or `xcrun simctl`, and reads that file. Nothing connects to the app, unlike `flutter test`, which sometimes never reaches the app on the emulators and simulators of CI. The script fails when the check fails, when the app stops before the check wrote its result, as when it crashes at start-up, and when the result does not come in time. Then it prints the lines of Flutter, the end of the log of the device and, on iOS, the crash report. With `release` after the seconds, on Android only, the script builds a release app for the ABI of the device. R8 shrinks that app as it shrinks the app that a user installs, which a debug build does not. The script cannot read the files of a release app, so it reads the result that the check prints to the log of the device, from the process that it launched. The job `Android start` of the first app of `start` starts its app this way after the debug start. The nightly run does so with every release of Flutter, so a plugin release that breaks release builds, as `shared_preferences_android` 2.5.0 did, shows within a day. After the mode, the script takes answers, `<name>=<command>`, in debug mode only. A probe of the app may write a request for one into the temporary directory of the app, `smf_start_request_<name>`, and later its verdict, `smf_start_report_<name>`. Once the start check passed, the script waits for the request, runs the command for it once, with the path of a copy of the request in `SMF_START_REQUEST`, and fails unless the app reports that the answer passed. It prints no request, but the log of the app that it prints shows what the app printed itself, such as the address for push messages that a debug app prints. Two groups of jobs start apps: - `Android start (<app>)` and `iOS start (<app>)` start the apps of `start`, which need nothing outside the app. - `Android with Firebase (<app>)` and `iOS with Firebase (<app>)` start the app of each provider of the app entry after `tool/configure_firebase.dart` configured it in the Firebase project of CI. Each job adds the check to its app with `--add-app-tests` and `--app`, the app of the plan that it generated, with `--without-external-steps` for the apps of `start`, so the check runs the probes of the tests of that app. The tool adds the dev dependencies of those tests with `flutter pub add`. The jobs with Firebase do more before they start the app: - A test of `smf_firebase_core` runs the command of the README of the app for one platform, with the key of a service account from the secret `FIREBASE_SERVICE_ACCOUNT`. It runs only when CI gives it the app, the project and the key. - Once the app is configured, `test/enable_sign_in_test.dart` of `smf_firebase_auth` asks the project for its sign-in methods as a client does, with the API key of the app: it signs in with a password for an address that has no account, which creates nothing. A project with Email/Password answers that the credentials are wrong. The test fails on a project where the method is off or where Authentication was never set up, and says who enables it. It skips an app without `firebase_auth`. The apps of CI are in the mode `required`, so it asks for Email/Password alone, and no job creates an anonymous user. - In a run of the Build workflow, one job enables the methods first. `Android with Firebase` of the first app of the plan runs the script of the app with the command of its README and the key of the service account, and expects the line with which the Firebase CLI names the methods that it enabled. It is one job, so that two never write to the project at once. The Firebase CLI provisions an app of the project for this, of any platform, and Google enables the APIs of Firebase in the project for it. So the service account needs `serviceusage.services.enable`, which the role Service Usage Admin has and Firebase Admin lacks. When the script fails for a permission, the test names the permission that the Firebase CLI printed as denied, and a role that has it. - The Firebase CLI of these jobs is the latest one of npm. `firebase_auth` needs 15.34.0 or later, and its check of the machine and the script of the app refuse an older one themselves. `tools/firebase_cli_version_test.dart` fails when a workflow or a script of CI installs or runs `firebase-tools` in a version that it writes. - On Android, the job starts the app with the answer `firebase_messaging`. The probe of `firebase_messaging` writes a request with the address of the app and a message with a value of its own. The answer, `test/push_delivery_test.dart` of `smf_firebase_messaging`, sends that message with the HTTP v1 API of Firebase Cloud Messaging and the key of the service account, and tells what a failure means, such as an API that is not enabled or a missing permission, without printing the address or the key. The app then has to get the message on `appPush.messages`. On the iOS virtual machine of CI the app gets no token of APNs, so no message is sent there. - On iOS, `test/flutterfire_phase_test.dart` of `smf_firebase_crashlytics` then fixes the build phase for Crashlytics that flutterfire added, with the command from the Crashlytics section of the README, as SMF does right after it configures an app. It takes the app from `SMF_CONFIGURED_APP` and skips an app without Crashlytics. - These jobs, like the job `Windows`, activate the FlutterFire CLI in the version that `tool/flutterfire_version.dart` of `smf_firebase_core` prints, the one that the module activates for its users. `tools/flutterfire_version_test.dart` fails when a workflow or a script of CI activates the FlutterFire CLI in a version that it writes itself, or in none. These apps are named `firebase_start_app` for the first provider of the app entry, and `firebase_start_app_<providers>` for another, after the providers other than the first of their roles. The names stay when another role gets a second provider, so flutterfire finds the Firebase apps that an earlier run registered. flutterfire registers a Firebase app when the project has none with the id of the app. Runs at the same time, such as those of the nightly run, could register one each, and the test fails on a project with more than one app with the id. So only the runs of the Build workflow let flutterfire register an app: the run of the pull request into `main` that brings a new provider of the app entry registers its apps, one job for each platform. In any other run, the test fails before flutterfire when the project has no app with the id, and asks to run Build first, which you can start by hand. `tools/firebase_registration_test.dart` fails when another workflow lets the test register apps. Without the secret, as in a pull request from a fork, the jobs with Firebase do not run, and the job `Firebase key` says so in a notice. To start an app that CI starts, generate it as CI does and add the check for the same app, then start it on a running Android emulator or device, or on a booted iOS simulator: ```bash dart run packages/smf_flutter_cli/tool/matrix.dart --create --without-external-steps --app 'every module (bloc)' /tmp/smf_start start_app dart run packages/smf_flutter_cli/tool/matrix.dart --add-app-tests --without-external-steps --app 'every module (bloc)' /tmp/smf_start/start_app packages/smf_flutter_cli/app_tests/start cd /tmp/smf_start/start_app <repository>/.github/scripts/start_app.sh android <device> 240 # such as emulator-5554 <repository>/.github/scripts/start_app.sh ios <UDID of the simulator> 240 <repository>/.github/scripts/start_app.sh android <device> 240 release ``` `--app` names the app with every module that the app was generated as, and `--without-external-steps` goes with it when `--create` had it. The tool then adds the tests of that app that have a probe, with the files that they read, such as the locations of its routes, and their dev dependencies. To start an app of yours, leave both out: `--add-app-tests <app> packages/smf_flutter_cli/app_tests/start` adds the check, which then runs no probe. The third argument of the script is how many seconds the app has to start once it is built. The build itself has no limit, as it can take minutes longer on a busy machine. `flutter run -d <device> -t integration_test/start_check.dart` runs the check too and prints its result. An app with Firebase starts only once `flutterfire configure` configured it, as its README says. ## Nightly run Every night, CI runs the jobs with Flutter again, on every stable release of Flutter that the generated apps allow. `tool/flutter_versions.dart` of the CLI finds them: it takes the Flutter and Dart constraints that the modules put into the `pubspec.yaml` of the apps, and the releases from the lists that Flutter publishes. The jobs on Linux run on all of them, and the jobs on macOS and Windows on the oldest and on the latest patch of each minor version. The jobs that the nightly run leaves out for a release show up as skipped, such as those on macOS and Windows of the other releases. A skipped job does not fail the run, so a red nightly run always has a job that really failed. To start the run by hand, use Run workflow on the Nightly workflow in the Actions tab. With the latest release, the jobs of the matrices check every combination of the apps with every module, the apps of the other values of the mode options among them, or a 3-wise covering of them when there are more than 100, in more shards. The apps that CI builds and starts stay the pairwise coverings on every release. The job `Generated apps (broken providers)` runs only with the latest release: whether the tests of the roles fail on the bugs hardly depends on the version of Flutter, apart from how `flutter_test` reports a failure. The nightly run skips the job of the checks, which needs the pinned Dart, and the job that installs the Firebase CLI. It also skips the comparison of the brick of `flutter_core` with `flutter create`, because the brick follows the template of the pinned Flutter. Only its jobs with the latest Flutter save the caches of Gradle and Swift Package Manager; the others restore them. So the caches get new versions of plugins within a week even when nothing is pushed. If the nightly run fails while the run with the pinned Flutter passes, a release of Flutter broke something. It also checks what users install. On each release of Flutter, the job `CLI from pub.dev` activates `smf_flutter_cli` from pub.dev, generates with it the apps with every module of that release, with the full `dart fix`, and runs `flutter analyze`, `flutter test` and `flutter build apk --debug` in each. The published CLI has the modules of its release, which may differ from those in the repository, so `tool/every_module_apps.dart` of the CLI lists the apps from the matrix of that release, one for each combination of its providers, and the workflow names no module. A release from before the plan has no covering, so this job alone checks every combination, one app after another. A failure there affects the users of the published version, and its fix needs a release. ## Changing the workflows The workflows take their apps from the plan, and they name neither modules nor apps. `tools/workflow_apps_test.dart` checks the workflows and the scripts in `.github/scripts`, and fails when a step: - selects an app of a matrix tool by its name, or refers to an app of `--create` by its name, as in `"$apps/android_app"`. `.github/scripts/each_app.sh` runs a command in each app of a directory instead, and fails at the end when it failed in any of them; - runs `smf create` itself, or names the modules of an app with `-m`; - refers to the package of a module, unless it runs the tests of the module, or runs with `dart run` a tool of the module that prints what the step needs to know of it, such as the version of the FlutterFire CLI, and the test lists the step as an exception, with its reason; - adds the tests of a matrix tool to an app with `--add-app-tests` but without `--app`, which names the app of the plan that the job generated; - generates or checks a whole selection of apps in one job, as `--create` without `--app`, `--every-module` without `--app` or `--shard`, or the matrix without `--shard` do, or takes an `--app` or a `--shard` that does not come from the matrix of its job. A job takes one app or one shard, so it gets a fixed number of minutes, and the test fails when a job or a step computes its `timeout-minutes`. It fails when a job whose outputs feed a matrix refers to a secret, since the runner leaves out an output with a line of a secret, such as the `{` of a key in JSON. So the job `Plan` refers to no secret, and `Firebase key` tells the other jobs whether the key is there. And it fails when a job on Linux or macOS generates an app to build it but restores no cache of Gradle or of Swift Package Manager. A new job in `build.yml` goes into the `needs` of the job `CI`, and a test in `tools/` fails when it does not. ## Changes - Keep modules independent. A change never teaches one module about another to fix a problem quickly. See [Module independence](https://doc.saymyframe.com/concepts/independence.md). - A module of the CLI with variants has one for every provider of their role that the CLI offers, as `sign_in` has for `bloc` and `riverpod`. A test of the CLI fails otherwise, since an app with the module and the other provider could not be generated. - Use [Conventional Commits](https://www.conventionalcommits.org/) with the short name of the package as the scope, such as `fix(go_router): …` or `feat(contracts): …`. `melos version` derives the versions and changelogs from them, so don't bump versions or edit changelogs by hand. - Name branches `fix/<topic>`, `feat/<topic>`, `docs/<topic>`, `test/<topic>` or `chore/<topic>`. Keep a pull request to one concern and a commit to one logical change. - A pull request is squash-merged, and the commit takes the title of the pull request as its only line, so the title must be a Conventional Commit too, and CI checks it. Mark a breaking change with `!` in the title, such as `feat(contracts)!: …`, since a `BREAKING CHANGE:` footer in a commit of the branch does not reach `main`. - A larger change may collect its pull requests in a branch of its own. The pull request of that branch into `main` is merged with a merge commit rather than squashed, so that the squash commit of each of its pull requests reaches `main` as it is and gets its own entry in the changelogs. The `!` of a breaking change then goes into the title of the pull request into that branch that makes the change. - A pull request needs two checks to pass: `PR title`, and `CI`, which fails when another job of the Build workflow failed or was cancelled, and, in a run that runs every job, when one was skipped. - Pull requests into `main` and pushes to it run every job of the Build workflow. The jobs with Flutter are many and take about half an hour, so a pull request into another branch, such as one that collects the pull requests of a larger change, runs only `PR title` and the job of the checks. The jobs with Flutter run once that branch goes into `main` through a pull request of its own. To run them on a branch before that, use Run workflow on the Build workflow in the Actions tab. - A new run of the Build workflow cancels the run of the same pull request or branch that is still in progress, and the run of a pull request stops once the pull request is merged or closed. - Once a branch is pushed, add new commits on top instead of rewriting it.