flutter/examples/api
Justin McCandless dedd100ebd
Predictive back support for root routes (#120385)
This PR aims to support Android's predictive back gesture when popping the entire Flutter app.  Predictive route transitions between routes inside of a Flutter app will come later.

<img width="200" src="https://user-images.githubusercontent.com/389558/217918109-945febaa-9086-41cc-a476-1a189c7831d8.gif" />

### Trying it out

If you want to try this feature yourself, here are the necessary steps:

  1. Run Android 33 or above.
  1. Enable the feature flag for predictive back on the device under "Developer
     options".
  1. Create a Flutter project, or clone [my example project](https://github.com/justinmc/flutter_predictive_back_examples).
  1. Set `android:enableOnBackInvokedCallback="true"` in
     android/app/src/main/AndroidManifest.xml (already done in the example project).
  1. Check out this branch.
  1. Run the app. Perform a back gesture (swipe from the left side of the
     screen).

You should see the predictive back animation like in the animation above and be able to commit or cancel it.

### go_router support

go_router works with predictive back out of the box because it uses a Navigator internally that dispatches NavigationNotifications!

~~go_router can be supported by adding a listener to the router and updating SystemNavigator.setFrameworkHandlesBack.~~

Similar to with nested Navigators, nested go_routers is supported by using a PopScope widget.

<details>

<summary>Full example of nested go_routers</summary>

```dart
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:go_router/go_router.dart';

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

void main() => runApp(_MyApp());

class _MyApp extends StatelessWidget {
  final GoRouter router = GoRouter(
    routes: <RouteBase>[
      GoRoute(
        path: '/',
        builder: (BuildContext context, GoRouterState state) => _HomePage(),
      ),
      GoRoute(
        path: '/nested_navigators',
        builder: (BuildContext context, GoRouterState state) => _NestedGoRoutersPage(),
      ),
    ],
  );

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
    );
  }
}

class _HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Nested Navigators Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text('Home Page'),
            const Text('A system back gesture here will exit the app.'),
            const SizedBox(height: 20.0),
            ListTile(
              title: const Text('Nested go_router route'),
              subtitle: const Text('This route has another go_router in addition to the one used with MaterialApp above.'),
              onTap: () {
                context.push('/nested_navigators');
              },
            ),
          ],
        ),
      ),
    );
  }
}

class _NestedGoRoutersPage extends StatefulWidget {
  @override
  State<_NestedGoRoutersPage> createState() => _NestedGoRoutersPageState();
}

class _NestedGoRoutersPageState extends State<_NestedGoRoutersPage> {
  late final GoRouter _router;
  final GlobalKey<NavigatorState> _nestedNavigatorKey = GlobalKey<NavigatorState>();

  // If the nested navigator has routes that can be popped, then we want to
  // block the root navigator from handling the pop so that the nested navigator
  // can handle it instead.
  bool get _popEnabled {
    // canPop will throw an error if called before build. Is this the best way
    // to avoid that?
    return _nestedNavigatorKey.currentState == null ? true : !_router.canPop();
  }

  void _onRouterChanged() {
    // Here the _router reports the location correctly, but canPop is still out
    // of date.  Hence the post frame callback.
    SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
      setState(() {});
    });
  }

  @override
  void initState() {
    super.initState();

    final BuildContext rootContext = context;
    _router = GoRouter(
      navigatorKey: _nestedNavigatorKey,
      routes: [
        GoRoute(
          path: '/',
          builder: (BuildContext context, GoRouterState state) => _LinksPage(
            title: 'Nested once - home route',
            backgroundColor: Colors.indigo,
            onBack: () {
              rootContext.pop();
            },
            buttons: <Widget>[
              TextButton(
                onPressed: () {
                  context.push('/two');
                },
                child: const Text('Go to another route in this nested Navigator'),
              ),
            ],
          ),
        ),
        GoRoute(
          path: '/two',
          builder: (BuildContext context, GoRouterState state) => _LinksPage(
            backgroundColor: Colors.indigo.withBlue(255),
            title: 'Nested once - page two',
          ),
        ),
      ],
    );

    _router.addListener(_onRouterChanged);
  }

  @override
  void dispose() {
    _router.removeListener(_onRouterChanged);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      popEnabled: _popEnabled,
      onPopped: (bool success) {
        if (success) {
          return;
        }
        _router.pop();
      },
      child: Router<Object>.withConfig(
        restorationScopeId: 'router-2',
        config: _router,
      ),
    );
  }
}

class _LinksPage extends StatelessWidget {
  const _LinksPage ({
    required this.backgroundColor,
    this.buttons = const <Widget>[],
    this.onBack,
    required this.title,
  });

  final Color backgroundColor;
  final List<Widget> buttons;
  final VoidCallback? onBack;
  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(title),
            //const Text('A system back here will go back to Nested Navigators Page One'),
            ...buttons,
            TextButton(
              onPressed: onBack ?? () {
                context.pop();
              },
              child: const Text('Go back'),
            ),
          ],
        ),
      ),
    );
  }
}
```

</details>

### Resources

Fixes https://github.com/flutter/flutter/issues/109513
Depends on engine PR https://github.com/flutter/engine/pull/39208 ✔️ 
Design doc: https://docs.google.com/document/d/1BGCWy1_LRrXEB6qeqTAKlk-U2CZlKJ5xI97g45U7azk/edit#
Migration guide: https://github.com/flutter/website/pull/8952
2023-08-04 20:44:44 +00:00
..
android Fix warning in flutter created project ("package attribute is deprecated" in AndroidManifest) (#123426) 2023-03-29 04:21:03 +00:00
ios iOS info.plist template: make UIViewControllerBasedStatusBar to be true (#128970) 2023-06-20 18:11:18 +00:00
lib Predictive back support for root routes (#120385) 2023-08-04 20:44:44 +00:00
linux Deletes files that should be ignored (#127984) 2023-06-29 19:45:22 +00:00
macos Migrate Xcode projects last version checks to Xcode 14.3 (#125827) 2023-05-02 00:06:33 +00:00
test Predictive back support for root routes (#120385) 2023-08-04 20:44:44 +00:00
test_driver Add smoke tests for all the examples, fix 17 broken examples. (#89021) 2021-09-28 09:32:06 -07:00
web Fix example app names and copyrights (#100795) 2022-03-25 17:40:11 -07:00
windows Deletes files that should be ignored (#127984) 2023-06-29 19:45:22 +00:00
.metadata Fix example app names and copyrights (#100795) 2022-03-25 17:40:11 -07:00
analysis_options.yaml Enable unreachable_from_main lint - it is stable now!!1 (#129854) 2023-07-06 00:09:01 +00:00
pubspec.yaml Upgrade packages. (#131927) 2023-08-04 08:09:00 -07:00
README.md Add example examples (#111276) 2022-09-12 20:28:09 +00:00

API Example Code

This directory contains the API sample code that is referenced from the API documentation in the framework.

The examples can be run individually by just specifying the path to the example on the command line (or in the run configuration of an IDE).

For example (no pun intended!), to run the first example from the Curve2D class in Chrome, you would run it like so from the api directory:

% flutter run -d chrome lib/animation/curves/curve2_d.0.dart

All of these same examples are available on the API docs site. For instance, the example above is available on this page. Most of the samples are available as interactive examples in Dartpad, but some (the ones marked with {@tool sample} in the framework source code), just don't make sense on the web, and so are available as standalone examples that can be run here. For instance, setting the system overlay style doesn't make sense on the web (it only changes the notification area background color on Android), so you can run the example for that on an Android device like so:

% flutter run -d MyAndroidDevice lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.1.dart

Naming

lib/library/file/class_name.n.dart

lib/library/file/class_name.member_name.n.dart

The naming scheme for the files is similar to the hierarchy under packages/flutter/lib/src, except that the files are represented as directories (without the .dart suffix), and each sample in the file is a separate file in that directory. So, for the example above, where the examples are from the packages/flutter/lib/src/animation/curves.dart file, the Curve2D class, the first sample (hence the index "0") for that symbol resides in the file named lib/animation/curves/curve2_d.0.dart.

Symbol names are converted from "CamelCase" to "snake_case". Dots are left between symbol names, so the first example for symbol InputDecoration.prefixIconConstraints would be converted to input_decoration.prefix_icon_constraints.0.dart.

If the same example is linked to from multiple symbols, the source will be in the canonical location for one of the symbols, and the link in the API docs block for the other symbols will point to the first symbol's example location.

Authoring

For more detailed information about authoring examples, see the snippets package.

When authoring examples, first place a block in the Dartdoc documentation for the symbol you would like to attach it to. Here's what it might look like if you wanted to add a new example to the Curve2D class:

/// {@tool dartpad}
/// Write a description of the example here. This description will appear in the
/// API web documentation to introduce the example.
///
/// ** See code in examples/api/lib/animation/curves/curve2_d.0.dart **
/// {@end-tool}

The "See code in" line needs to be formatted exactly as above, with no wrapping or newlines, one space after the "**" at the beginning, and one space before the "**" at the end, and the words "See code in" at the beginning of the line. This is what the snippets tool use when finding the example source code that you are creating.

Use {@tool dartpad} for Dartpad examples, and use {@tool sample} for examples that shouldn't be run/shown in Dartpad.

Once that comment block is inserted in the source code, create a new file at the appropriate path under examples/api. See the sample_templates directory for examples of different types of samples with some best practices applied.

The filename should match the location of the source file it is linked from, and is named for the symbol it is attached to, in lower_snake_case, with an index relating to their order within the doc comment. So, for the Curve2D example above, since it's in the animation library, in a file called curves.dart, and it's the first example, it should have the name examples/api/lib/animation/curves/curve2_d.0.dart.

You should also add tests for your sample code under examples/api/test, that matches their location under lib, ending in _test.dart. See the section on writing tests for more information on what kinds of tests to write.

The entire example should be in a single file, so that Dartpad can load it.

Only packages that can be loaded by Dartpad may be imported. If you use one that hasn't been used in an example before, you may have to add it to the pubspec.yaml in the api directory.

Snippets

There is another type of example that can also be authored, using {@tool snippet}. Snippet examples are just written inline in the source, like so:

/// {@tool dartpad}
/// Write a description of the example here. This description will appear in the
/// API web documentation to introduce the example.
///
/// ```dart
/// // Sample code goes here, e.g.:
/// const Widget emptyBox = SizedBox();
/// ```
/// {@end-tool}

The source for these snippets isn't stored under the examples/api directory, or available in Dartpad in the API docs, since they're not intended to be runnable, they just show some incomplete snippet of example code. It must compile (in the context of the sample analyzer), but doesn't need to do anything. See the snippets documentation for more information about the context that the analyzer uses.

Writing Tests

Examples are required to have tests. There is already a "smoke test" that simply builds and runs all the API examples, just to make sure that they start up without crashing. Functionality tests are required the examples, and generally just do what is normally done for writing tests. The one thing that makes it more challenging to do for examples is that they can't really be written for testability in any obvious way, since that would complicate the examples and make them harder to explain.

As an example, in regular framework code, you might include a parameter for a Platform object that can be overridden by a test to supply a dummy platform, but in the example. This would be unnecessarily complex for the example. In all other ways, these are just normal tests. You don't need to re-test the functionality of the widget being used in the example, but you should test the functionality and integrity of the example itself.

Tests go into a directory under test that matches their location under lib. They are named the same as the example they are testing, with _test.dart at the end, like other tests. For instance, a LayoutBuilder example that resides in lib/widgets/layout_builder/layout_builder.0.dart would have its tests in a file named test/widgets/layout_builder/layout_builder.0_test.dart