build method

  1. @override
Widget build(
  1. BuildContext context,
  2. WidgetRef ref
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context, WidgetRef ref) {
  final currentUser = ref.watch(currentUserProvider).valueOrNull;

  if (currentUser == null) {
    return Container(
      color: context.colorScheme.surfaceContainerLowest,
      alignment: Alignment.center,
      child: const SizedBox.square(
        dimension: 48.0,
        child: CircularProgressIndicator(),
      ),
    );
  }

  AppRoute routeFor(AppRootRoute rootRoute) {
    return routes[rootRoute] ?? rootRoute.appRoute;
  }

  final fleetRoute = routeFor(AppRootRoute.fleet);
  final profileRoute = routeFor(AppRootRoute.profile);
  final currentNavItem = AppNavItem.forRoute(currentRoute);

  final body = AppNavigationChrome<AppNavItem>(
    navItems: const [
      AppNavItem.fleet,
      AppNavItem.notifications,
      AppNavItem.profiles,
    ],
    navItemBuilder: (context, navItem) => AppNavigationItem(
      navItem: navItem,
      isSelected: currentNavItem == navItem,
      onSelected: () {
        final behavior = ref.read(bottomNavStackBehaviorFlagProvider);

        switch (behavior) {
          case BottomNavStackBehavior.preserveNavStack:
            if (currentRoute == navItem.route) {
              // We are currently on the root route that the user pressed.
              // Navigate to the bottom-most page in that route.
              context.router.navigateTo(navItem.route.appRoute);
            } else {
              // User switched to a new root route. Go to the top-most route
              // for the root route
              final newRoute =
                  routes[navItem.route] ?? navItem.route.appRoute;
              context.router.navigateTo(newRoute);
            }
            break;
          case BottomNavStackBehavior.clearNavStack:
            // Always navigate to the bottom-most page in the route
            context.router.navigateTo(navItem.route.appRoute);
            break;
        }
      },
      icon: Icon(
        currentNavItem == navItem ? navItem.selectedIcon : navItem.icon,
      ),
      label: Text(navItem.getLabel(context)),
    ),
    child: Theme(
      data: context.theme.copyWith(
        pageTransitionsTheme: const _DealerServicePageTransitionsTheme(),
      ),
      child: NestedNavigatorBuilder<AppRootRoute>(
        currentKey: currentRoute,
        restorationScopeIdCallback: (rootRoute) =>
            'app-screen-navigator-${rootRoute.name}',
        navObserversBuilder: ref.watch(navObserversFactoryProvider),
        onDidRemovePage: (key, page) {
          final pageKey = page.key;
          if (pageKey is ValueKey<AppRoute>) {
            context.router.onDidPopAppRoute(pageKey.value);
          }
        },
        builders: {
          AppRootRoute.fleet: (context) => [
                MaterialPage(
                  key: const ValueKey<AppRoute>(AppRoute.fleet),
                  restorationId: 'fleet',
                  name: 'fleet',
                  child: FleetPage(
                    view: fleetView,
                    showingDashboard: fleetShowingDashboard,
                  ),
                ),
                ...fleetRoute.expandAncestors(
                  (ancestor) => [
                    if (ancestor is DeviceOverviewRoute)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId: 'fleet/${ancestor.id}',
                        name: 'device-overview',
                        child: DeviceOverviewPage(
                          deviceId: ancestor.id,
                        ),
                      )
                    else if (ancestor is DeviceRedirectRoute)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId:
                            'fleet/device/${ancestor.serialNumber}',
                        name: 'device-redirect',
                        child: DeviceRedirectPage(
                          serialNumber: ancestor.serialNumber,
                          appRoute: AppRoute.deviceOverview,
                        ),
                      )
                    else if (ancestor is EventsRedirectRoute)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId:
                            'fleet/device/events/${ancestor.serialNumber}',
                        name: 'events-redirect',
                        child: DeviceRedirectPage(
                          serialNumber: ancestor.serialNumber,
                          appRoute: AppRoute.deviceEvents,
                        ),
                      )
                    else if (ancestor is DeviceEventsRoute)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId: 'fleet/${ancestor.id}/events',
                        name: 'events-log',
                        child: AppEventsPage(
                          deviceId: ancestor.id,
                          resetFaultsEnabled: true,
                          title: EventsPageTitle(deviceId: ancestor.id),
                        ),
                      )
                    else if (ancestor is GeneratorTrendsRoute)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId:
                            'fleet/${ancestor.id}/${ancestor.arg.path}',
                        name: 'trend-${ancestor.arg.path}',
                        child: GeneratorTrendsPage(
                          generatorId: ancestor.id,
                          trend: ancestor.arg.apiTrend,
                          timeSpan: ancestor.t?.apiTime,
                        ),
                      ),
                  ],
                ),
              ],
          AppRootRoute.notifications: (context) => const [
                MaterialPage(
                  key: ValueKey<AppRoute>(AppRoute.notifications),
                  restorationId: 'notifications',
                  name: 'notifications',
                  child: NotificationsPage(),
                ),
              ],
          AppRootRoute.profile: (context) => [
                const MaterialPage(
                  key: ValueKey<AppRoute>(AppRoute.profile),
                  restorationId: 'profile',
                  name: 'profile',
                  child: ProfilePage(),
                ),
                ...profileRoute.expandAncestors(
                  (ancestor) => [
                    if (ancestor == AppRoute.profileResources)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId: 'profile/resources',
                        name: 'resource-links',
                        child: const ResourceLinksPage(),
                      ),
                    if (ancestor == AppRoute.profileCompany)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId: 'profile/company',
                        name: 'company-info',
                        child: const CompanyInformationPage(),
                      ),
                    if (ancestor == AppRoute.profileTeam)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId: 'profile/team',
                        name: 'view-team',
                        child: const ViewTeamPage(),
                      ),
                    if (ancestor == AppRoute.profileTermsAndConditions)
                      MaterialPage(
                        key: ValueKey<AppRoute>(ancestor),
                        restorationId: 'profile/termsandconditions',
                        name: 'profile-termsandconditions',
                        child: TermsAndConditionsPage(
                          breadcrumbTitle: BreadcrumbTitle(
                            children: [
                              Breadcrumb(
                                onPressed: () {
                                  context.logBreadcrumb('my_profile');
                                  Actions.invoke(
                                    context,
                                    const NavigateIntent(AppRoute.profile),
                                  );
                                },
                                child: Text(context.l10n.myProfile),
                              ),
                              Breadcrumb(
                                onPressed: null,
                                child: Text(context.l10n.moreInformation),
                              ),
                            ],
                          ),
                        ),
                      ),
                  ],
                ),
              ],
        },
      ),
    ),
  );

  void handleNavToDeviceAction(NavToDeviceAction action) {
    final id = action.deviceId;
    final serialNumber = action.serialNumber;

    if (id != null) {
      context.router.navigateTo(AppRoute.deviceEvents(id));
    } else if (serialNumber != null) {
      context.router.navigateTo(AppRoute.eventsRedirect(serialNumber));
    }
  }

  return Material(
    child: NotificationProcessor(
      onAction: (action) => switch (action) {
        NavToDeviceAction() => handleNavToDeviceAction(action),
        _ => null,
      },
      foregroundMessageHandler: (message) =>
          handleForegroundMessage(context, message),
      backgroundMessageHandler: handleBackgroundMessage,
      child: body,
    ),
  );
}