<topic_start>
flutter for android developers
this document is meant for android developers looking to apply their
existing android knowledge to build mobile apps with flutter.
if you understand the fundamentals of the android framework then you
can use this document as a jump start to flutter development.
info note
  to integrate flutter code into your android app, see
  add flutter to existing app.
your android knowledge and skill set are highly valuable when building with
flutter, because flutter relies on the mobile operating system for numerous
capabilities and configurations. flutter is a new way to build UIs for mobile,
but it has a plugin system to communicate with android (and iOS) for non-UI
tasks. if you’re an expert with android, you don’t have to relearn everything
to use flutter.
this document can be used as a cookbook by jumping around and
finding questions that are most relevant to your needs.
<topic_end>
<topic_start>
views
<topic_end>
<topic_start>
what is the equivalent of a view in flutter?
how is react-style, or declarative, programming different than the
  traditional imperative style?
  for a comparison, see introduction to declarative UI.
in android, the view is the foundation of everything that shows up on the
screen. buttons, toolbars, and inputs, everything is a view.
in flutter, the rough equivalent to a view is a widget.
widgets don’t map exactly to android views, but while you’re getting
acquainted with how flutter works you can think of them as
“the way you declare and construct UI”.
however, these have a few differences to a view. to start, widgets have a
different lifespan: they are immutable and only exist until they need to be
changed. whenever widgets or their state change, flutter’s framework creates
a new tree of widget instances. in comparison, an android view is drawn once
and does not redraw until invalidate is called.
flutter’s widgets are lightweight, in part due to their immutability.
because they aren’t views themselves, and aren’t directly drawing anything,
but rather are a description of the UI and its semantics that get “inflated”
into actual view objects under the hood.
flutter includes the material components library.
these are widgets that implement the
material design guidelines. material design is a
flexible design system optimized for all platforms,
including iOS.
but flutter is flexible and expressive enough to implement any design language.
for example, on iOS, you can use the cupertino widgets
to produce an interface that looks like apple’s iOS design language.
<topic_end>
<topic_start>
how do i update widgets?
in android, you update your views by directly mutating them. however,
in flutter, widgets are immutable and are not updated directly,
instead you have to work with the widget’s state.
this is where the concept of stateful and stateless widgets comes from.
a StatelessWidget is just what it sounds like—a
widget with no state information.
StatelessWidgets are useful when the part of the user interface
you are describing does not depend on anything other than the configuration
information in the object.
for example, in android, this is similar to placing an ImageView
with your logo. the logo is not going to change during runtime,
so use a StatelessWidget in flutter.
if you want to dynamically change the UI based on data received
after making an HTTP call or user interaction then you have to work
with StatefulWidget and tell the flutter framework that the widget’s
state has been updated so it can update that widget.
the important thing to note here is at the core both stateless and stateful
widgets behave the same. they rebuild every frame, the difference is the
StatefulWidget has a state object that stores state data across frames
and restores it.
if you are in doubt, then always remember this rule: if a widget changes
(because of user interactions, for example) it’s stateful.
however, if a widget reacts to change, the containing parent widget can
still be stateless if it doesn’t itself react to change.
the following example shows how to use a StatelessWidget. a common
StatelessWidget is the text widget. if you look at the implementation of
the text widget you’ll find that it subclasses StatelessWidget.
<code_start>
text(
  'i like flutter!',
  style: TextStyle(fontWeight: FontWeight.bold),
);
<code_end>
as you can see, the text widget has no state information associated with it,
it renders what is passed in its constructors and nothing more.
but, what if you want to make “i like flutter” change dynamically, for
example when clicking a FloatingActionButton?
to achieve this, wrap the text widget in a StatefulWidget and
update it when the user clicks the button.
for example:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  // default placeholder text.
  string textToShow = 'i like flutter';
  void _updateText() {
    setState(() {
      // update the text.
      textToShow = 'flutter is awesome!';
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: center(child: Text(textToShow)),
      floatingActionButton: FloatingActionButton(
        onPressed: _updateText,
        tooltip: 'update text',
        child: const Icon(Icons.update),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i lay out my widgets? where is my XML layout file?
in android, you write layouts in XML, but in flutter you write your layouts
with a widget tree.
the following example shows how to display a simple widget with padding:
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(
      title: const Text('Sample app'),
    ),
    body: center(
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.only(left: 20, right: 30),
        ),
        onPressed: () {},
        child: const Text('Hello'),
      ),
    ),
  );
}
<code_end>
you can view some of the layouts that flutter has to offer in the
widget catalog.
<topic_end>
<topic_start>
how do i add or remove a component from my layout?
in android, you call addChild() or removeChild()
on a parent to dynamically add or remove child views.
in flutter, because widgets are immutable there is
no direct equivalent to addChild().  instead,
you can pass a function to the parent that returns a widget,
and control that child’s creation with a boolean flag.
for example, here is how you can toggle between two
widgets when you click on a FloatingActionButton:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  // default value for toggle.
  bool toggle = true;
  void _toggle() {
    setState(() {
      toggle = !toggle;
    });
  }
  widget _getToggleChild() {
    if (toggle) {
      return const Text('Toggle one');
    } else {
      return ElevatedButton(
        onPressed: () {},
        child: const Text('Toggle two'),
      );
    }
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: center(
        child: _getToggleChild(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _toggle,
        tooltip: 'update text',
        child: const Icon(Icons.update),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i animate a widget?
in android, you either create animations using XML, or call the animate()
method on a view. in flutter, animate widgets using the animation
library by wrapping widgets inside an animated widget.
in flutter, use an AnimationController which is an animation<double>
that can pause, seek, stop and reverse the animation. it requires a ticker
that signals when vsync happens, and produces a linear interpolation between
0 and 1 on each frame while it’s running. you then create one or more
animations and attach them to the controller.
for example, you might use CurvedAnimation to implement an animation
along an interpolated curve. in this sense, the controller
is the “master” source of the animation progress and the CurvedAnimation
computes the curve that replaces the controller’s default linear motion.
like widgets, animations in flutter work with composition.
when building the widget tree you assign the animation to an animated
property of a widget, such as the opacity of a FadeTransition, and tell the
controller to start the animation.
the following example shows how to write a FadeTransition that fades the
widget into a logo when you press the FloatingActionButton:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const FadeAppTest());
}
class FadeAppTest extends StatelessWidget {
  const FadeAppTest({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'fade demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyFadeTest(title: 'fade demo'),
    );
  }
}
class MyFadeTest extends StatefulWidget {
  const MyFadeTest({super.key, required this.title});
  final string title;
  @override
  State<MyFadeTest> createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
  late AnimationController controller;
  late CurvedAnimation curve;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const duration(milliseconds: 2000),
      vsync: this,
    );
    curve = CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn,
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(widget.title),
      ),
      body: center(
        child: FadeTransition(
          opacity: curve,
          child: const FlutterLogo(
            size: 100,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        tooltip: 'fade',
        onPressed: () {
          controller.forward();
        },
        child: const Icon(Icons.brush),
      ),
    );
  }
}
<code_end>
for more information, see
animation & motion widgets,
the animations tutorial,
and the animations overview.
<topic_end>
<topic_start>
how do i use a canvas to draw/paint?
in android, you would use the canvas and drawable
to draw images and shapes to the screen.
flutter has a similar canvas API as well,
since it’s based on the same low-level rendering engine, skia.
as a result, painting to a canvas in flutter
is a very familiar task for android developers.
flutter has two classes that help you draw to the canvas: CustomPaint
and CustomPainter,
the latter of which implements your algorithm to draw to the canvas.
to learn how to implement a signature painter in flutter,
see collin’s answer on custom paint.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: DemoApp()));
class DemoApp extends StatelessWidget {
  const DemoApp({super.key});
  @override
  widget build(BuildContext context) => const scaffold(body: signature());
}
class signature extends StatefulWidget {
  const signature({super.key});
  @override
  SignatureState createState() => SignatureState();
}
class SignatureState extends State<Signature> {
  List<Offset?> _points = <offset>[];
  @override
  widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (details) {
        setState(() {
          RenderBox? referenceBox = context.findRenderObject() as RenderBox;
          offset localPosition =
              referenceBox.globalToLocal(details.globalPosition);
          _points = List.from(_points)..add(localPosition);
        });
      },
      onPanEnd: (details) => _points.add(null),
      child: CustomPaint(
        painter: SignaturePainter(_points),
        size: size.infinite,
      ),
    );
  }
}
class SignaturePainter extends CustomPainter {
  SignaturePainter(this.points);
  final List<Offset?> points;
  @override
  void paint(Canvas canvas, size size) {
    var paint = paint()
      ..color = colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i]!, points[i + 1]!, paint);
      }
    }
  }
  @override
  bool shouldRepaint(SignaturePainter oldDelegate) =>
      oldDelegate.points != points;
}
<code_end>
<topic_end>
<topic_start>
how do i build custom widgets?
in android, you typically subclass view, or use a pre-existing view,
to override and implement methods that achieve the desired behavior.
in flutter, build a custom widget by composing
smaller widgets (instead of extending them).
it is somewhat similar to implementing a custom ViewGroup
in android, where all the building blocks are already existing,
but you provide a different behavior—for example,
custom layout logic.
for example, how do you build a CustomButton that takes a label in
the constructor? create a CustomButton that composes a ElevatedButton with
a label, rather than by extending ElevatedButton:
<code_start>
class CustomButton extends StatelessWidget {
  final string label;
  const CustomButton(this.label, {super.key});
  @override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: text(label),
    );
  }
}
<code_end>
then use CustomButton, just as you’d use any other flutter widget:
<code_start>
@override
widget build(BuildContext context) {
  return const center(
    child: CustomButton('Hello'),
  );
}
<code_end>
<topic_end>
<topic_start>
intents
<topic_end>
<topic_start>
what is the equivalent of an intent in flutter?
in android, there are two main use cases for intents: navigating between
activities, and communicating with components. flutter, on the other hand,
does not have the concept of intents, although you can still start intents
through native integrations (using a plugin).
flutter doesn’t really have a direct equivalent to activities and fragments;
rather, in flutter you navigate between screens, using a navigator and
routes, all within the same activity.
a route is an abstraction for a “screen” or “page” of an app, and a
navigator is a widget that manages routes. a route roughly maps to an
activity, but it does not carry the same meaning. a navigator can push
and pop routes to move from screen to screen. navigators work like a stack
on which you can push() new routes you want to navigate to, and from
which you can pop() routes when you want to “go back”.
in android, you declare your activities inside the app’s AndroidManifest.xml.
in flutter, you have a couple options to navigate between pages:
the following example builds a map.
<code_start>
void main() {
  runApp(MaterialApp(
    home: const MyAppHome(), // becomes the route named '/'.
    routes: <string, WidgetBuilder>{
      '/a': (context) => const MyPage(title: 'page a'),
      '/b': (context) => const MyPage(title: 'page b'),
      '/c': (context) => const MyPage(title: 'page c'),
    },
  ));
}
<code_end>
navigate to a route by pushing its name to the navigator.
<code_start>
Navigator.of(context).pushNamed('/b');
<code_end>
the other popular use-case for intents is to call external components such
as a camera or file picker. for this, you would need to create a native platform
integration (or use an existing plugin).
to learn how to build a native platform integration,
see developing packages and plugins.
<topic_end>
<topic_start>
how do i handle incoming intents from external applications in flutter?
flutter can handle incoming intents from android by directly talking to the
android layer and requesting the data that was shared.
the following example registers a text share intent filter on the native
activity that runs our flutter code, so other apps can share text with
our flutter app.
the basic flow implies that we first handle the shared text data on the
android native side (in our activity), and then wait until flutter requests
for the data to provide it using a MethodChannel.
first, register the intent filter for all intents in AndroidManifest.xml:
then in MainActivity, handle the intent, extract the text that was
shared from the intent, and hold onto it. when flutter is ready to process,
it requests the data using a platform channel, and it’s sent
across from the native side:
finally, request the data from the flutter side
when the widget is rendered:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample shared app handler',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  static const platform = MethodChannel('app.channel.shared.data');
  string dataShared = 'no data';
  @override
  void initState() {
    super.initState();
    getSharedText();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(body: center(child: Text(dataShared)));
  }
  future<void> getSharedText() async {
    var sharedData = await platform.invokeMethod('getSharedText');
    if (shareddata != null) {
      setState(() {
        dataShared = sharedData;
      });
    }
  }
}
<code_end>
<topic_end>
<topic_start>
what is the equivalent of startActivityForResult()?
the navigator class handles routing in flutter and is used to get
a result back from a route that you have pushed on the stack.
this is done by awaiting on the future returned by push().
for example, to start a location route that lets the user select
their location, you could do the following:
<code_start>
object? coordinates = await Navigator.of(context).pushNamed('/location');
<code_end>
and then, inside your location route, once the user has selected their location
you can pop the stack with the result:
<code_start>
navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392});
<code_end>
<topic_end>
<topic_start>
async UI
<topic_end>
<topic_start>
what is the equivalent of runOnUiThread() in flutter?
dart has a single-threaded execution model, with support for isolates
(a way to run dart code on another thread), an event loop, and
asynchronous programming. unless you spawn an isolate, your dart code
runs in the main UI thread and is driven by an event loop. flutter’s event
loop is equivalent to android’s main looper—that is, the looper that
is attached to the main thread.
dart’s single-threaded model doesn’t mean you need to run everything as a
blocking operation that causes the UI to freeze. unlike android, which
requires you to keep the main thread free at all times, in flutter,
use the asynchronous facilities that the dart language provides, such as
async/await, to perform asynchronous work. you might be familiar with
the async/await paradigm if you’ve used it in c#, javascript, or if you
have used kotlin’s coroutines.
for example, you can run network code without causing the UI to hang by
using async/await and letting dart do the heavy lifting:
<code_start>
future<void> loadData() async {
  var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
  http.Response response = await http.get(dataURL);
  setState(() {
    widgets = jsonDecode(response.body);
  });
}
<code_end>
once the awaited network call is done, update the UI by calling setState(),
which triggers a rebuild of the widget subtree and updates the data.
the following example loads data asynchronously and displays it in a ListView:
<code_start>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  list widgets = [];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView.builder(
        itemCount: widgets.length,
        itemBuilder: (context, position) {
          return getRow(position);
        },
      ),
    );
  }
  widget getRow(int i) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text("Row ${widgets[i]["title"]}"),
    );
  }
  future<void> loadData() async {
    var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
    http.Response response = await http.get(dataURL);
    setState(() {
      widgets = jsonDecode(response.body);
    });
  }
}
<code_end>
refer to the next section for more information on doing work in the
background, and how flutter differs from android.
<topic_end>
<topic_start>
how do you move work to a background thread?
in android, when you want to access a network resource you would typically
move to a background thread and do the work, as to not block the main thread,
and avoid ANRs. for example, you might be using an AsyncTask, a LiveData,
an IntentService, a JobScheduler job, or an RxJava pipeline with a
scheduler that works on background threads.
since flutter is single threaded and runs an event loop (like node.js), you
don’t have to worry about thread management or spawning background threads. if
you’re doing I/O-bound work, such as disk access or a network call, then
you can safely use async/await and you’re all set. if, on the other
hand, you need to do computationally intensive work that keeps the CPU busy,
you want to move it to an isolate to avoid blocking the event loop, like
you would keep any sort of work out of the main thread in android.
for I/O-bound work, declare the function as an async function,
and await on long-running tasks inside the function:
<code_start>
future<void> loadData() async {
  var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
  http.Response response = await http.get(dataURL);
  setState(() {
    widgets = jsonDecode(response.body);
  });
}
<code_end>
this is how you would typically do network or database calls, which are both
I/O operations.
on android, when you extend AsyncTask, you typically override 3 methods,
onPreExecute(), doInBackground() and onPostExecute(). there is no
equivalent in flutter, since you await on a long-running function, and
dart’s event loop takes care of the rest.
however, there are times when you might be processing a large amount of data and
your UI hangs. in flutter, use isolates to take advantage of
multiple CPU cores to do long-running or computationally intensive tasks.
isolates are separate execution threads that do not share any memory
with the main execution memory heap. this means you can’t access variables from
the main thread, or update your UI by calling setState().
unlike android threads,
isolates are true to their name, and cannot share memory
(in the form of static fields, for example).
the following example shows, in a simple isolate, how to share data back to
the main thread to update the UI.
<code_start>
future<void> loadData() async {
  ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(dataLoader, receivePort.sendPort);
  // the 'echo' isolate sends its SendPort as the first message.
  SendPort sendPort = await receivePort.first;
  list msg = await sendReceive(
    sendPort,
    'https://jsonplaceholder.typicode.com/posts',
  );
  setState(() {
    widgets = msg;
  });
}
// the entry point for the isolate.
static future<void> dataLoader(SendPort sendPort) async {
  // open the ReceivePort for incoming messages.
  ReceivePort port = ReceivePort();
  // notify any other isolates what port this isolate listens to.
  sendPort.send(port.sendPort);
  await for (var msg in port) {
    string data = msg[0];
    SendPort replyTo = msg[1];
    string dataURL = data;
    http.Response response = await http.get(Uri.parse(dataURL));
    // lots of JSON to parse
    replyTo.send(jsonDecode(response.body));
  }
}
future sendReceive(SendPort port, msg) {
  ReceivePort response = ReceivePort();
  port.send([msg, response.sendPort]);
  return response.first;
}
<code_end>
here, dataLoader() is the isolate that runs in its own separate
execution thread.  in the isolate you can perform more CPU intensive
processing (parsing a big JSON, for example),
or perform computationally intensive math,
such as encryption or signal processing.
you can run the full example below:
<code_start>
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  list widgets = [];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  widget getBody() {
    bool showLoadingDialog = widgets.isEmpty;
    if (showloadingdialog) {
      return getProgressDialog();
    } else {
      return getListView();
    }
  }
  widget getProgressDialog() {
    return const center(child: CircularProgressIndicator());
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: getBody(),
    );
  }
  ListView getListView() {
    return ListView.builder(
      itemCount: widgets.length,
      itemBuilder: (context, position) {
        return getRow(position);
      },
    );
  }
  widget getRow(int i) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text("Row ${widgets[i]["title"]}"),
    );
  }
  future<void> loadData() async {
    ReceivePort receivePort = ReceivePort();
    await Isolate.spawn(dataLoader, receivePort.sendPort);
    // the 'echo' isolate sends its SendPort as the first message.
    SendPort sendPort = await receivePort.first;
    list msg = await sendReceive(
      sendPort,
      'https://jsonplaceholder.typicode.com/posts',
    );
    setState(() {
      widgets = msg;
    });
  }
  // the entry point for the isolate.
  static future<void> dataLoader(SendPort sendPort) async {
    // open the ReceivePort for incoming messages.
    ReceivePort port = ReceivePort();
    // notify any other isolates what port this isolate listens to.
    sendPort.send(port.sendPort);
    await for (var msg in port) {
      string data = msg[0];
      SendPort replyTo = msg[1];
      string dataURL = data;
      http.Response response = await http.get(Uri.parse(dataURL));
      // lots of JSON to parse
      replyTo.send(jsonDecode(response.body));
    }
  }
  future sendReceive(SendPort port, msg) {
    ReceivePort response = ReceivePort();
    port.send([msg, response.sendPort]);
    return response.first;
  }
}
<code_end>
<topic_end>
<topic_start>
what is the equivalent of OkHttp on flutter?
making a network call in flutter is easy when you use the
popular http package.
while the http package doesn’t have every feature found in OkHttp,
it abstracts away much of the networking that you would normally implement
yourself, making it a simple way to make network calls.
to add the http package as a dependency, run flutter pub add:
to make a network call, call await on the async function http.get():
<code_start>
import 'dart:developer' as developer;
import 'package:http/http.dart' as http;
future<void> loadData() async {
  var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
  http.Response response = await http.get(dataURL);
  developer.log(response.body);
}
<code_end>
<topic_end>
<topic_start>
how do i show the progress for a long-running task?
in android you would typically show a ProgressBar view in your UI while
executing a long-running task on a background thread.
in flutter, use a ProgressIndicator widget.
show the progress programmatically by controlling when it’s rendered
through a boolean flag. tell flutter to update its state before your
long-running task starts, and hide it after it ends.
in the following example, the build function is separated into three different
functions. if showLoadingDialog is true (when widgets.isEmpty),
then render the ProgressIndicator. otherwise, render the
ListView with the data returned from a network call.
<code_start>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  list widgets = [];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  widget getBody() {
    bool showLoadingDialog = widgets.isEmpty;
    if (showloadingdialog) {
      return getProgressDialog();
    } else {
      return getListView();
    }
  }
  widget getProgressDialog() {
    return const center(child: CircularProgressIndicator());
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: getBody(),
    );
  }
  ListView getListView() {
    return ListView.builder(
      itemCount: widgets.length,
      itemBuilder: (context, position) {
        return getRow(position);
      },
    );
  }
  widget getRow(int i) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text("Row ${widgets[i]["title"]}"),
    );
  }
  future<void> loadData() async {
    var dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
    http.Response response = await http.get(dataURL);
    setState(() {
      widgets = jsonDecode(response.body);
    });
  }
}
<code_end>
<topic_end>
<topic_start>
project structure & resources
<topic_end>
<topic_start>
where do i store my resolution-dependent image files?
while android treats resources and assets as distinct items,
flutter apps have only assets. all resources that would live
in the res/drawable-* folders on android,
are placed in an assets folder for flutter.
flutter follows a simple density-based format like iOS.
assets might be 1.0x, 2.0x, 3.0x, or any other multiplier.
flutter doesn’t have dps but there are logical pixels,
which are basically the same as device-independent pixels.
flutter’s devicePixelRatio expresses the ratio
of physical pixels in a single logical pixel.
the equivalent to android’s density buckets are:
assets are located in any arbitrary folder—Flutter
has no predefined folder structure.
you declare the assets (with location) in
the pubspec.yaml file, and flutter picks them up.
assets stored in the native asset folder are
accessed on the native side using android’s AssetManager:
flutter can’t access native resources or assets.
to add a new image asset called my_icon.png to our flutter project,
for example, and deciding that it should live in a folder we
arbitrarily called images, you would put the base image (1.0x)
in the images folder, and all the other variants in sub-folders
called with the appropriate ratio multiplier:
next, you’ll need to declare these images in your pubspec.yaml file:
you can then access your images using AssetImage:
<code_start>
AssetImage('images/my_icon.jpeg')
<code_end>
or directly in an image widget:
<code_start>
@override
widget build(BuildContext context) {
  return image.asset('images/my_image.png');
}
<code_end>
<topic_end>
<topic_start>
where do i store strings? how do i handle localization?
flutter currently doesn’t have a dedicated resources-like system for strings.
the best and recommended practice is to hold your strings in a .arb file as key-value pairs for example:
<code_start>
{
   "@@locale": "en",
   "hello":"hello {username}",
   "@hello":{
      "description":"a message with a single parameter",
      "placeholders":{
         "username":{
            "type":"string",
            "example":"bob"
         }
      }
   }
}
<code_end>
then in your code, you can access your strings as such:
<code_start>
Text(AppLocalizations.of(context)!.hello('John'));
<code_end>
flutter has basic support for accessibility on android,
though this feature is a work in progress.
see internationalizing flutter apps for more information on this.
<topic_end>
<topic_start>
what is the equivalent of a gradle file? how do i add dependencies?
in android, you add dependencies by adding to your gradle build script.
flutter uses dart’s own build system, and the pub package manager.
the tools delegate the building of the native android and iOS
wrapper apps to the respective build systems.
while there are gradle files under the android folder in your
flutter project, only use these if you are adding native
dependencies needed for per-platform integration.
in general, use pubspec.yaml to declare
external dependencies to use in flutter.
a good place to find flutter packages is pub.dev.
<topic_end>
<topic_start>
activities and fragments
<topic_end>
<topic_start>
what are the equivalent of activities and fragments in flutter?
in android, an activity represents a single focused thing the user can do.
a fragment represents a behavior or a portion of user interface.
fragments are a way to modularize your code, compose sophisticated
user interfaces for larger screens, and help scale your application UI.
in flutter, both of these concepts fall under the umbrella of widgets.
to learn more about the UI for building activities and fragments,
see the community-contributed medium article,
flutter for android developers: how to design activity UI in flutter.
as mentioned in the intents section,
screens in flutter are represented by widgets since everything is
a widget in flutter. use a navigator to move between different
routes that represent different screens or pages,
or perhaps different states or renderings of the same data.
<topic_end>
<topic_start>
how do i listen to android activity lifecycle events?
in android, you can override methods from the activity to capture lifecycle
methods for the activity itself, or register ActivityLifecycleCallbacks on
the application. in flutter, you have neither concept, but you can instead
listen to lifecycle events by hooking into the WidgetsBinding observer and
listening to the didChangeAppLifecycleState() change event.
the observable lifecycle events are:
for more details on the meaning of these states, see the
AppLifecycleStatus documentation.
as you might have noticed, only a small minority of the activity
lifecycle events are available; while FlutterActivity does
capture almost all the activity lifecycle events internally and
send them over to the flutter engine, they’re mostly shielded
away from you. flutter takes care of starting and stopping the
engine for you, and there is little reason for needing to
observe the activity lifecycle on the flutter side in most cases.
if you need to observe the lifecycle to acquire or release any
native resources, you should likely be doing it from the native side,
at any rate.
here’s an example of how to observe the lifecycle status of the
containing activity:
<code_start>
import 'package:flutter/widgets.dart';
class LifecycleWatcher extends StatefulWidget {
  const LifecycleWatcher({super.key});
  @override
  State<LifecycleWatcher> createState() => _LifecycleWatcherState();
}
class _LifecycleWatcherState extends State<LifecycleWatcher>
    with WidgetsBindingObserver {
  AppLifecycleState? _lastLifecycleState;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _lastLifecycleState = state;
    });
  }
  @override
  widget build(BuildContext context) {
    if (_lastlifecyclestate == null) {
      return const text(
        'this widget has not observed any lifecycle changes.',
        textDirection: TextDirection.ltr,
      );
    }
    return text(
      'the most recent lifecycle state this widget observed was: $_lastLifecycleState.',
      textDirection: TextDirection.ltr,
    );
  }
}
void main() {
  runApp(const center(child: LifecycleWatcher()));
}
<code_end>
<topic_end>
<topic_start>
layouts
<topic_end>
<topic_start>
what is the equivalent of a LinearLayout?
in android, a LinearLayout is used to lay your widgets out
linearly—either horizontally or vertically.
in flutter, use the row or column
widgets to achieve the same result.
if you notice the two code samples are identical with the exception of the
“row” and “column” widget. the children are the same and this feature can be
exploited to develop rich layouts that can change overtime with the same
children.
<code_start>
@override
widget build(BuildContext context) {
  return const row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <widget>[
      Text('Row one'),
      Text('Row two'),
      Text('Row three'),
      Text('Row four'),
    ],
  );
}
<code_end>
<code_start>
@override
widget build(BuildContext context) {
  return const column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <widget>[
      Text('Column one'),
      Text('Column two'),
      Text('Column three'),
      Text('Column four'),
    ],
  );
}
<code_end>
to learn more about building linear layouts,
see the community-contributed medium article
flutter for android developers: how to design LinearLayout in flutter.
<topic_end>
<topic_start>
what is the equivalent of a RelativeLayout?
a RelativeLayout lays your widgets out relative to each other. in
flutter, there are a few ways to achieve the same result.
you can achieve the result of a RelativeLayout by using a combination of
column, row, and stack widgets. you can specify rules for the widgets
constructors on how the children are laid out relative to the parent.
for a good example of building a RelativeLayout in flutter,
see collin’s answer on StackOverflow.
<topic_end>
<topic_start>
what is the equivalent of a ScrollView?
in android, use a ScrollView to lay out your widgets—if the user’s
device has a smaller screen than your content, it scrolls.
in flutter, the easiest way to do this is using the ListView widget.
this might seem like overkill coming from android,
but in flutter a ListView widget is
both a ScrollView and an android ListView.
<code_start>
@override
widget build(BuildContext context) {
  return ListView(
    children: const <widget>[
      Text('Row one'),
      Text('Row two'),
      Text('Row three'),
      Text('Row four'),
    ],
  );
}
<code_end>
<topic_end>
<topic_start>
how do i handle landscape transitions in flutter?
FlutterView handles the config change if AndroidManifest.xml contains:
<topic_end>
<topic_start>
gesture detection and touch event handling
<topic_end>
<topic_start>
how do i add an onClick listener to a widget in flutter?
in android, you can attach onClick to views such as button by calling
the method ‘setonclicklistener’.
in flutter there are two ways of adding touch listeners:
<code_start>
@override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        developer.log('click');
      },
      child: const Text('Button'),
    );
  }
<code_end>
<code_start>
class SampleTapApp extends StatelessWidget {
    const SampleTapApp({super.key});
    @override
    widget build(BuildContext context) {
      return scaffold(
        body: center(
          child: GestureDetector(
            onTap: () {
              developer.log('tap');
            },
            child: const FlutterLogo(
              size: 200,
            ),
          ),
        ),
      );
    }
  }
<code_end>
<topic_end>
<topic_start>
how do i handle other gestures on widgets?
using the GestureDetector, you can listen to a wide range of gestures such as:
tap
double tap
long press
vertical drag
horizontal drag
the following example shows a GestureDetector
that rotates the flutter logo on a double tap:
<code_start>
class SampleApp extends StatefulWidget {
  const SampleApp({super.key});
  @override
  State<SampleApp> createState() => _SampleAppState();
}
class _SampleAppState extends State<SampleApp>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late CurvedAnimation curve;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const duration(milliseconds: 2000),
    );
    curve = CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn,
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: GestureDetector(
          onDoubleTap: () {
            if (controller.iscompleted) {
              controller.reverse();
            } else {
              controller.forward();
            }
          },
          child: RotationTransition(
            turns: curve,
            child: const FlutterLogo(
              size: 200,
            ),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
listviews & adapters
<topic_end>
<topic_start>
what is the alternative to a ListView in flutter?
the equivalent to a ListView in flutter is … a ListView!
in an android ListView, you create an adapter and pass it into the
ListView, which renders each row with what your adapter returns. however, you
have to make sure you recycle your rows, otherwise, you get all sorts of crazy
visual glitches and memory issues.
due to flutter’s immutable widget pattern, you pass a list of
widgets to your ListView, and flutter takes care of making sure
that scrolling is fast and smooth.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView(children: _getListData()),
    );
  }
  List<Widget> _getListData() {
    List<Widget> widgets = [];
    for (int i = 0; i < 100; i++) {
      widgets.add(Padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $i'),
      ));
    }
    return widgets;
  }
}
<code_end>
<topic_end>
<topic_start>
how do i know which list item is clicked on?
in android, the ListView has a method to find out which item was clicked,
‘onitemclicklistener’.
in flutter, use the touch handling provided by the passed-in widgets.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView(children: _getListData()),
    );
  }
  List<Widget> _getListData() {
    List<Widget> widgets = [];
    for (int i = 0; i < 100; i++) {
      widgets.add(
        GestureDetector(
          onTap: () {
            developer.log('row tapped');
          },
          child: padding(
            padding: const EdgeInsets.all(10),
            child: Text('Row $i'),
          ),
        ),
      );
    }
    return widgets;
  }
}
<code_end>
<topic_end>
<topic_start>
how do i update ListView’s dynamically?
on android, you update the adapter and call notifyDataSetChanged.
in flutter, if you were to update the list of widgets inside a setState(),
you would quickly see that your data did not change visually.
this is because when setState() is called, the flutter rendering engine
looks at the widget tree to see if anything has changed. when it gets to your
ListView, it performs a == check, and determines that the two
ListViews are the same. nothing has changed, so no update is required.
for a simple way to update your ListView, create a new list inside of
setState(), and copy the data from the old list to the new list.
while this approach is simple, it is not recommended for large data sets,
as shown in the next example.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> widgets = [];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 100; i++) {
      widgets.add(getRow(i));
    }
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView(children: widgets),
    );
  }
  widget getRow(int i) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widgets = list.from(widgets);
          widgets.add(getRow(widgets.length));
          developer.log('row $i');
        });
      },
      child: padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $i'),
      ),
    );
  }
}
<code_end>
the recommended, efficient, and effective way to build a list uses a
ListView.Builder. this method is great when you have a dynamic
list or a list with very large amounts of data. this is essentially
the equivalent of RecyclerView on android, which automatically
recycles list elements for you:
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> widgets = [];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 100; i++) {
      widgets.add(getRow(i));
    }
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView.builder(
        itemCount: widgets.length,
        itemBuilder: (context, position) {
          return getRow(position);
        },
      ),
    );
  }
  widget getRow(int i) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widgets.add(getRow(widgets.length));
          developer.log('row $i');
        });
      },
      child: padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $i'),
      ),
    );
  }
}
<code_end>
instead of creating a “listview”, create a
ListView.builder that takes two key parameters: the
initial length of the list, and an ItemBuilder function.
the ItemBuilder function is similar to the getView
function in an android adapter; it takes a position,
and returns the row you want rendered at that position.
finally, but most importantly, notice that the onTap() function
doesn’t recreate the list anymore, but instead .adds to it.
<topic_end>
<topic_start>
working with text
<topic_end>
<topic_start>
how do i set custom fonts on my text widgets?
in android SDK (as of android o), you create a font resource file and
pass it into the FontFamily param for your TextView.
in flutter, place the font file in a folder and reference it in the
pubspec.yaml file, similar to how you import images.
then assign the font to your text widget:
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(
      title: const Text('Sample app'),
    ),
    body: const center(
      child: text(
        'this is a custom font text',
        style: TextStyle(fontFamily: 'mycustomfont'),
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
how do i style my text widgets?
along with fonts, you can customize other styling elements on a text widget.
the style parameter of a text widget takes a TextStyle object, where you can
customize many parameters, such as:
<topic_end>
<topic_start>
form input
for more information on using forms,
see retrieve the value of a text field,
from the flutter cookbook.
<topic_end>
<topic_start>
what is the equivalent of a “hint” on an input?
in flutter, you can easily show a “hint” or a placeholder text for your input by
adding an InputDecoration object to the decoration constructor parameter for
the text widget.
<code_start>
center(
  child: TextField(
    decoration: InputDecoration(hintText: 'this is a hint'),
  ),
)
<code_end>
<topic_end>
<topic_start>
how do i show validation errors?
just as you would with a “hint”, pass an InputDecoration object
to the decoration constructor for the text widget.
however, you don’t want to start off by showing an error.
instead, when the user has entered invalid data,
update the state, and pass a new InputDecoration object.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  string? _errorText;
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: center(
        child: TextField(
          onSubmitted: (text) {
            setState(() {
              if (!isemail(text)) {
                _errorText = 'error: this is not an email';
              } else {
                _errorText = null;
              }
            });
          },
          decoration: InputDecoration(
            hintText: 'this is a hint',
            errorText: _getErrorText(),
          ),
        ),
      ),
    );
  }
  string? _getErrorText() {
    return _errorText;
  }
  bool isEmail(String em) {
    string emailRegexp =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|'
        r'(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|'
        r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regExp = RegExp(emailRegexp);
    return regExp.hasMatch(em);
  }
}
<code_end>
<topic_end>
<topic_start>
flutter plugins
<topic_end>
<topic_start>
how do i access the GPS sensor?
use the geolocator community plugin.
<topic_end>
<topic_start>
how do i access the camera?
the image_picker plugin is popular
for accessing the camera.
<topic_end>
<topic_start>
how do i log in with facebook?
to log in with facebook, use the
flutter_facebook_login community plugin.
<topic_end>
<topic_start>
how do i use firebase features?
most firebase functions are covered by
first party plugins.
these plugins are first-party integrations,
maintained by the flutter team:
you can also find some third-party firebase plugins on
pub.dev that cover areas not directly covered by the
first-party plugins.
<topic_end>
<topic_start>
how do i build my own custom native integrations?
if there is platform-specific functionality that flutter
or its community plugins are missing,
you can build your own following the
developing packages and plugins page.
flutter’s plugin architecture, in a nutshell, is much like using an event bus in
android: you fire off a message and let the receiver process and emit a result
back to you. in this case, the receiver is code running on the native side
on android or iOS.
<topic_end>
<topic_start>
how do i use the NDK in my flutter application?
if you use the NDK in your current android application and want your flutter
application to take advantage of your native libraries then it’s possible by
building a custom plugin.
your custom plugin first talks to your android app, where you call your
native functions over JNI. once a response is ready,
send a message back to flutter and render the result.
calling native code directly from flutter is currently not supported.
<topic_end>
<topic_start>
themes
<topic_end>
<topic_start>
how do i theme my app?
out of the box, flutter comes with a beautiful implementation of material
design, which takes care of a lot of styling and theming needs that you would
typically do. unlike android where you declare themes in XML and then assign it
to your application using AndroidManifest.xml, in flutter you declare themes
in the top level widget.
to take full advantage of material components in your app, you can declare a top
level widget MaterialApp as the entry point to your application. MaterialApp
is a convenience widget that wraps a number of widgets that are commonly
required for applications implementing material design.
it builds upon a WidgetsApp by adding material specific functionality.
you can also use a WidgetsApp as your app widget, which provides some of the
same functionality, but is not as rich as MaterialApp.
to customize the colors and styles of any child components, pass a
ThemeData object to the MaterialApp widget. for example, in the code below,
the color scheme from seed is set to deepPurple and text selection color is red.
<code_start>
import 'package:flutter/material.dart';
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        textSelectionTheme:
            const TextSelectionThemeData(selectionColor: colors.red),
      ),
      home: const SampleAppPage(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
databases and local storage
<topic_end>
<topic_start>
how do i access shared preferences?
in android, you can store a small collection of key-value pairs using
the SharedPreferences API.
in flutter, access this functionality using the
Shared_Preferences plugin.
this plugin wraps the functionality of both
shared preferences and NSUserDefaults (the iOS equivalent).
<code_start>
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
  runApp(
    const MaterialApp(
      home: scaffold(
        body: center(
          child: ElevatedButton(
            onPressed: _incrementCounter,
            child: Text('Increment counter'),
          ),
        ),
      ),
    ),
  );
}
future<void> _incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getint('counter') ?? 0) + 1;
  await prefs.setInt('counter', counter);
}
<code_end>
<topic_end>
<topic_start>
how do i access SQLite in flutter?
in android, you use SQLite to store structured data
that you can query using SQL.
in flutter, for macOS, android, or iOS,
access this functionality using the
SQFlite plugin.
<topic_end>
<topic_start>
debugging
<topic_end>
<topic_start>
what tools can i use to debug my app in flutter?
use the DevTools suite for debugging flutter or dart apps.
DevTools includes support for profiling, examining the heap,
inspecting the widget tree, logging diagnostics, debugging,
observing executed lines of code, debugging memory leaks and memory
fragmentation. for more information, see the
DevTools documentation.
<topic_end>
<topic_start>
notifications
<topic_end>
<topic_start>
how do i set up push notifications?
in android, you use firebase cloud messaging to set up
push notifications for your app.
in flutter, access this functionality using the
firebase messaging plugin.
for more information on using the firebase cloud messaging API,
see the firebase_messaging plugin documentation.
<topic_end>
<topic_start>
flutter for SwiftUI developers
SwiftUI developers who want to write mobile apps using flutter
should review this guide.
it explains how to apply existing SwiftUI knowledge to flutter.
info note
  if you instead have experience building apps for iOS with UIKit,
  see flutter for UIKit developers.
flutter is a framework for building cross-platform applications
that uses the dart programming language.
to understand some differences between programming with dart
and programming with swift, see learning dart as a swift developer
and flutter concurrency for swift developers.
your SwiftUI knowledge and experience
are highly valuable when building with flutter.
flutter also makes a number of adaptations
to app behavior when running on iOS and macOS.
to learn how, see platform adaptations.
info
  to integrate flutter code into an existing iOS app,
  check out add flutter to existing app.
this document can be used as a cookbook by jumping around
and finding questions that are most relevant to your needs.
this guide embeds sample code.
you can test full working examples on DartPad or view them on GitHub.
<topic_end>
<topic_start>
overview
as an introduction, watch the following video.
it outlines how flutter works on iOS and how to use flutter to build iOS apps.
flutter and SwiftUI code describes how the UI looks and works.
developers call this type of code a declarative framework.
<topic_end>
<topic_start>
views vs. widgets
SwiftUI represents UI components as views.
you configure views using modifiers.
flutter represents UI components as widgets.
both views and widgets only exist until they need to be changed.
these languages call this property immutability.
SwiftUI represents a UI component property as a view modifier.
by contrast, flutter uses widgets for both UI components and
their properties.
to compose layouts, both SwiftUI and flutter nest UI components
within one another.
SwiftUI nests views while flutter nests widgets.
<topic_end>
<topic_start>
layout process
SwiftUI lays out views using the following process:
flutter differs somewhat with its process:
flutter differs from SwiftUI because the parent component can override
the child’s desired size. the widget cannot have any size it wants.
it also cannot know or decide its position on screen as its parent
makes that decision.
to force a child widget to render at a specific size,
the parent must set tight constraints.
a constraint becomes tight when its constraint’s minimum size value
equals its maximum size value.
in SwiftUI, views might expand to the available space or
limit their size to that of its content.
flutter widgets behave in similar manner.
however, in flutter parent widgets can offer unbounded constraints.
unbounded constraints set their maximum values to infinity.
if the child expands and it has unbounded constraints,
flutter returns an overflow warning:
to learn how constraints work in flutter,
see understanding constraints.
<topic_end>
<topic_start>
design system
because flutter targets multiple platforms, your app doesn’t need
to conform to any design system.
though this guide features material widgets,
your flutter app can use many different design systems:
if you’re looking for a great reference app that features a
custom design system, check out wonderous.
<topic_end>
<topic_start>
UI basics
this section covers the basics of UI development in
flutter and how it compares to SwiftUI.
this includes how to start developing your app, display static text,
create buttons, react to on-press events, display lists, grids, and more.
<topic_end>
<topic_start>
getting started
in SwiftUI, you use app to start your app.
another common SwiftUI practice places the app body within a struct
that conforms to the view protocol as follows:
to start your flutter app, pass in an instance of your app to
the runApp function.
<code_start>
void main() {
  runApp(const MyApp());
}
<code_end>
app is a widget. the build method describes the part of the
user interface it represents.
it’s common to begin your app with a WidgetApp class,
like CupertinoApp.
<code_start>
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    // returns a CupertinoApp that, by default,
    // has the look and feel of an iOS app.
    return const CupertinoApp(
      home: HomePage(),
    );
  }
}
<code_end>
the widget used in HomePage might begin with the scaffold class.
scaffold implements a basic layout structure for an app.
<code_start>
class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  widget build(BuildContext context) {
    return const scaffold(
      body: center(
        child: text(
          'hello, world!',
        ),
      ),
    );
  }
}
<code_end>
note how flutter uses the center widget.
SwiftUI renders a view’s contents in its center by default.
that’s not always the case with flutter.
scaffold doesn’t render its body widget at the center of the screen.
to center the text, wrap it in a center widget.
to learn about different widgets and their default behaviors, check out
the widget catalog.
<topic_end>
<topic_start>
adding buttons
in SwiftUI, you use the button struct to create a button.
to achieve the same result in flutter,
use the CupertinoButton class:
<code_start>
        CupertinoButton(
  onPressed: () {
    // this closure is called when your button is tapped.
  },
  child: const Text('Do something'),
)
<code_end>
flutter gives you access to a variety of buttons with predefined styles.
the CupertinoButton class comes from the cupertino library.
widgets in the cupertino library use apple’s design system.
<topic_end>
<topic_start>
aligning components horizontally
in SwiftUI, stack views play a big part in designing your layouts.
two separate structures allow you to create stacks:
HStack for horizontal stack views
VStack for vertical stack views
the following SwiftUI view adds a globe image and
text to a horizontal stack view:
flutter uses row rather than HStack:
<code_start>
    row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Icon(CupertinoIcons.globe),
    Text('Hello, world!'),
  ],
),
<code_end>
the row widget requires a List<Widget> in the children parameter.
the mainAxisAlignment property tells flutter how to position children
with extra space. MainAxisAlignment.center positions children in the
center of the main axis. for row, the main axis is the horizontal
axis.
<topic_end>
<topic_start>
aligning components vertically
the following examples build on those in the previous section.
in SwiftUI, you use VStack to arrange the components into a
vertical pillar.
flutter uses the same dart code from the previous example,
except it swaps column for row:
<code_start>
    column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Icon(CupertinoIcons.globe),
    Text('Hello, world!'),
  ],
),
<code_end>
<topic_end>
<topic_start>
displaying a list view
in SwiftUI, you use the list base component to display sequences
of items.
to display a sequence of model objects, make sure that the user can
identify your model objects.
to make an object identifiable, use the identifiable protocol.
this resembles how flutter prefers to build its list widgets.
flutter doesn’t need the list items to be identifiable.
you set the number of items to display then build a widget for each item.
<code_start>
class person {
  string name;
  person(this.name);
}
var items = [
  Person('Person 1'),
  Person('Person 2'),
  Person('Person 3'),
];
class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: text(items[index].name),
          );
        },
      ),
    );
  }
}
<code_end>
flutter has some caveats for lists:
the ListView widget has a builder method.
this works like the ForEach within SwiftUI’s list struct.
the itemCount parameter of the ListView sets how many items
the ListView displays.
the itemBuilder has an index parameter that will be between zero
and one less than itemCount.
the previous example returned a ListTile widget for each item.
the ListTile widget includes properties like height and font-size.
these properties help build a list. however, flutter allows you to return
almost any widget that represents your data.
<topic_end>
<topic_start>
displaying a grid
when constructing non-conditional grids in SwiftUI,
you use grid with GridRow.
to display grids in flutter, use the GridView widget.
this widget has various constructors. each constructor has
a similar goal, but uses different input parameters.
the following example uses the .builder() initializer:
<code_start>
const widgets = [
  Text('Row 1'),
  Icon(CupertinoIcons.arrow_down_square),
  Icon(CupertinoIcons.arrow_up_square),
  Text('Row 2'),
  Icon(CupertinoIcons.arrow_down_square),
  Icon(CupertinoIcons.arrow_up_square),
];
class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          mainAxisExtent: 40,
        ),
        itemCount: widgets.length,
        itemBuilder: (context, index) => widgets[index],
      ),
    );
  }
}
<code_end>
the SliverGridDelegateWithFixedCrossAxisCount delegate determines
various parameters that the grid uses to lay out its components.
this includes crossAxisCount that dictates the number of items
displayed on each row.
how SwiftUI’s grid and flutter’s GridView differ in that grid
requires GridRow. GridView uses the delegate to decide how the
grid should lay out its components.
<topic_end>
<topic_start>
creating a scroll view
in SwiftUI, you use ScrollView to create custom scrolling
components.
the following example displays a series of PersonView instances
in a scrollable fashion.
to create a scrolling view, flutter uses SingleChildScrollView.
in the following example, the function mockPerson mocks instances
of the person class to create the custom PersonView widget.
<code_start>
    SingleChildScrollView(
  child: column(
    children: mockPersons
        .map(
          (person) => PersonView(
            person: person,
          ),
        )
        .tolist(),
  ),
),
<code_end>
<topic_end>
<topic_start>
responsive and adaptive design
in SwiftUI, you use GeometryReader to create relative view sizes.
for example, you could:
you can also see if the size class has .regular or .compact
using horizontalSizeClass.
to create relative views in flutter, you can use one of two options:
to learn more, check out creating responsive and adaptive apps.
<topic_end>
<topic_start>
managing state
in SwiftUI, you use the @state property wrapper to represent the
internal state of a SwiftUI view.
SwiftUI also includes several options for more complex state
management such as the ObservableObject protocol.
flutter manages local state using a StatefulWidget.
implement a stateful widget with the following two classes:
the state object stores the widget’s state.
to change a widget’s state, call setState() from the state subclass
to tell the framework to redraw the widget.
the following example shows a part of a counter app:
<code_start>
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            text('$_counter'),
            TextButton(
              onPressed: () => setState(() {
                _counter++;
              }),
              child: const text('+'),
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
to learn more ways to manage state, check out state management.
<topic_end>
<topic_start>
animations
two main types of UI animations exist.
<topic_end>
<topic_start>
implicit animation
SwiftUI and flutter take a similar approach to animation.
in both frameworks, you specify parameters like duration, and curve.
in SwiftUI, you use the animate() modifier to handle implicit
animation.
flutter includes widgets for implicit animation.
this simplifies animating common widgets.
flutter names these widgets with the following format: AnimatedFoo.
for example: to rotate a button, use the AnimatedRotation class.
this animates the transform.rotate widget.
<code_start>
    AnimatedRotation(
  duration: const duration(seconds: 1),
  turns: turns,
  curve: Curves.easeIn,
  child: TextButton(
      onPressed: () {
        setState(() {
          turns += .125;
        });
      },
      child: const Text('Tap me!')),
),
<code_end>
flutter allows you to create custom implicit animations.
to compose a new animated widget, use the TweenAnimationBuilder.
<topic_end>
<topic_start>
explicit animation
for explicit animations, SwiftUI uses the withAnimation() function.
flutter includes explicitly animated widgets with names formatted
like FooTransition.
one example would be the RotationTransition class.
flutter also allows you to create a custom explicit animation using
AnimatedWidget or AnimatedBuilder.
to learn more about animations in flutter, see animations overview.
<topic_end>
<topic_start>
drawing on the screen
in SwiftUI, you use CoreGraphics to draw lines and shapes to the
screen.
flutter has an API based on the canvas class,
with two classes that help you draw:
CustomPaint that requires a painter:
<code_start>
    CustomPaint(
   painter: SignaturePainter(_points),
   size: size.infinite,
 ),
<code_end>
CustomPainter that implements your algorithm to draw to the canvas.
<code_start>
class SignaturePainter extends CustomPainter {
   SignaturePainter(this.points);
   final List<Offset?> points;
   @override
   void paint(Canvas canvas, size size) {
     final paint paint = paint()
       ..color = colors.black
       ..strokeCap = StrokeCap.round
       ..strokeWidth = 5;
     for (int i = 0; i < points.length - 1; i++) {
       if (points[i] != null && points[i + 1] != null) {
         canvas.drawLine(points[i]!, points[i + 1]!, paint);
       }
     }
   }
   @override
   bool shouldRepaint(SignaturePainter oldDelegate) =>
       oldDelegate.points != points;
 }
<code_end>
<topic_end>
<topic_start>
navigation
this section explains how to navigate between pages of an app,
the push and pop mechanism, and more.
<topic_end>
<topic_start>
navigating between pages
developers build iOS and macOS apps with different pages called
navigation routes.
in SwiftUI, the NavigationStack represents this stack of pages.
the following example creates an app that displays a list of persons.
to display a person’s details in a new navigation link,
tap on that person.
if you have a small flutter app without complex linking,
use navigator with named routes.
after defining your navigation routes,
call your navigation routes using their names.
name each route in the class passed to the runApp() function.
the following example uses app:
<code_start>
// defines the route name as a constant
 // so that it's reusable.
 const detailsPageRouteName = '/details';
 class app extends StatelessWidget {
   const app({
     super.key,
   });
   @override
   widget build(BuildContext context) {
     return CupertinoApp(
       home: const HomePage(),
       // the [routes] property defines the available named routes
       // and the widgets to build when navigating to those routes.
       routes: {
         detailsPageRouteName: (context) => const DetailsPage(),
       },
     );
   }
 }
<code_end>
the following sample generates a list of persons using
mockPersons(). tapping a person pushes the person’s detail page
to the navigator using pushNamed().
<code_start>
    ListView.builder(
   itemCount: mockPersons.length,
   itemBuilder: (context, index) {
     final person = mockPersons.elementAt(index);
     final age = '${person.age} years old';
     return ListTile(
       title: text(person.name),
       subtitle: text(age),
       trailing: const icon(
         icons.arrow_forward_ios,
       ),
       onTap: () {
         // when a [listtile] that represents a person is
         // tapped, push the detailsPageRouteName route
         // to the navigator and pass the person's instance
         // to the route.
         Navigator.of(context).pushNamed(
           detailsPageRouteName,
           arguments: person,
         );
       },
     );
   },
 ),
<code_end>
define the DetailsPage widget that displays the details of
each person. in flutter, you can pass arguments into the
widget when navigating to the new route.
extract the arguments using ModalRoute.of():
<code_start>
class DetailsPage extends StatelessWidget {
   const DetailsPage({super.key});
   @override
   widget build(BuildContext context) {
     // read the person instance from the arguments.
     final person person = ModalRoute.of(
       context,
     )?.settings.arguments as person;
     // extract the age.
     final age = '${person.age} years old';
     return scaffold(
       // display name and age.
       body: column(children: [text(person.name), text(age)]),
     );
   }
 }
<code_end>
to create more advanced navigation and routing requirements,
use a routing package such as go_router.
to learn more, check out navigation and routing.
<topic_end>
<topic_start>
manually pop back
in SwiftUI, you use the dismiss environment value to pop-back to
the previous screen.
in flutter, use the pop() function of the navigator class:
<code_start>
TextButton(
  onPressed: () {
    // this code allows the
    // view to pop back to its presenter.
    navigator.of(context).pop();
  },
  child: const Text('Pop back'),
),
<code_end>
<topic_end>
<topic_start>
navigating to another app
in SwiftUI, you use the openURL environment variable to open a
URL to another application.
in flutter, use the url_launcher plugin.
<code_start>
    CupertinoButton(
  onPressed: () async {
    await launchUrl(
      uri.parse('https://google.com'),
    );
  },
  child: const text(
    'open website',
  ),
),
<code_end>
<topic_end>
<topic_start>
themes, styles, and media
you can style flutter apps with little effort.
styling includes switching between light and dark themes,
changing the design of your text and UI components,
and more. this section covers how to style your apps.
<topic_end>
<topic_start>
using dark mode
in SwiftUI, you call the preferredColorScheme()
function on a view to use dark mode.
in flutter, you can control light and dark mode at the app-level.
to control the brightness mode, use the theme property
of the app class:
<code_start>
    CupertinoApp(
  theme: CupertinoThemeData(
    brightness: brightness.dark,
  ),
  home: HomePage(),
);
<code_end>
<topic_end>
<topic_start>
styling text
in SwiftUI, you use modifier functions to style text.
for example, to change the font of a text string,
use the font() modifier:
to style text in flutter, add a TextStyle widget as the value
of the style parameter of the text widget.
<code_start>
    text(
  'hello, world!',
  style: TextStyle(
    fontSize: 30,
    fontWeight: FontWeight.bold,
    color: CupertinoColors.systemYellow,
  ),
),
<code_end>
<topic_end>
<topic_start>
styling buttons
in SwiftUI, you use modifier functions to style buttons.
to style button widgets in flutter, set the style of its child,
or modify properties on the button itself.
in the following example:
<code_start>
child: CupertinoButton(
  color: CupertinoColors.systemYellow,
  onPressed: () {},
  padding: const EdgeInsets.all(16),
  child: const text(
    'do something',
    style: TextStyle(
      color: CupertinoColors.systemBlue,
      fontSize: 30,
      fontWeight: FontWeight.bold,
    ),
  ),
),
<code_end>
<topic_end>
<topic_start>
using custom fonts
in SwiftUI, you can use a custom font in your app in two steps.
first, add the font file to your SwiftUI project. after adding the file,
use the .font() modifier to apply it to your UI components.
in flutter, you control your resources with a file
named pubspec.yaml. this file is platform agnostic.
to add a custom font to your project, follow these steps:
add your custom font(s) under the fonts section.
after you add the font to your project, you can use it as in the
following example:
<code_start>
        text(
  'cupertino',
  style: TextStyle(
    fontSize: 40,
    fontFamily: 'bungeespice',
  ),
)
<code_end>
info note
  to download custom fonts to use in your apps,
  check out google fonts.
<topic_end>
<topic_start>
bundling images in apps
in SwiftUI, you first add the image files to assets.xcassets,
then use the image view to display the images.
to add images in flutter, follow a method similar to how you added
custom fonts.
add this asset to the pubspec.yaml file.
after adding your image, display it using the image widget’s
.asset() constructor. this constructor:
to review a complete example, check out the image docs.
<topic_end>
<topic_start>
bundling videos in apps
in SwiftUI, you bundle a local video file with your app in two
steps.
first, you import the AVKit framework, then you instantiate a
VideoPlayer view.
in flutter, add the video_player plugin to your project.
this plugin allows you to create a video player that works on
android, iOS, and on the web from the same codebase.
to review a complete walkthrough, check out the video_player example.
<topic_end>
<topic_start>
flutter for UIKit developers
iOS developers with experience using UIKit
who want to write mobile apps using flutter
should review this guide.
it explains how to apply existing UIKit knowledge to flutter.
info note
  if you have experience building apps with SwiftUI,
  check out flutter for SwiftUI developers instead.
flutter is a framework for building cross-platform applications
that uses the dart programming language.
to understand some differences between programming with dart
and programming with swift, see learning dart as a swift developer
and flutter concurrency for swift developers.
your iOS and UIKit knowledge and experience
are highly valuable when building with flutter.
flutter also makes a number of adaptations
to app behavior when running on iOS.
to learn how, see platform adaptations.
info
  to integrate flutter code into an existing iOS app,
  check out add flutter to existing app.
use this guide as a cookbook.
jump around and find questions that address your most relevant needs.
<topic_end>
<topic_start>
overview
as an introduction, watch the following video.
it outlines how flutter works on iOS and how to use flutter to build iOS apps.
<topic_end>
<topic_start>
views vs. widgets
how is react-style, or declarative,
  programming different from the
  traditional imperative style?
  for a comparison, see introduction to declarative UI.
in UIKit, most of what you create in the UI is done using view objects,
which are instances of the UIView class.
these can act as containers for other UIView classes,
which form your layout.
in flutter, the rough equivalent to a UIView is a widget.
widgets don’t map exactly to iOS views,
but while you’re getting acquainted with how flutter works
you can think of them as “the way you declare and construct UI”.
however, these have a few differences to a UIView.
to start, widgets have a different lifespan: they are immutable
and only exist until they need to be changed.
whenever widgets or their state change,
flutter’s framework creates a new tree of widget instances.
in comparison, a UIKit view is not recreated when it changes,
but rather it’s a mutable entity that is drawn once
and doesn’t redraw until it is invalidated using setNeedsDisplay().
furthermore, unlike UIView, flutter’s widgets are lightweight,
in part due to their immutability.
because they aren’t views themselves,
and aren’t directly drawing anything,
but rather are a description of the UI and its semantics
that get “inflated” into actual view objects under the hood.
flutter includes the material components library.
these are widgets that implement the
material design guidelines.
material design is a flexible design system
optimized for all platforms, including iOS.
but flutter is flexible and expressive enough
to implement any design language.
on iOS, you can use the cupertino widgets
to produce an interface that looks like
apple’s iOS design language.
<topic_end>
<topic_start>
updating widgets
to update your views in UIKit, you directly mutate them.
in flutter, widgets are immutable and not updated directly.
instead, you have to manipulate the widget’s state.
this is where the concept of stateful vs stateless widgets
comes in. a StatelessWidget is just what it sounds
like—a widget with no state attached.
StatelessWidgets are useful when the part of the user interface you are
describing does not depend on anything other than the initial configuration
information in the widget.
for example, with UIKit, this is similar to placing a UIImageView
with your logo as the image. if the logo is not changing during runtime,
use a StatelessWidget in flutter.
if you want to dynamically change the UI based on data received
after making an HTTP call, use a StatefulWidget.
after the HTTP call has completed, tell the flutter framework
that the widget’s state is updated, so it can update the UI.
the important difference between stateless and
stateful widgets is that StatefulWidgets have a state object
that stores state data and carries it over across tree rebuilds,
so it’s not lost.
if you are in doubt, remember this rule:
if a widget changes outside of the build method
(because of runtime user interactions, for example),
it’s stateful.
if the widget never changes, once built, it’s stateless.
however, even if a widget is stateful, the containing parent widget
can still be stateless if it isn’t itself reacting to those changes
(or other inputs).
the following example shows how to use a StatelessWidget.
a commonStatelessWidget is the text widget.
if you look at the implementation of the text widget,
you’ll find it subclasses StatelessWidget.
<code_start>
text(
  'i like flutter!',
  style: TextStyle(fontWeight: FontWeight.bold),
);
<code_end>
if you look at the code above, you might notice that the text widget
carries no explicit state with it. it renders what is passed in its
constructors and nothing more.
but, what if you want to make “i like flutter” change dynamically,
for example when clicking a FloatingActionButton?
to achieve this, wrap the text widget in a StatefulWidget and
update it when the user clicks the button.
for example:
<code_start>
class SampleApp extends StatelessWidget {
  // this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  // default placeholder text
  string textToShow = 'i like flutter';
  void _updateText() {
    setState(() {
      // update the text
      textToShow = 'flutter is awesome!';
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: center(child: Text(textToShow)),
      floatingActionButton: FloatingActionButton(
        onPressed: _updateText,
        tooltip: 'update text',
        child: const Icon(Icons.update),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
widget layout
in UIKit, you might use a storyboard file
to organize your views and set constraints,
or you might set your constraints programmatically in your view controllers.
in flutter, declare your layout in code by composing a widget tree.
the following example shows how to display a simple widget with padding:
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(title: const Text('Sample app')),
    body: center(
      child: CupertinoButton(
        onPressed: () {},
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: const Text('Hello'),
      ),
    ),
  );
}
<code_end>
you can add padding to any widget,
which mimics the functionality of constraints in iOS.
you can view the layouts that flutter has to offer
in the widget catalog.
<topic_end>
<topic_start>
removing widgets
in UIKit, you call addSubview() on the parent,
or removeFromSuperview() on a child view
to dynamically add or remove child views.
in flutter, because widgets are immutable,
there is no direct equivalent to addSubview().
instead, you can pass a function to the parent
that returns a widget, and control that child’s creation
with a boolean flag.
the following example shows how to toggle between two widgets
when the user clicks the FloatingActionButton:
<code_start>
class SampleApp extends StatelessWidget {
  // this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  // default value for toggle.
  bool toggle = true;
  void _toggle() {
    setState(() {
      toggle = !toggle;
    });
  }
  widget _getToggleChild() {
    if (toggle) {
      return const Text('Toggle one');
    }
    return CupertinoButton(
      onPressed: () {},
      child: const Text('Toggle two'),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: center(
        child: _getToggleChild(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _toggle,
        tooltip: 'update text',
        child: const Icon(Icons.update),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
animations
in UIKit, you create an animation by calling the
animate(withDuration:animations:) method on a view.
in flutter, use the animation library
to wrap widgets inside an animated widget.
in flutter, use an AnimationController, which is an animation<double>
that can pause, seek, stop, and reverse the animation.
it requires a ticker that signals when vsync happens
and produces a linear interpolation
between 0 and 1 on each frame while it’s running.
you then create one or more
animations and attach them to the controller.
for example, you might use CurvedAnimation
to implement an animation along an interpolated curve.
in this sense, the controller is the “master” source
of the animation progress
and the CurvedAnimation computes the curve
that replaces the controller’s default linear motion.
like widgets, animations in flutter work with composition.
when building the widget tree you assign the animation to an animated
property of a widget, such as the opacity of a FadeTransition,
and tell the controller to start the animation.
the following example shows how to write a FadeTransition that
fades the widget into a logo when you press the FloatingActionButton:
<code_start>
import 'package:flutter/material.dart';
class SampleApp extends StatelessWidget {
  // this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'fade demo',
      home: MyFadeTest(title: 'fade demo'),
    );
  }
}
class MyFadeTest extends StatefulWidget {
  const MyFadeTest({super.key, required this.title});
  final string title;
  @override
  State<MyFadeTest> createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late CurvedAnimation curve;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const duration(milliseconds: 2000),
      vsync: this,
    );
    curve = CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn,
    );
  }
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: text(widget.title)),
      body: center(
        child: FadeTransition(
          opacity: curve,
          child: const FlutterLogo(size: 100),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          controller.forward();
        },
        tooltip: 'fade',
        child: const Icon(Icons.brush),
      ),
    );
  }
}
<code_end>
for more information, see animation & motion widgets,
the animations tutorial, and the animations overview.
<topic_end>
<topic_start>
drawing on the screen
in UIKit, you use CoreGraphics to draw lines and shapes to the
screen. flutter has a different API based on the canvas class,
with two other classes that help you draw: CustomPaint and CustomPainter,
the latter of which implements your algorithm to draw to the canvas.
to learn how to implement a signature painter in flutter,
see collin’s answer on StackOverflow.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: DemoApp()));
class DemoApp extends StatelessWidget {
  const DemoApp({super.key});
  @override
  widget build(BuildContext context) => const scaffold(body: signature());
}
class signature extends StatefulWidget {
  const signature({super.key});
  @override
  State<Signature> createState() => SignatureState();
}
class SignatureState extends State<Signature> {
  List<Offset?> _points = <offset?>[];
  @override
  widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (details) {
        setState(() {
          RenderBox? referenceBox = context.findRenderObject() as RenderBox;
          offset localPosition =
              referenceBox.globalToLocal(details.globalPosition);
          _points = List.from(_points)..add(localPosition);
        });
      },
      onPanEnd: (details) => _points.add(null),
      child:
          CustomPaint(
        painter: SignaturePainter(_points),
        size: size.infinite,
      ),
    );
  }
}
class SignaturePainter extends CustomPainter {
  SignaturePainter(this.points);
  final List<Offset?> points;
  @override
  void paint(Canvas canvas, size size) {
    final paint paint = paint()
      ..color = colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i]!, points[i + 1]!, paint);
      }
    }
  }
  @override
  bool shouldRepaint(SignaturePainter oldDelegate) =>
      oldDelegate.points != points;
}
<code_end>
<topic_end>
<topic_start>
widget opacity
in UIKit, everything has .opacity or .alpha.
in flutter, most of the time you need to
wrap a widget in an opacity widget to accomplish this.
<topic_end>
<topic_start>
custom widgets
in UIKit, you typically subclass UIView, or use a pre-existing view,
to override and implement methods that achieve the desired behavior.
in flutter, build a custom widget by composing smaller widgets
(instead of extending them).
for example, how do you build a CustomButton
that takes a label in the constructor?
create a CustomButton that composes a ElevatedButton with a label,
rather than by extending ElevatedButton:
<code_start>
class CustomButton extends StatelessWidget {
  const CustomButton(this.label, {super.key});
  final string label;
  @override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: text(label),
    );
  }
}
<code_end>
then use CustomButton,
just as you’d use any other flutter widget:
<code_start>
@override
widget build(BuildContext context) {
  return const center(
    child: CustomButton('Hello'),
  );
}
<code_end>
<topic_end>
<topic_start>
navigation
this section of the document discusses navigation
between pages of an app, the push and pop mechanism, and more.
<topic_end>
<topic_start>
navigating between pages
in UIKit, to travel between view controllers, you can use a
UINavigationController that manages the stack of view controllers
to display.
flutter has a similar implementation,
using a navigator and routes.
a route is an abstraction for a “screen” or “page” of an app,
and a navigator is a widget
that manages routes. a route roughly maps to a
UIViewController. the navigator works in a similar way to the iOS
UINavigationController, in that it can push() and pop()
routes depending on whether you want to navigate to, or back from, a view.
to navigate between pages, you have a couple options:
the following example builds a map.
<code_start>
void main() {
  runApp(
    CupertinoApp(
      home: const MyAppHome(), // becomes the route named '/'
      routes: <string, WidgetBuilder>{
        '/a': (context) => const MyPage(title: 'page a'),
        '/b': (context) => const MyPage(title: 'page b'),
        '/c': (context) => const MyPage(title: 'page c'),
      },
    ),
  );
}
<code_end>
navigate to a route by pushing its name to the navigator.
<code_start>
Navigator.of(context).pushNamed('/b');
<code_end>
the navigator class handles routing in flutter and is used to get
a result back from a route that you have pushed on the stack.
this is done by awaiting on the future returned by push().
for example, to start a location route that lets the user select their
location, you might do the following:
<code_start>
object? coordinates = await Navigator.of(context).pushNamed('/location');
<code_end>
and then, inside your location route, once the user has selected their
location, pop() the stack with the result:
<code_start>
navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392});
<code_end>
<topic_end>
<topic_start>
navigating to another app
in UIKit, to send the user to another application,
you use a specific URL scheme.
for the system level apps, the scheme depends on the app.
to implement this functionality in flutter,
create a native platform integration, or use an
existing plugin, such as url_launcher.
<topic_end>
<topic_start>
manually pop back
calling SystemNavigator.pop() from your dart code
invokes the following iOS code:
if that doesn’t do what you want, you can create your own
platform channel to invoke arbitrary iOS code.
<topic_end>
<topic_start>
handling localization
unlike iOS, which has the localizable.strings file,
flutter doesn’t currently have a dedicated system for handling strings.
at the moment, the best practice is to declare your copy text
in a class as static fields and access them from there. for example:
<code_start>
class strings {
  static const string welcomeMessage = 'welcome to flutter';
}
<code_end>
you can access your strings as such:
<code_start>
Text(Strings.welcomeMessage);
<code_end>
by default, flutter only supports US english for its strings.
if you need to add support for other languages,
include the flutter_localizations package.
you might also need to add dart’s intl
package to use i10n machinery, such as date/time formatting.
to use the flutter_localizations package,
specify the localizationsDelegates and
supportedLocales on the app widget:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      localizationsDelegates: <localizationsdelegate<dynamic>>[
        // add app-specific localization delegate[s] here
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: <locale>[
        locale('en', 'us'), // english
        locale('he', 'il'), // hebrew
        // ... other locales the app supports
      ],
    );
  }
}
<code_end>
the delegates contain the actual localized values,
while the supportedLocales defines which locales the app supports.
the above example uses a MaterialApp,
so it has both a GlobalWidgetsLocalizations
for the base widgets localized values,
and a MaterialWidgetsLocalizations for the material widgets localizations.
if you use WidgetsApp for your app, you don’t need the latter.
note that these two delegates contain “default” values,
but you’ll need to provide one or more delegates
for your own app’s localizable copy,
if you want those to be localized too.
when initialized, the WidgetsApp (or MaterialApp)
creates a localizations widget for you,
with the delegates you specify.
the current locale for the device is always accessible
from the localizations widget from the current context
(in the form of a locale object), or using the window.locale.
to access localized resources, use the localizations.of() method
to access a specific localizations class that is provided by a given delegate.
use the intl_translation package to extract translatable copy
to arb files for translating, and importing them back into the app
for using them with intl.
for further details on internationalization and localization in flutter,
see the internationalization guide, which has sample code
with and without the intl package.
<topic_end>
<topic_start>
managing dependencies
in iOS, you add dependencies with CocoaPods by adding to your podfile.
flutter uses dart’s build system and the pub package manager
to handle dependencies. the tools delegate the building of the
native android and iOS wrapper apps to the
respective build systems.
while there is a podfile in the iOS folder in your
flutter project, only use this if you are adding native
dependencies needed for per-platform integration.
in general, use pubspec.yaml to declare external dependencies in flutter.
a good place to find great packages for flutter is on pub.dev.
<topic_end>
<topic_start>
ViewControllers
this section of the document discusses the equivalent
of ViewController in flutter and how to listen to
lifecycle events.
<topic_end>
<topic_start>
equivalent of ViewController in flutter
in UIKit, a ViewController represents a portion of user interface,
most commonly used for a screen or section.
these are composed together to build complex user interfaces,
and help scale your application’s UI.
in flutter, this job falls to widgets.
as mentioned in the navigation section,
screens in flutter are represented by widgets since
“everything is a widget!”
use a navigator to move between different routes
that represent different screens or pages,
or maybe different states or renderings of the same data.
<topic_end>
<topic_start>
listening to lifecycle events
in UIKit, you can override methods to the ViewController
to capture lifecycle methods for the view itself,
or register lifecycle callbacks in the AppDelegate.
in flutter, you have neither concept, but you can instead
listen to lifecycle events by hooking into
the WidgetsBinding observer and listening to
the didChangeAppLifecycleState() change event.
the observable lifecycle events are:
for more details on the meaning of these states, see
AppLifecycleState documentation.
<topic_end>
<topic_start>
layouts
this section discusses different layouts in flutter
and how they compare with UIKit.
<topic_end>
<topic_start>
displaying a list view
in UIKit, you might show a list in
either a UITableView or a UICollectionView.
in flutter, you have a similar implementation using a ListView.
in UIKit, these views have delegate methods
for deciding the number of rows,
the cell for each index path, and the size of the cells.
due to flutter’s immutable widget pattern,
you pass a list of widgets to your ListView,
and flutter takes care of making sure that
scrolling is fast and smooth.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> _getListData() {
    final List<Widget> widgets = [];
    for (int i = 0; i < 100; i++) {
      widgets.add(Padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $i'),
      ));
    }
    return widgets;
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView(children: _getListData()),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
detecting what was clicked
in UIKit, you implement the delegate method,
tableView:didSelectRowAtIndexPath:.
in flutter, use the touch handling provided by the passed-in widgets.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> _getListData() {
    List<Widget> widgets = [];
    for (int i = 0; i < 100; i++) {
      widgets.add(
        GestureDetector(
          onTap: () {
            developer.log('row tapped');
          },
          child: padding(
            padding: const EdgeInsets.all(10),
            child: Text('Row $i'),
          ),
        ),
      );
    }
    return widgets;
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView(children: _getListData()),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
dynamically updating ListView
in UIKit, you update the data for the list view,
and notify the table or collection view using the
reloadData method.
in flutter, if you update the list of widgets inside a setState(),
you quickly see that your data doesn’t change visually.
this is because when setState() is called,
the flutter rendering engine looks at the widget tree
to see if anything has changed.
when it gets to your ListView, it performs an == check,
and determines that the two ListViews are the same.
nothing has changed, so no update is required.
for a simple way to update your ListView,
create a new list inside of setState(),
and copy the data from the old list to the new list.
while this approach is simple,
it is not recommended for large data sets,
as shown in the next example.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> widgets = <widget>[];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 100; i++) {
      widgets.add(getRow(i));
    }
  }
  widget getRow(int i) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widgets = list.from(widgets);
          widgets.add(getRow(widgets.length));
          developer.log('row $i');
        });
      },
      child: padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $i'),
      ),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView(children: widgets),
    );
  }
}
<code_end>
the recommended, efficient,
and effective way to build a list uses a ListView.Builder.
this method is great when you have a dynamic
list or a list with very large amounts of data.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> widgets = [];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 100; i++) {
      widgets.add(getRow(i));
    }
  }
  widget getRow(int i) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widgets.add(getRow(widgets.length));
          developer.log('row $i');
        });
      },
      child: padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $i'),
      ),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView.builder(
        itemCount: widgets.length,
        itemBuilder: (context, position) {
          return getRow(position);
        },
      ),
    );
  }
}
<code_end>
instead of creating a ListView, create a ListView.builder
that takes two key parameters: the initial length of the list,
and an ItemBuilder function.
the ItemBuilder function is similar to the cellForItemAt
delegate method in an iOS table or collection view,
as it takes a position, and returns the
cell you want rendered at that position.
finally, but most importantly, notice that the onTap() function
doesn’t recreate the list anymore, but instead .adds to it.
<topic_end>
<topic_start>
creating a scroll view
in UIKit, you wrap your views in a ScrollView that
allows a user to scroll your content if needed.
in flutter the easiest way to do this is using the ListView widget.
this acts as both a ScrollView and an iOS TableView,
as you can lay out widgets in a vertical format.
<code_start>
@override
widget build(BuildContext context) {
  return ListView(
    children: const <widget>[
      Text('Row one'),
      Text('Row two'),
      Text('Row three'),
      Text('Row four'),
    ],
  );
}
<code_end>
for more detailed docs on how to lay out widgets in flutter,
see the layout tutorial.
<topic_end>
<topic_start>
gesture detection and touch event handling
this section discusses how to detect gestures
and handle different events in flutter,
and how they compare with UIKit.
<topic_end>
<topic_start>
adding a click listener
in UIKit, you attach a GestureRecognizer to a view to
handle click events.
in flutter, there are two ways of adding touch listeners:
if the widget supports event detection, pass a function to it,
and handle the event in the function. for example, the
ElevatedButton widget has an onPressed parameter:
<code_start>
@override
widget build(BuildContext context) {
  return ElevatedButton(
    onPressed: () {
      developer.log('click');
    },
    child: const Text('Button'),
  );
}
<code_end>
if the widget doesn’t support event detection,
wrap the widget in a GestureDetector and pass a function
to the onTap parameter.
<code_start>
class SampleTapApp extends StatelessWidget {
  const SampleTapApp({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: GestureDetector(
          onTap: () {
            developer.log('tap');
          },
          child: const FlutterLogo(
            size: 200,
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
handling other gestures
using GestureDetector you can listen
to a wide range of gestures such as:
tapping
double tapping
long pressing
vertical dragging
horizontal dragging
the following example shows a GestureDetector
that rotates the flutter logo on a double tap:
<code_start>
class SampleApp extends StatefulWidget {
  const SampleApp({super.key});
  @override
  State<SampleApp> createState() => _SampleAppState();
}
class _SampleAppState extends State<SampleApp>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late CurvedAnimation curve;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      vsync: this,
      duration: const duration(milliseconds: 2000),
    );
    curve = CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn,
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: GestureDetector(
          onDoubleTap: () {
            if (controller.iscompleted) {
              controller.reverse();
            } else {
              controller.forward();
            }
          },
          child: RotationTransition(
            turns: curve,
            child: const FlutterLogo(
              size: 200,
            ),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
themes, styles, and media
flutter applications are easy to style; you can switch
between light and dark themes,
change the style of your text and UI components,
and more. this section covers aspects of styling your flutter apps
and compares how you might do the same in UIKit.
<topic_end>
<topic_start>
using a theme
out of the box, flutter comes with a beautiful implementation
of material design, which takes care of a lot of styling and
theming needs that you would typically do.
to take full advantage of material components in your app,
declare a top-level widget, MaterialApp,
as the entry point to your application.
MaterialApp is a convenience widget that wraps a number
of widgets that are commonly required for applications
implementing material design.
it builds upon a WidgetsApp by adding material specific functionality.
but flutter is flexible and expressive enough to implement
any design language. on iOS, you can use the
cupertino library to produce an interface that adheres to the
human interface guidelines.
for the full set of these widgets,
see the cupertino widgets gallery.
you can also use a WidgetsApp as your app widget,
which provides some of the same functionality,
but is not as rich as MaterialApp.
to customize the colors and styles of any child components,
pass a ThemeData object to the MaterialApp widget.
for example, in the code below,
the color scheme from seed is set to deepPurple and divider color is grey.
<code_start>
import 'package:flutter/material.dart';
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        dividerColor: colors.grey,
      ),
      home: const SampleAppPage(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
using custom fonts
in UIKit, you import any ttf font files into your project
and create a reference in the info.plist file.
in flutter, place the font file in a folder
and reference it in the pubspec.yaml file,
similar to how you import images.
then assign the font to your text widget:
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(
      title: const Text('Sample app'),
    ),
    body: const center(
      child: text(
        'this is a custom font text',
        style: TextStyle(fontFamily: 'mycustomfont'),
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
styling text
along with fonts, you can customize other styling elements on a text widget.
the style parameter of a text widget takes a TextStyle object,
where you can customize many parameters, such as:
<topic_end>
<topic_start>
bundling images in apps
while iOS treats images and assets as distinct items,
flutter apps have only assets. resources that are
placed in the images.xcasset folder on iOS,
are placed in an assets’ folder for flutter.
as with iOS, assets are any type of file, not just images.
for example, you might have a JSON file located in the my-assets folder:
declare the asset in the pubspec.yaml file:
and then access it from code using an AssetBundle:
<code_start>
import 'dart:async' show future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
  return await rootBundle.loadString('my-assets/data.json');
}
<code_end>
for images, flutter follows a simple density-based format like iOS.
image assets might be 1.0x, 2.0x, 3.0x, or any other multiplier.
flutter’s devicePixelRatio expresses the ratio
of physical pixels in a single logical pixel.
assets are located in any arbitrary folder—
flutter has no predefined folder structure.
you declare the assets (with location) in
the pubspec.yaml file, and flutter picks them up.
for example, to add an image called my_icon.png to your flutter
project, you might decide to store it in a folder arbitrarily called images.
place the base image (1.0x) in the images folder, and the
other variants in sub-folders named after the appropriate ratio multiplier:
next, declare these images in the pubspec.yaml file:
you can now access your images using AssetImage:
<code_start>
AssetImage('images/a_dot_burr.jpeg')
<code_end>
or directly in an image widget:
<code_start>
@override
widget build(BuildContext context) {
  return image.asset('images/my_image.png');
}
<code_end>
for more details, see
adding assets and images in flutter.
<topic_end>
<topic_start>
form input
this section discusses how to use forms in flutter
and how they compare with UIKit.
<topic_end>
<topic_start>
retrieving user input
given how flutter uses immutable widgets with a separate state,
you might be wondering how user input fits into the picture.
in UIKit, you usually query the widgets for their current values
when it’s time to submit the user input, or action on it.
how does that work in flutter?
in practice forms are handled, like everything in flutter,
by specialized widgets. if you have a TextField or a
TextFormField, you can supply a TextEditingController
to retrieve user input:
<code_start>
class _MyFormState extends State<MyForm> {
  // create a text controller and use it to retrieve the current value.
  // of the TextField!
  final myController = TextEditingController();
  @override
  void dispose() {
    // clean up the controller when disposing of the widget.
    myController.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Retrieve text input')),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: TextField(controller: myController),
      ),
      floatingActionButton: FloatingActionButton(
        // when the user presses the button, show an alert dialog with the
        // text the user has typed into our text field.
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // retrieve the text the user has typed in using our
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'show me the value!',
        child: const Icon(Icons.text_fields),
      ),
    );
  }
}
<code_end>
you can find more information and the full code listing in
retrieve the value of a text field,
from the flutter cookbook.
<topic_end>
<topic_start>
placeholder in a text field
in flutter, you can easily show a “hint” or a placeholder text
for your field by adding an InputDecoration object
to the decoration constructor parameter for the text widget:
<code_start>
center(
  child: TextField(
    decoration: InputDecoration(hintText: 'this is a hint'),
  ),
)
<code_end>
<topic_end>
<topic_start>
showing validation errors
just as you would with a “hint”, pass an InputDecoration object
to the decoration constructor for the text widget.
however, you don’t want to start off by showing an error.
instead, when the user has entered invalid data,
update the state, and pass a new InputDecoration object.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  // this widget is the root of your application.
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  string? _errorText;
  bool isEmail(String em) {
    string emailRegexp =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|'
        r'(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|'
        r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regExp = RegExp(emailRegexp);
    return regExp.hasMatch(em);
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: center(
        child: TextField(
          onSubmitted: (text) {
            setState(() {
              if (!isemail(text)) {
                _errorText = 'error: this is not an email';
              } else {
                _errorText = null;
              }
            });
          },
          decoration: InputDecoration(
            hintText: 'this is a hint',
            errorText: _errorText,
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
threading & asynchronicity
this section discusses concurrency in flutter and
how it compares with UIKit.
<topic_end>
<topic_start>
writing asynchronous code
dart has a single-threaded execution model,
with support for isolates
(a way to run dart code on another thread),
an event loop, and asynchronous programming.
unless you spawn an isolate,
your dart code runs in the main UI thread and is
driven by an event loop. flutter’s event loop is
equivalent to the iOS main loop—that is,
the looper that is attached to the main thread.
dart’s single-threaded model doesn’t mean you are
required to run everything as a blocking operation
that causes the UI to freeze. instead,
use the asynchronous facilities that the dart language provides,
such as async/await, to perform asynchronous work.
for example, you can run network code without causing the
UI to hang by using async/await and letting dart do
the heavy lifting:
<code_start>
future<void> loadData() async {
  final uri dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
  final http.Response response = await http.get(dataURL);
  setState(() {
    data = jsonDecode(response.body);
  });
}
<code_end>
once the awaited network call is done,
update the UI by calling setState(),
which triggers a rebuild of the widget subtree
and updates the data.
the following example loads data asynchronously and
displays it in a ListView:
<code_start>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Map<String, dynamic>> data = <map<string, dynamic>>[];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  future<void> loadData() async {
    final uri dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
    final http.Response response = await http.get(dataURL);
    setState(() {
      data = jsonDecode(response.body);
    });
  }
  widget getRow(int index) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text('Row ${data[index]['title']}'),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return getRow(index);
        },
      ),
    );
  }
}
<code_end>
refer to the next section for more information on doing work
in the background, and how flutter differs from iOS.
<topic_end>
<topic_start>
moving to the background thread
since flutter is single threaded and runs an event loop
(like node.js), you don’t have to worry about
thread management or spawning background threads.
if you’re doing I/O-bound work,
such as disk access or a network call,
then you can safely use async/await and you’re done.
if, on the other hand, you need to do computationally intensive
work that keeps the CPU busy, you want to move it to an
isolate to avoid blocking the event loop.
for I/O-bound work, declare the function as an async function,
and await on long-running tasks inside the function:
<code_start>
future<void> loadData() async {
  final uri dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
  final http.Response response = await http.get(dataURL);
  setState(() {
    data = jsonDecode(response.body);
  });
}
<code_end>
this is how you typically do network or database calls,
which are both I/O operations.
however, there are times when you might be processing
a large amount of data and your UI hangs.
in flutter, use isolates to take advantage of
multiple CPU cores to do long-running or
computationally intensive tasks.
isolates are separate execution threads that do not share
any memory with the main execution memory heap.
this means you can’t access variables from the main thread,
or update your UI by calling setState().
isolates are true to their name, and cannot share memory
(in the form of static fields, for example).
the following example shows, in a simple isolate,
how to share data back to the main thread to update the UI.
<code_start>
future<void> loadData() async {
  final ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(dataLoader, receivePort.sendPort);
  // the 'echo' isolate sends its SendPort as the first message.
  final SendPort sendPort = await receivePort.first as SendPort;
  final List<Map<String, dynamic>> msg = await sendReceive(
    sendPort,
    'https://jsonplaceholder.typicode.com/posts',
  );
  setState(() {
    data = msg;
  });
}
// the entry point for the isolate.
static future<void> dataLoader(SendPort sendPort) async {
  // open the ReceivePort for incoming messages.
  final ReceivePort port = ReceivePort();
  // notify any other isolates what port this isolate listens to.
  sendPort.send(port.sendPort);
  await for (final dynamic msg in port) {
    final string url = msg[0] as string;
    final SendPort replyTo = msg[1] as SendPort;
    final uri dataURL = uri.parse(url);
    final http.Response response = await http.get(dataURL);
    // lots of JSON to parse
    replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>);
  }
}
Future<List<Map<String, dynamic>>> sendReceive(SendPort port, string msg) {
  final ReceivePort response = ReceivePort();
  port.send(<dynamic>[msg, response.sendPort]);
  return response.first as Future<List<Map<String, dynamic>>>;
}
<code_end>
here, dataLoader() is the isolate that runs in
its own separate execution thread.
in the isolate, you can perform more CPU intensive
processing (parsing a big JSON, for example),
or perform computationally intensive math,
such as encryption or signal processing.
you can run the full example below:
<code_start>
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Map<String, dynamic>> data = <map<string, dynamic>>[];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  bool get showLoadingDialog => data.isEmpty;
  future<void> loadData() async {
    final ReceivePort receivePort = ReceivePort();
    await Isolate.spawn(dataLoader, receivePort.sendPort);
    // the 'echo' isolate sends its SendPort as the first message.
    final SendPort sendPort = await receivePort.first as SendPort;
    final List<Map<String, dynamic>> msg = await sendReceive(
      sendPort,
      'https://jsonplaceholder.typicode.com/posts',
    );
    setState(() {
      data = msg;
    });
  }
  // the entry point for the isolate.
  static future<void> dataLoader(SendPort sendPort) async {
    // open the ReceivePort for incoming messages.
    final ReceivePort port = ReceivePort();
    // notify any other isolates what port this isolate listens to.
    sendPort.send(port.sendPort);
    await for (final dynamic msg in port) {
      final string url = msg[0] as string;
      final SendPort replyTo = msg[1] as SendPort;
      final uri dataURL = uri.parse(url);
      final http.Response response = await http.get(dataURL);
      // lots of JSON to parse
      replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>);
    }
  }
  Future<List<Map<String, dynamic>>> sendReceive(SendPort port, string msg) {
    final ReceivePort response = ReceivePort();
    port.send(<dynamic>[msg, response.sendPort]);
    return response.first as Future<List<Map<String, dynamic>>>;
  }
  widget getBody() {
    bool showLoadingDialog = data.isEmpty;
    if (showloadingdialog) {
      return getProgressDialog();
    } else {
      return getListView();
    }
  }
  widget getProgressDialog() {
    return const center(child: CircularProgressIndicator());
  }
  ListView getListView() {
    return ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, position) {
        return getRow(position);
      },
    );
  }
  widget getRow(int i) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text("Row ${data[i]["title"]}"),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: getBody(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
making network requests
making a network call in flutter is easy when you
use the popular http package. this abstracts
away a lot of the networking that you might normally
implement yourself, making it simple to make network calls.
to add the http package as a dependency, run flutter pub add:
to make a network call,
call await on the async function http.get():
<code_start>
future<void> loadData() async {
  final uri dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
  final http.Response response = await http.get(dataURL);
  setState(() {
    data = jsonDecode(response.body);
  });
}
<code_end>
<topic_end>
<topic_start>
showing the progress on long-running tasks
in UIKit, you typically use a UIProgressView
while executing a long-running task in the background.
in flutter, use a ProgressIndicator widget.
show the progress programmatically by controlling
when it’s rendered through a boolean flag.
tell flutter to update its state before your long-running task starts,
and hide it after it ends.
in the example below, the build function is separated into three different
functions. if showLoadingDialog is true
(when widgets.length == 0), then render the ProgressIndicator.
otherwise, render the ListView with the data returned from a network call.
<code_start>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Map<String, dynamic>> data = <map<string, dynamic>>[];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  bool get showLoadingDialog => data.isEmpty;
  future<void> loadData() async {
    final uri dataURL = uri.parse('https://jsonplaceholder.typicode.com/posts');
    final http.Response response = await http.get(dataURL);
    setState(() {
      data = jsonDecode(response.body);
    });
  }
  widget getBody() {
    if (showloadingdialog) {
      return getProgressDialog();
    }
    return getListView();
  }
  widget getProgressDialog() {
    return const center(child: CircularProgressIndicator());
  }
  ListView getListView() {
    return ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index) {
        return getRow(index);
      },
    );
  }
  widget getRow(int i) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text("Row ${data[i]["title"]}"),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Sample app'),
      ),
      body: getBody(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
flutter for react native developers
this document is for react native (rn) developers looking to apply their
existing RN knowledge to build mobile apps with flutter. if you understand
the fundamentals of the RN framework then you can use this document as a
way to get started learning flutter development.
this document can be used as a cookbook by jumping around and finding
questions that are most relevant to your needs.
<topic_end>
<topic_start>
introduction to dart for JavaScript developers (es6)
like react native, flutter uses reactive-style views. however, while RN
transpiles to native widgets, flutter compiles all the way to native code.
flutter controls each pixel on the screen, which avoids performance problems
caused by the need for a JavaScript bridge.
dart is an easy language to learn and offers the following features:
a few examples of the differences between JavaScript and dart are described
below.
<topic_end>
<topic_start>
entry point
JavaScript doesn’t have a pre-defined entry
function—you define the entry point.
in dart, every app must have a top-level main() function that serves as the
entry point to the app.
<code_start>
/// dart
void main() {}
<code_end>
try it out in DartPad.
<topic_end>
<topic_start>
printing to the console
to print to the console in dart, use print().
<code_start>
/// dart
print('Hello world!');
<code_end>
try it out in DartPad.
<topic_end>
<topic_start>
variables
dart is type safe—it uses a combination of static type checking
and runtime checks to ensure that a variable’s value always matches
the variable’s static type. although types are mandatory,
some type annotations are optional because
dart performs type inference.
<topic_end>
<topic_start>
creating and assigning variables
in JavaScript, variables cannot be typed.
in dart, variables must either be explicitly
typed or the type system must infer the proper type automatically.
<code_start>
/// dart
/// both variables are acceptable.
string name = 'dart'; // explicitly typed as a [string].
var otherName = 'dart'; // inferred [string] type.
<code_end>
try it out in DartPad.
for more information, see dart’s type system.
<topic_end>
<topic_start>
default value
in JavaScript, uninitialized variables are undefined.
in dart, uninitialized variables have an initial value of null.
because numbers are objects in dart, even uninitialized variables with
numeric types have the value null.
info note
  as of 2.12, dart supports sound null safety,
  all underlying types are non-nullable by default,
  which must be initialized as a non-nullable value.
<code_start>
// dart
var name; // == null; raises a linter warning
int? x; // == null
<code_end>
try it out in DartPad.
for more information, see the documentation on
variables.
<topic_end>
<topic_start>
checking for null or zero
in JavaScript, values of 1 or any non-null objects
are treated as true when using the == comparison operator.
in dart, only the boolean value true is treated as true.
<code_start>
/// dart
var myNull;
var zero = 0;
if (zero == 0) {
  print('use "== 0" to check zero');
}
<code_end>
try it out in DartPad.
<topic_end>
<topic_start>
functions
dart and JavaScript functions are generally similar.
the primary difference is the declaration.
<code_start>
/// dart
/// you can explicitly define the return type.
bool fn() {
  return true;
}
<code_end>
try it out in DartPad.
for more information, see the documentation on
functions.
<topic_end>
<topic_start>
asynchronous programming
<topic_end>
<topic_start>
futures
like JavaScript, dart supports single-threaded execution. in JavaScript,
the promise object represents the eventual completion (or failure)
of an asynchronous operation and its resulting value.
dart uses future objects to handle this.
<code_start>
// dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class example {
  Future<String> _getIPAddress() {
    final url = uri.https('httpbin.org', '/ip');
    return http.get(url).then((response) {
      final ip = jsonDecode(response.body)['origin'] as string;
      return ip;
    });
  }
}
void main() {
  final example = example();
  example
      ._getipaddress()
      .then((ip) => print(ip))
      .catcherror((error) => print(error));
}
<code_end>
for more information, see the documentation on
future objects.
<topic_end>
<topic_start>
async and await
the async function declaration defines an asynchronous function.
in JavaScript, the async function returns a promise.
the await operator is used to wait for a promise.
in dart, an async function returns a future,
and the body of the function is scheduled for execution later.
the await operator is used to wait for a future.
<code_start>
// dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class example {
  Future<String> _getIPAddress() async {
    final url = uri.https('httpbin.org', '/ip');
    final response = await http.get(url);
    final ip = jsonDecode(response.body)['origin'] as string;
    return ip;
  }
}
/// an async function returns a `future`.
/// it can also return `void`, unless you use
/// the `avoid_void_async` lint. in that case,
/// return `future<void>`.
void main() async {
  final example = example();
  try {
    final ip = await example._getIPAddress();
    print(ip);
  } catch (error) {
    print(error);
  }
}
<code_end>
for more information, see the documentation for async and await.
<topic_end>
<topic_start>
the basics
<topic_end>
<topic_start>
how do i create a flutter app?
to create an app using react native,
you would run create-react-native-app from the command line.
to create an app in flutter, do one of the following:
for more information, see getting started, which
walks you through creating a button-click counter app.
creating a flutter project builds all the files that you
need to run a sample app on both android and iOS devices.
<topic_end>
<topic_start>
how do i run my app?
in react native, you would run npm run or yarn run from the project
directory.
you can run flutter apps in a couple of ways:
your app runs on a connected device, the iOS simulator,
or the android emulator.
for more information, see the flutter getting started
documentation.
<topic_end>
<topic_start>
how do i import widgets?
in react native, you need to import each required component.
in flutter, to use widgets from the material design library,
import the material.dart package. to use iOS style widgets,
import the cupertino library. to use a more basic widget set,
import the widgets library.
or, you can write your own widget library and import that.
<code_start>
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:my_widgets/my_widgets.dart';
<code_end>
whichever widget package you import,
dart pulls in only the widgets that are used in your app.
for more information, see the flutter widget catalog.
<topic_end>
<topic_start>
what is the equivalent of the react native “hello world!” app in flutter?
in react native, the HelloWorldApp class extends React.Component and
implements the render method by returning a view component.
in flutter, you can create an identical “hello world!” app using the
center and text widgets from the core widget library.
the center widget becomes the root of the widget tree and has one child,
the text widget.
<code_start>
// flutter
import 'package:flutter/material.dart';
void main() {
  runApp(
    const center(
      child: text(
        'hello, world!',
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}
<code_end>
the following images show the android and iOS UI for the basic flutter
“hello world!” app.
now that you’ve seen the most basic flutter app, the next section shows how to
take advantage of flutter’s rich widget libraries to create a modern, polished
app.
<topic_end>
<topic_start>
how do i use widgets and nest them to form a widget tree?
in flutter, almost everything is a widget.
widgets are the basic building blocks of an app’s user interface.
you compose widgets into a hierarchy, called a widget tree.
each widget nests inside a parent widget
and inherits properties from its parent.
even the application object itself is a widget.
there is no separate “application” object.
instead, the root widget serves this role.
a widget can define:
the following example shows the “hello world!” app using widgets from the
material library. in this example, the widget tree is nested inside the
MaterialApp root widget.
<code_start>
// flutter
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'welcome to flutter',
      home: scaffold(
        appBar: AppBar(
          title: const Text('Welcome to flutter'),
        ),
        body: const center(
          child: Text('Hello world'),
        ),
      ),
    );
  }
}
<code_end>
the following images show “hello world!” built from material design widgets.
you get more functionality for free than in the basic “hello world!” app.
when writing an app, you’ll use two types of widgets:
StatelessWidget or StatefulWidget.
a StatelessWidget is just what it sounds like—a
widget with no state. a StatelessWidget is created once,
and never changes its appearance.
a StatefulWidget dynamically changes state based on data
received, or user input.
the important difference between stateless and stateful
widgets is that StatefulWidgets have a state object
that stores state data and carries it over
across tree rebuilds, so it’s not lost.
in simple or basic apps it’s easy to nest widgets,
but as the code base gets larger and the app becomes complex,
you should break deeply nested widgets into
functions that return the widget or smaller classes.
creating separate functions
and widgets allows you to reuse the components within the app.
<topic_end>
<topic_start>
how do i create reusable components?
in react native, you would define a class to create a
reusable component and then use props methods to set
or return properties and values of the selected elements.
in the example below, the CustomCard class is defined
and then used inside a parent class.
in flutter, define a class to create a custom widget and then reuse the
widget. you can also define and call a function that returns a
reusable widget as shown in the build function in the following example.
<code_start>
/// flutter
class CustomCard extends StatelessWidget {
  const CustomCard({
    super.key,
    required this.index,
    required this.onPress,
  });
  final int index;
  final void function() onPress;
  @override
  widget build(BuildContext context) {
    return card(
      child: column(
        children: <widget>[
          Text('Card $index'),
          TextButton(
            onPressed: onPress,
            child: const Text('Press'),
          ),
        ],
      ),
    );
  }
}
class UseCard extends StatelessWidget {
  const UseCard({super.key, required this.index});
  final int index;
  @override
  widget build(BuildContext context) {
    /// usage
    return CustomCard(
      index: index,
      onPress: () {
        print('Card $index');
      },
    );
  }
}
<code_end>
in the previous example, the constructor for the CustomCard
class uses dart’s curly brace syntax { } to indicate named parameters.
to require these fields, either remove the curly braces from
the constructor, or add required to the constructor.
the following screenshots show an example of the reusable
CustomCard class.
<topic_end>
<topic_start>
project structure and resources
<topic_end>
<topic_start>
where do i start writing the code?
start with the lib/main.dart file.
it’s autogenerated when you create a flutter app.
<code_start>
// dart
void main() {
  print('Hello, this is the main function.');
}
<code_end>
in flutter, the entry point file is
{project_name}/lib/main.dart and execution
starts from the main function.
<topic_end>
<topic_start>
how are files structured in a flutter app?
when you create a new flutter project,
it builds the following directory structure.
you can customize it later, but this is where you start.
<topic_end>
<topic_start>
where do i put my resources and assets and how do i use them?
a flutter resource or asset is a file that is bundled and deployed
with your app and is accessible at runtime.
flutter apps can include the following asset types:
flutter uses the pubspec.yaml file,
located at the root of your project, to
identify assets required by an app.
the assets subsection specifies files that should be included with the app.
each asset is identified by an explicit path
relative to the pubspec.yaml file, where the asset file is located.
the order in which the assets are declared does not matter.
the actual directory used (assets in this case) does not matter.
however, while assets can be placed in any app directory, it’s a
best practice to place them in the assets directory.
during a build, flutter places assets into a special archive
called the asset bundle, which apps read from at runtime.
when an asset’s path is specified in the assets’ section of pubspec.yaml,
the build process looks for any files
with the same name in adjacent subdirectories.
these files are also included in the asset bundle
along with the specified asset. flutter uses asset variants
when choosing resolution-appropriate images for your app.
in react native, you would add a static image by placing the image file
in a source code directory and referencing it.
in flutter, add a static image to your app
using the image.asset constructor in a widget’s build method.
<code_start>
image.asset('assets/background.png');
<code_end>
for more information, see adding assets and images in flutter.
<topic_end>
<topic_start>
how do i load images over a network?
in react native, you would specify the uri in the
source prop of the image component and also provide the
size if needed.
in flutter, use the image.network constructor to include
an image from a URL.
<code_start>
image.network('https://docs.flutter.dev/assets/images/docs/owl.jpg');
<code_end>
<topic_end>
<topic_start>
how do i install packages and package plugins?
flutter supports using shared packages contributed by other developers to the
flutter and dart ecosystems. this allows you to quickly build your app without
having to develop everything from scratch. packages that contain
platform-specific code are known as package plugins.
in react native, you would use yarn add {package-name} or
npm install --save {package-name} to install packages
from the command line.
in flutter, install a package using the following instructions:
<code_start>
import 'package:flutter/material.dart';
<code_end>
for more information, see using packages and
developing packages & plugins.
you can find many packages shared by flutter developers in the
flutter packages section of pub.dev.
<topic_end>
<topic_start>
flutter widgets
in flutter, you build your UI out of widgets that describe what their view
should look like given their current configuration and state.
widgets are often composed of many small,
single-purpose widgets that are nested to produce powerful effects.
for example, the container widget consists of
several widgets responsible for layout, painting, positioning, and sizing.
specifically, the container widget includes the LimitedBox,
ConstrainedBox, align, padding, DecoratedBox, and transform widgets.
rather than subclassing container to produce a customized effect, you can
compose these and other simple widgets in new and unique ways.
the center widget is another example of how you can control the layout.
to center a widget, wrap it in a center widget and then use layout
widgets for alignment, row, columns, and grids.
these layout widgets do not have a visual representation of their own.
instead, their sole purpose is to control some aspect of another
widget’s layout. to understand why a widget renders in a
certain way, it’s often helpful to inspect the neighboring widgets.
for more information, see the flutter technical overview.
for more information about the core widgets from the widgets package,
see flutter basic widgets,
the flutter widget catalog,
or the flutter widget index.
<topic_end>
<topic_start>
views
<topic_end>
<topic_start>
what is the equivalent of the view container?
in react native, view is a container that supports layout with flexbox,
style, touch handling, and accessibility controls.
in flutter, you can use the core layout widgets in the widgets
library, such as container, column,
row, and center.
for more information, see the layout widgets catalog.
<topic_end>
<topic_start>
what is the equivalent of FlatList or SectionList?
a list is a scrollable list of components arranged vertically.
in react native, FlatList or SectionList are used to render simple or
sectioned lists.
ListView is flutter’s most commonly used scrolling widget.
the default constructor takes an explicit list of children.
ListView is most appropriate for a small number of widgets.
for a large or infinite list, use ListView.builder,
which builds its children on demand and only builds
those children that are visible.
<code_start>
var data = [
  'hello',
  'world',
];
return ListView.builder(
  itemCount: data.length,
  itemBuilder: (context, index) {
    return text(data[index]);
  },
);
<code_end>
to learn how to implement an infinite scrolling list, see the official
infinite_list sample.
<topic_end>
<topic_start>
how do i use a canvas to draw or paint?
in react native, canvas components aren’t present
so third party libraries like react-native-canvas are used.
in flutter, you can use the CustomPaint
and CustomPainter classes to draw to the canvas.
the following example shows how to draw during the paint phase using the
CustomPaint widget. it implements the abstract class, CustomPainter,
and passes it to CustomPaint’s painter property.
CustomPaint subclasses must implement the paint()
and shouldRepaint() methods.
<code_start>
class MyCanvasPainter extends CustomPainter {
  const MyCanvasPainter();
  @override
  void paint(Canvas canvas, size size) {
    final paint paint = paint()..color = colors.amber;
    canvas.drawCircle(const offset(100, 200), 40, paint);
    final paint paintRect = paint()..color = Colors.lightBlue;
    final rect rect = Rect.fromPoints(
      const offset(150, 300),
      const offset(300, 400),
    );
    canvas.drawRect(rect, paintRect);
  }
  @override
  bool shouldRepaint(MyCanvasPainter oldDelegate) => false;
}
class MyCanvasWidget extends StatelessWidget {
  const MyCanvasWidget({super.key});
  @override
  widget build(BuildContext context) {
    return const scaffold(
      body: CustomPaint(painter: MyCanvasPainter()),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
layouts
<topic_end>
<topic_start>
how do i use widgets to define layout properties?
in react native, most of the layout can be done with the props
that are passed to a specific component.
for example, you could use the style prop on the view component
in order to specify the flexbox properties.
to arrange your components in a column, you would specify a prop such as:
flexDirection: 'column'.
in flutter, the layout is primarily defined by widgets
specifically designed to provide layout,
combined with control widgets and their style properties.
for example, the column and row widgets
take an array of children and align them
vertically and horizontally respectively.
a container widget takes a combination of
layout and styling properties, and a
center widget centers its child widgets.
<code_start>
@override
widget build(BuildContext context) {
  return center(
    child: column(
      children: <widget>[
        container(
          color: colors.red,
          width: 100,
          height: 100,
        ),
        container(
          color: colors.blue,
          width: 100,
          height: 100,
        ),
        container(
          color: colors.green,
          width: 100,
          height: 100,
        ),
      ],
    ),
  );
<code_end>
flutter provides a variety of layout widgets in its core widget library.
for example, padding, align, and stack.
for a complete list, see layout widgets.
<topic_end>
<topic_start>
how do i layer widgets?
in react native, components can be layered using absolute positioning.
flutter uses the stack
widget to arrange children widgets in layers.
the widgets can entirely or partially overlap the base widget.
the stack widget positions its children relative to the edges of its box.
this class is useful if you simply want to overlap several children widgets.
<code_start>
@override
widget build(BuildContext context) {
  return stack(
    alignment: const alignment(0.6, 0.6),
    children: <widget>[
      const CircleAvatar(
        backgroundImage: NetworkImage(
          'https://avatars3.githubusercontent.com/u/14101776?v=4',
        ),
      ),
      container(
        color: colors.black45,
        child: const Text('Flutter'),
      ),
    ],
  );
<code_end>
the previous example uses stack to overlay a container
(that displays its text on a translucent black background)
on top of a CircleAvatar.
the stack offsets the text using the alignment property
and alignment coordinates.
for more information, see the stack class documentation.
<topic_end>
<topic_start>
styling
<topic_end>
<topic_start>
how do i style my components?
in react native, inline styling and stylesheets.create
are used to style components.
in flutter, a text widget can take a TextStyle class
for its style property. if you want to use the same text
style in multiple places, you can create a
TextStyle class and use it for multiple text widgets.
<code_start>
const TextStyle textStyle = TextStyle(
  color: colors.cyan,
  fontSize: 32,
  fontWeight: FontWeight.w600,
);
return const center(
  child: column(
    children: <widget>[
      Text('Sample text', style: textStyle),
      padding(
        padding: EdgeInsets.all(20),
        child: icon(
          icons.lightbulb_outline,
          size: 48,
          color: Colors.redAccent,
        ),
      ),
    ],
  ),
);
<code_end>
<topic_end>
<topic_start>
how do i use icons and colors?
react native doesn’t include support for icons
so third party libraries are used.
in flutter, importing the material library also pulls in the
rich set of material icons and colors.
<code_start>
return const Icon(Icons.lightbulb_outline, color: Colors.redAccent);
<code_end>
when using the icons class,
make sure to set uses-material-design: true in
the project’s pubspec.yaml file.
this ensures that the MaterialIcons font,
which displays the icons, is included in your app.
in general, if you intend to use the material library,
you should include this line.
flutter’s cupertino (ios-style) package provides high
fidelity widgets for the current iOS design language.
to use the CupertinoIcons font,
add a dependency for cupertino_icons in your project’s 
pubspec.yaml file.
to globally customize the colors and styles of components,
use ThemeData to specify default colors
for various aspects of the theme.
set the theme property in MaterialApp to the ThemeData object.
the colors class provides colors
from the material design color palette.
the following example sets the color scheme from seed to deepPurple
and the text selection to red.
<code_start>
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          textSelectionTheme:
              const TextSelectionThemeData(selectionColor: colors.red)),
      home: const SampleAppPage(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i add style themes?
in react native, common themes are defined for
components in stylesheets and then used in components.
in flutter, create uniform styling for almost everything
by defining the styling in the ThemeData
class and passing it to the theme property in the
MaterialApp widget.
<code_start>
@override
widget build(BuildContext context) {
  return MaterialApp(
    theme: ThemeData(
      primaryColor: colors.cyan,
      brightness: brightness.dark,
    ),
    home: const StylingPage(),
  );
}
<code_end>
a theme can be applied even without using the MaterialApp widget.
the theme widget takes a ThemeData in its data parameter
and applies the ThemeData to all of its children widgets.
<code_start>
@override
widget build(BuildContext context) {
  return theme(
    data: ThemeData(
      primaryColor: colors.cyan,
      brightness: brightness,
    ),
    child: scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      //...
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
state management
state is information that can be read synchronously
when a widget is built or information
that might change during the lifetime of a widget.
to manage app state in flutter,
use a StatefulWidget paired with a state object.
for more information on ways to approach managing state in flutter,
see state management.
<topic_end>
<topic_start>
the StatelessWidget
a StatelessWidget in flutter is a widget
that doesn’t require a state change—
it has no internal state to manage.
stateless widgets are useful when the part of the user interface
you are describing does not depend on anything other than the
configuration information in the object itself and the
BuildContext in which the widget is inflated.
AboutDialog, CircleAvatar, and text are examples
of stateless widgets that subclass StatelessWidget.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(
      const MyStatelessWidget(
        text: 'statelesswidget example to show immutable data',
      ),
    );
class MyStatelessWidget extends StatelessWidget {
  const MyStatelessWidget({
    super.key,
    required this.text,
  });
  final string text;
  @override
  widget build(BuildContext context) {
    return center(
      child: text(
        text,
        textDirection: TextDirection.ltr,
      ),
    );
  }
}
<code_end>
the previous example uses the constructor of the MyStatelessWidget
class to pass the text, which is marked as final.
this class extends StatelessWidget—it contains immutable data.
the build method of a stateless widget is typically called
in only three situations:
<topic_end>
<topic_start>
the StatefulWidget
a StatefulWidget is a widget that changes state.
use the setState method to manage the
state changes for a StatefulWidget.
a call to setState() tells the flutter
framework that something has changed in a state,
which causes an app to rerun the build() method
so that the app can reflect the change.
state is information that can be read synchronously when a widget
is built and might change during the lifetime of the widget.
it’s the responsibility of the widget implementer to ensure that
the state object is promptly notified when the state changes.
use StatefulWidget when a widget can change dynamically.
for example, the state of the widget changes by typing into a form,
or moving a slider.
or, it can change over time—perhaps a data feed updates the UI.
checkbox, radio, slider, InkWell,
form, and TextField
are examples of stateful widgets that subclass
StatefulWidget.
the following example declares a StatefulWidget
that requires a createState() method.
this method creates the state object that manages the widget’s state,
_MyStatefulWidgetState.
<code_start>
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({
    super.key,
    required this.title,
  });
  final string title;
  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
<code_end>
the following state class, _MyStatefulWidgetState,
implements the build() method for the widget.
when the state changes, for example, when the user toggles
the button, setState() is called with the new toggle value.
this causes the framework to rebuild this widget in the UI.
<code_start>
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool showText = true;
  bool toggleState = true;
  timer? t2;
  void toggleBlinkState() {
    setState(() {
      toggleState = !togglestate;
    });
    if (!togglestate) {
      t2 = timer.periodic(const duration(milliseconds: 1000), (t) {
        toggleShowText();
      });
    } else {
      t2?.cancel();
    }
  }
  void toggleShowText() {
    setState(() {
      showText = !showtext;
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: column(
          children: <widget>[
            if (showtext)
              const text(
                'this execution will be done before you can blink.',
              ),
            padding(
              padding: const EdgeInsets.only(top: 70),
              child: ElevatedButton(
                onPressed: toggleBlinkState,
                child: toggleState
                    ? const Text('Blink')
                    : const Text('Stop blinking'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
what are the StatefulWidget and StatelessWidget best practices?
here are a few things to consider when designing your widget.
in flutter, widgets are either stateful or stateless—depending on whether
they depend on a state change.
in flutter, there are three primary ways to manage state:
when deciding which approach to use, consider the following principles:
the MyStatefulWidget class manages its own state—it extends
StatefulWidget, it overrides the createState()
method to create the state object,
and the framework calls createState() to build the widget.
in this example, createState() creates an instance of
_MyStatefulWidgetState, which
is implemented in the next best practice.
<code_start>
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({
    super.key,
    required this.title,
  });
  final string title;
  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  widget build(BuildContext context) {
    //...
  }
}
<code_end>
add your custom StatefulWidget to the widget tree
in the app’s build method.
<code_start>
class MyStatelessWidget extends StatelessWidget {
  // this widget is the root of your application.
  const MyStatelessWidget({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'flutter demo',
      home: MyStatefulWidget(title: 'state change demo'),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
props
in react native, most components can be customized when they are
created with different parameters or properties, called props.
these parameters can be used in a child component using this.props.
in flutter, you assign a local variable or function marked
final with the property received in the parameterized constructor.
<code_start>
/// flutter
class CustomCard extends StatelessWidget {
  const CustomCard({
    super.key,
    required this.index,
    required this.onPress,
  });
  final int index;
  final void function() onPress;
  @override
  widget build(BuildContext context) {
    return card(
      child: column(
        children: <widget>[
          Text('Card $index'),
          TextButton(
            onPressed: onPress,
            child: const Text('Press'),
          ),
        ],
      ),
    );
  }
}
class UseCard extends StatelessWidget {
  const UseCard({super.key, required this.index});
  final int index;
  @override
  widget build(BuildContext context) {
    /// usage
    return CustomCard(
      index: index,
      onPress: () {
        print('Card $index');
      },
    );
  }
}
<code_end>
<topic_end>
<topic_start>
local storage
if you don’t need to store a lot of data, and it doesn’t require
structure, you can use shared_preferences which allows you to
read and write persistent key-value pairs of primitive data
types: booleans, floats, ints, longs, and strings.
<topic_end>
<topic_start>
how do i store persistent key-value pairs that are global to the app?
in react native, you use the setItem and getItem functions
of the AsyncStorage component to store and retrieve data
that is persistent and global to the app.
in flutter, use the shared_preferences plugin to
store and retrieve key-value data that is persistent and global
to the app. the shared_preferences plugin wraps
NSUserDefaults on iOS and SharedPreferences on android,
providing a persistent store for simple data.
to add the shared_preferences package as a dependency, run flutter pub add:
<code_start>
import 'package:shared_preferences/shared_preferences.dart';
<code_end>
to implement persistent data, use the setter methods
provided by the SharedPreferences class.
setter methods are available for various primitive
types, such as setInt, setBool, and setString.
to read data, use the appropriate getter method provided
by the SharedPreferences class. for each
setter there is a corresponding getter method,
for example, getInt, getBool, and getString.
<code_start>
future<void> updateCounter() async {
  final prefs = await SharedPreferences.getInstance();
  int? counter = prefs.getInt('counter');
  if (counter is int) {
    await prefs.setInt('counter', ++counter);
  }
  setState(() {
    _counter = counter;
  });
}
<code_end>
<topic_end>
<topic_start>
routing
most apps contain several screens for displaying different
types of information. for example, you might have a product
screen that displays images where users could tap on a product
image to get more information about the product on a new screen.
in android, new screens are new activities.
in iOS, new screens are new ViewControllers. in flutter,
screens are just widgets! and to navigate to new
screens in flutter, use the navigator widget.
<topic_end>
<topic_start>
how do i navigate between screens?
in react native, there are three main navigators:
StackNavigator, TabNavigator, and DrawerNavigator.
each provides a way to configure and define the screens.
in flutter, there are two main widgets used to navigate between screens:
a navigator is defined as a widget that manages a set of child
widgets with a stack discipline. the navigator manages a stack
of route objects and provides methods for managing the stack,
like navigator.push and navigator.pop.
a list of routes might be specified in the MaterialApp widget,
or they might be built on the fly, for example, in hero animations.
the following example specifies named routes in the MaterialApp widget.
info note
  named routes are no longer recommended for most
  applications. for more information, see
  limitations in the navigation overview page.
<code_start>
class NavigationApp extends StatelessWidget {
  // this widget is the root of your application.
  const NavigationApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      //...
      routes: <string, WidgetBuilder>{
        '/a': (context) => const UsualNavScreen(),
        '/b': (context) => const DrawerNavScreen(),
      },
      //...
    );
  }
}
<code_end>
to navigate to a named route, the navigator.of()
method is used to specify the BuildContext
(a handle to the location of a widget in the widget tree).
the name of the route is passed to the pushNamed function to
navigate to the specified route.
<code_start>
Navigator.of(context).pushNamed('/a');
<code_end>
you can also use the push method of navigator which
adds the given route to the history of the
navigator that most tightly encloses the given BuildContext,
and transitions to it. in the following example,
the MaterialPageRoute widget is a modal route that
replaces the entire screen with a platform-adaptive
transition. it takes a WidgetBuilder as a required parameter.
<code_start>
navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => const UsualNavScreen(),
  ),
);
<code_end>
<topic_end>
<topic_start>
how do i use tab navigation and drawer navigation?
in material design apps, there are two primary options
for flutter navigation: tabs and drawers.
when there is insufficient space to support tabs, drawers
provide a good alternative.
<topic_end>
<topic_start>
tab navigation
in react native, createBottomTabNavigator
and TabNavigation are used to
show tabs and for tab navigation.
flutter provides several specialized widgets for drawer and
tab navigation:
<code_start>
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  late TabController controller = TabController(length: 2, vsync: this);
  @override
  widget build(BuildContext context) {
    return TabBar(
      controller: controller,
      tabs: const <tab>[
        tab(icon: Icon(Icons.person)),
        tab(icon: Icon(Icons.email)),
      ],
    );
  }
}
<code_end>
a TabController is required to coordinate the tab selection
between a TabBar and a TabBarView.
the TabController constructor length argument is the total
number of tabs. a TickerProvider is required to trigger
the notification whenever a frame triggers a state change.
the TickerProvider is vsync. pass the
vsync: this argument to the TabController constructor
whenever you create a new TabController.
the TickerProvider is an interface implemented
by classes that can vend ticker objects.
tickers can be used by any object that must be notified whenever a
frame triggers, but they’re most commonly used indirectly via an
AnimationController. AnimationControllers
need a TickerProvider to obtain their ticker.
if you are creating an AnimationController from a state,
then you can use the TickerProviderStateMixin
or SingleTickerProviderStateMixin
classes to obtain a suitable TickerProvider.
the scaffold widget wraps a new TabBar widget and
creates two tabs. the TabBarView widget
is passed as the body parameter of the scaffold widget.
all screens corresponding to the TabBar widget’s tabs are
children to the TabBarView widget along with the same TabController.
<code_start>
class _NavigationHomePageState extends State<NavigationHomePage>
    with SingleTickerProviderStateMixin {
  late TabController controller = TabController(length: 2, vsync: this);
  @override
  widget build(BuildContext context) {
    return scaffold(
        bottomNavigationBar: material(
          color: colors.blue,
          child: TabBar(
            tabs: const <tab>[
              tab(
                icon: Icon(Icons.person),
              ),
              tab(
                icon: Icon(Icons.email),
              ),
            ],
            controller: controller,
          ),
        ),
        body: TabBarView(
          controller: controller,
          children: const <widget>[homescreen(), TabScreen()],
        ));
  }
}
<code_end>
<topic_end>
<topic_start>
drawer navigation
in react native, import the needed react-navigation packages and then use
createDrawerNavigator and DrawerNavigation.
in flutter, we can use the drawer widget in combination with a
scaffold to create a layout with a material design drawer.
to add a drawer to an app, wrap it in a scaffold widget.
the scaffold widget provides a consistent
visual structure to apps that follow the
material design guidelines. it also supports
special material design components,
such as drawers, AppBars, and SnackBars.
the drawer widget is a material design panel that slides
in horizontally from the edge of a scaffold to show navigation
links in an application. you can
provide a ElevatedButton, a text widget,
or a list of items to display as the child to the drawer widget.
in the following example, the ListTile
widget provides the navigation on tap.
<code_start>
@override
widget build(BuildContext context) {
  return drawer(
    elevation: 20,
    child: ListTile(
      leading: const Icon(Icons.change_history),
      title: const Text('Screen2'),
      onTap: () {
        Navigator.of(context).pushNamed('/b');
      },
    ),
  );
}
<code_end>
the scaffold widget also includes an AppBar widget that automatically
displays an appropriate IconButton to show the drawer when a drawer is
available in the scaffold. the scaffold automatically handles the
edge-swipe gesture to show the drawer.
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    drawer: drawer(
      elevation: 20,
      child: ListTile(
        leading: const Icon(Icons.change_history),
        title: const Text('Screen2'),
        onTap: () {
          Navigator.of(context).pushNamed('/b');
        },
      ),
    ),
    appBar: AppBar(title: const Text('Home')),
    body: container(),
  );
}
<code_end>
<topic_end>
<topic_start>
gesture detection and touch event handling
to listen for and respond to gestures,
flutter supports taps, drags, and scaling.
the gesture system in flutter has two separate layers.
the first layer includes raw pointer events,
which describe the location and movement of pointers,
(such as touches, mice, and styli movements), across the screen.
the second layer includes gestures,
which describe semantic actions
that consist of one or more pointer movements.
<topic_end>
<topic_start>
how do i add a click or press listeners to a widget?
in react native, listeners are added to components
using PanResponder or the touchable components.
for more complex gestures and combining several touches into
a single gesture, PanResponder is used.
in flutter, to add a click (or press) listener to a widget,
use a button or a touchable widget that has an onPress: field.
or, add gesture detection to any widget by wrapping it
in a GestureDetector.
<code_start>
@override
widget build(BuildContext context) {
  return GestureDetector(
    child: scaffold(
      appBar: AppBar(title: const Text('Gestures')),
      body: const center(
          child: column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <widget>[
          Text('Tap, long press, swipe horizontally or vertically'),
        ],
      )),
    ),
    onTap: () {
      print('Tapped');
    },
    onLongPress: () {
      print('Long pressed');
    },
    onVerticalDragEnd: (value) {
      print('Swiped vertically');
    },
    onHorizontalDragEnd: (value) {
      print('Swiped horizontally');
    },
  );
}
<code_end>
for more information, including a list of
flutter GestureDetector callbacks,
see the GestureDetector class.
<topic_end>
<topic_start>
making HTTP network requests
fetching data from the internet is common for most apps. and in flutter,
the http package provides the simplest way to fetch data from the internet.
<topic_end>
<topic_start>
how do i fetch data from API calls?
react native provides the fetch API for networking—you make a fetch request
and then receive the response to get the data.
flutter uses the http package.
to add the http package as a dependency, run flutter pub add:
flutter uses the dart:io core HTTP support client.
to create an HTTP client, import dart:io.
<code_start>
import 'dart:io';
<code_end>
the client supports the following HTTP operations:
GET, POST, PUT, and DELETE.
<code_start>
final url = uri.parse('https://httpbin.org/ip');
final httpClient = HttpClient();
future<void> getIPAddress() async {
  final request = await httpClient.getUrl(url);
  final response = await request.close();
  final responseBody = await response.transform(utf8.decoder).join();
  final ip = jsonDecode(responseBody)['origin'] as string;
  setState(() {
    _ipAddress = ip;
  });
}
<code_end>
<topic_end>
<topic_start>
form input
text fields allow users to type text into your app so they can be
used to build forms, messaging apps, search experiences, and more.
flutter provides two core text field widgets:
TextField and TextFormField.
<topic_end>
<topic_start>
how do i use text field widgets?
in react native, to enter text you use a TextInput component to show a text
input box and then use the callback to store the value in a variable.
in flutter, use the TextEditingController
class to manage a TextField widget.
whenever the text field is modified,
the controller notifies its listeners.
listeners read the text and selection properties to
learn what the user typed into the field.
you can access the text in TextField
by the text property of the controller.
<code_start>
final TextEditingController _controller = TextEditingController();
@override
widget build(BuildContext context) {
  return column(children: [
    TextField(
      controller: _controller,
      decoration: const InputDecoration(
        hintText: 'type something',
        labelText: 'text field',
      ),
    ),
    ElevatedButton(
      child: const Text('Submit'),
      onPressed: () {
        showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: const Text('Alert'),
                content: Text('You typed ${_controller.text}'),
              );
            });
      },
    ),
  ]);
}
<code_end>
in this example, when a user clicks on the submit button an alert dialog
displays the current text entered in the text field.
this is achieved using an AlertDialog
widget that displays the alert message, and the text from
the TextField is accessed by the text property of the
TextEditingController.
<topic_end>
<topic_start>
how do i use form widgets?
in flutter, use the form widget where
TextFormField widgets along with the submit
button are passed as children.
the TextFormField widget has a parameter called
onSaved that takes a callback and executes
when the form is saved. a FormState
object is used to save, reset, or validate
each FormField that is a descendant of this form.
to obtain the FormState, you can use form.of()
with a context whose ancestor is the form,
or pass a GlobalKey to the form constructor and call
GlobalKey.currentState().
<code_start>
@override
widget build(BuildContext context) {
  return form(
    key: formKey,
    child: column(
      children: <widget>[
        TextFormField(
          validator: (value) {
            if (value != null && value.contains('@')) {
              return null;
            }
            return 'not a valid email.';
          },
          onSaved: (val) {
            _email = val;
          },
          decoration: const InputDecoration(
            hintText: 'enter your email',
            labelText: 'email',
          ),
        ),
        ElevatedButton(
          onPressed: _submit,
          child: const Text('Login'),
        ),
      ],
    ),
  );
}
<code_end>
the following example shows how form.save() and formKey
(which is a GlobalKey), are used to save the form on submit.
<code_start>
void _submit() {
  final form = formKey.currentState;
  if (form != null && form.validate()) {
    form.save();
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
            title: const Text('Alert'),
            content: Text('Email: $_email, password: $_password'));
      },
    );
  }
}
<code_end>
<topic_end>
<topic_start>
platform-specific code
when building a cross-platform app, you want to re-use as much code as
possible across platforms. however, scenarios might arise where it
makes sense for the code to be different depending on the OS.
this requires a separate implementation by declaring a specific platform.
in react native, the following implementation would be used:
in flutter, use the following implementation:
<code_start>
final platform = theme.of(context).platform;
if (platform == TargetPlatform.iOS) {
  return 'ios';
}
if (platform == TargetPlatform.android) {
  return 'android';
}
if (platform == TargetPlatform.fuchsia) {
  return 'fuchsia';
}
return 'not recognized ';
<code_end>
<topic_end>
<topic_start>
debugging
<topic_end>
<topic_start>
what tools can i use to debug my app in flutter?
use the DevTools suite for debugging flutter or dart apps.
DevTools includes support for profiling, examining the heap,
inspecting the widget tree, logging diagnostics, debugging,
observing executed lines of code, debugging memory leaks and memory
fragmentation. for more information, see the
DevTools documentation.
if you’re using an IDE,
you can debug your application using the IDE’s debugger.
<topic_end>
<topic_start>
how do i perform a hot reload?
flutter’s stateful hot reload feature helps you quickly and easily experiment,
build UIs, add features, and fix bugs. instead of recompiling your app
every time you make a change, you can hot reload your app instantly.
the app is updated to reflect your change,
and the current state of the app is preserved.
in react native,
the shortcut is ⌘r for the iOS simulator and tapping r twice on
android emulators.
in flutter, if you are using IntelliJ IDE or android studio,
you can select save all (⌘s/ctrl-s), or you can click the
hot reload button on the toolbar. if you
are running the app at the command line using flutter run,
type r in the terminal window.
you can also perform a full restart by typing r in the
terminal window.
<topic_end>
<topic_start>
how do i access the in-app developer menu?
in react native, the developer menu can be accessed by shaking your device: ⌘d
for the iOS simulator or ⌘m for android emulator.
in flutter, if you are using an IDE, you can use the IDE tools. if you start
your application using flutter run you can also access the menu by typing h
in the terminal window, or type the following shortcuts:
<topic_end>
<topic_start>
animation
well-designed animation makes a UI feel intuitive,
contributes to the look and feel of a polished app,
and improves the user experience.
flutter’s animation support makes it easy
to implement simple and complex animations.
the flutter SDK includes many material design widgets
that include standard motion effects,
and you can easily customize these effects
to personalize your app.
in react native, animated APIs are used to create animations.
in flutter, use the animation
class and the AnimationController class.
animation is an abstract class that understands its
current value and its state (completed or dismissed).
the AnimationController class lets you
play an animation forward or in reverse,
or stop animation and set the animation
to a specific value to customize the motion.
<topic_end>
<topic_start>
how do i add a simple fade-in animation?
in the react native example below, an animated component,
FadeInView is created using the animated API.
the initial opacity state, final state, and the
duration over which the transition occurs are defined.
the animation component is added inside the animated component,
the opacity state fadeAnim is mapped
to the opacity of the text component that we want to animate,
and then, start() is called to start the animation.
to create the same animation in flutter, create an
AnimationController object named controller
and specify the duration. by default, an AnimationController
linearly produces values that range from 0.0 to 1.0,
during a given duration. the animation controller generates a new value
whenever the device running your app is ready to display a new frame.
typically, this rate is around 60 values per second.
when defining an AnimationController,
you must pass in a vsync object.
the presence of vsync prevents offscreen
animations from consuming unnecessary resources.
you can use your stateful object as the vsync by adding
TickerProviderStateMixin to the class definition.
an AnimationController needs a TickerProvider,
which is configured using the vsync argument on the constructor.
a tween describes the interpolation between a
beginning and ending value or the mapping from an input
range to an output range. to use a tween object
with an animation, call the tween object’s animate()
method and pass it the animation object that you want to modify.
for this example, a FadeTransition
widget is used and the opacity property is
mapped to the animation object.
to start the animation, use controller.forward().
other operations can also be performed using the
controller such as fling() or repeat().
for this example, the FlutterLogo
widget is used inside the FadeTransition widget.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const center(child: LogoFade()));
}
class LogoFade extends StatefulWidget {
  const LogoFade({super.key});
  @override
  State<LogoFade> createState() => _LogoFadeState();
}
class _LogoFadeState extends State<LogoFade>
    with SingleTickerProviderStateMixin {
  late animation<double> animation;
  late AnimationController controller;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const duration(milliseconds: 3000),
      vsync: this,
    );
    final CurvedAnimation curve = CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn,
    );
    animation = tween(begin: 0.0, end: 1.0).animate(curve);
    controller.forward();
  }
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return FadeTransition(
      opacity: animation,
      child: const SizedBox(
        height: 300,
        width: 300,
        child: FlutterLogo(),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i add swipe animation to cards?
in react native, either the PanResponder or
third-party libraries are used for swipe animation.
in flutter, to add a swipe animation, use the
dismissible widget and nest the child widgets.
<code_start>
return dismissible(
  key: Key(widget.key.toString()),
  onDismissed: (dismissdirection) {
    cards.removeLast();
  },
  child: container(
      //...
      ),
);
<code_end>
<topic_end>
<topic_start>
react native and flutter widget equivalent components
the following table lists commonly-used react native
components mapped to the corresponding flutter widget
and common widget properties.
<topic_end>
<topic_start>
flutter for web developers
this page is for users who are familiar with the HTML
and CSS syntax for arranging components of an application’s UI.
it maps HTML/CSS code snippets to their Flutter/Dart code equivalents.
flutter is a framework for building cross-platform applications
that uses the dart programming language.
to understand some differences between programming with dart
and programming with javascript, 
see learning dart as a JavaScript developer.
one of the fundamental differences between
designing a web layout and a flutter layout,
is learning how constraints work,
and how widgets are sized and positioned.
to learn more, see understanding constraints.
the examples assume:
the HTML document starts with <!doctype html>, and the CSS box model
for all HTML elements is set to border-box,
for consistency with the flutter model.
in flutter, the default styling of the ‘lorem ipsum’ text
is defined by the bold24Roboto variable as follows,
to keep the syntax simple:
<code_start>
TextStyle bold24Roboto = const TextStyle(
  color: colors.white,
  fontSize: 24,
  fontWeight: FontWeight.bold,
);
<code_end>
how is react-style, or declarative, programming different from the
  traditional imperative style?
  for a comparison, see introduction to declarative UI.
<topic_end>
<topic_start>
performing basic layout operations
the following examples show how to perform the most common UI layout tasks.
<topic_end>
<topic_start>
styling and aligning text
font style, size, and other text attributes that CSS
handles with the font and color properties are individual
properties of a TextStyle child of a text widget.
for text-align property in CSS that is used for aligning text,
there is a textAlign property of a text widget.
in both HTML and flutter, child elements or widgets
are anchored at the top left, by default.
<topic_end>
<topic_start>
setting background color
in flutter, you set the background color using the color property
or the decoration property of a container.
however, you cannot supply both, since it would potentially
result in the decoration drawing over the background color.
the color property should be preferred
when the background is a simple color.
for other cases, such as gradients or images,
use the decoration property.
the CSS examples use the hex color equivalents to the material color palette.
<topic_end>
<topic_start>
centering components
a center widget centers its child both horizontally
and vertically.
to accomplish a similar effect in CSS, the parent element uses either a flex
or table-cell display behavior. the examples on this page show the flex
behavior.
<topic_end>
<topic_start>
setting container width
to specify the width of a container
widget, use its width property.
this is a fixed width, unlike the CSS max-width property
that adjusts the container width up to a maximum value.
to mimic that effect in flutter,
use the constraints property of the container.
create a new BoxConstraints widget with a minWidth or maxWidth.
for nested containers, if the parent’s width is less than the child’s width,
the child container sizes itself to match the parent.
<topic_end>
<topic_start>
manipulating position and size
the following examples show how to perform more complex operations
on widget position, size, and background.
<topic_end>
<topic_start>
setting absolute position
by default, widgets are positioned relative to their parent.
to specify an absolute position for a widget as x-y coordinates,
nest it in a positioned widget that is,
in turn, nested in a stack widget.
<topic_end>
<topic_start>
rotating components
to rotate a widget, nest it in a transform widget.
use the transform widget’s alignment and origin properties
to specify the transform origin (fulcrum) in relative and absolute terms,
respectively.
for a simple 2d rotation, in which the widget is rotated on the z axis,
create a new matrix4 identity object
and use its rotateZ() method to specify the rotation factor
using radians (degrees × π / 180).
<topic_end>
<topic_start>
scaling components
to scale a widget up or down, nest it in a transform widget.
use the transform widget’s alignment and origin properties
to specify the transform origin (fulcrum) in relative or absolute terms,
respectively.
for a simple scaling operation along the x-axis,
create a new matrix4 identity object
and use its scale() method to specify the scaling factor.
when you scale a parent widget,
its child widgets are scaled accordingly.
<topic_end>
<topic_start>
applying a linear gradient
to apply a linear gradient to a widget’s background,
nest it in a container widget.
then use the container widget’s decoration property to create a
BoxDecoration object, and use BoxDecoration’s gradient
property to transform the background fill.
the gradient “angle” is based on the alignment (x, y) values:
<topic_end>
<topic_start>
vertical gradient
<topic_end>
<topic_start>
horizontal gradient
<topic_end>
<topic_start>
manipulating shapes
the following examples show how to make and customize shapes.
<topic_end>
<topic_start>
rounding corners
to round the corners of a rectangular shape,
use the borderRadius property of a BoxDecoration object.
create a new BorderRadius
object that specifies the radius for rounding each corner.
<topic_end>
<topic_start>
adding box shadows
in CSS you can specify shadow offset and blur in shorthand,
using the box-shadow property. this example shows two box shadows,
with properties:
in flutter, each property and value is specified separately.
use the boxShadow property of BoxDecoration to create a list of
BoxShadow widgets. you can define one or multiple
BoxShadow widgets, which can be stacked
to customize the shadow depth, color, and so on.
<topic_end>
<topic_start>
making circles and ellipses
making a circle in CSS requires a workaround of applying a
border-radius of 50% to all four sides of a rectangle,
though there are basic shapes.
while this approach is supported
with the borderRadius property of BoxDecoration,
flutter provides a shape property
with BoxShape enum for this purpose.
<topic_end>
<topic_start>
manipulating text
the following examples show how to specify fonts and other
text attributes. they also show how to transform text strings,
customize spacing, and create excerpts.
<topic_end>
<topic_start>
adjusting text spacing
in CSS, you specify the amount of white space
between each letter or word by giving a length value
for the letter-spacing and word-spacing properties, respectively.
the amount of space can be in px, pt, cm, em, etc.
in flutter, you specify white space as logical pixels
(negative values are allowed)
for the letterSpacing and wordSpacing properties
of a TextStyle child of a text widget.
<topic_end>
<topic_start>
making inline formatting changes
a text widget lets you display text
with some formatting characteristics.
to display text that uses multiple styles
(in this example, a single word with emphasis),
use a RichText widget instead.
its text property can specify one or more
TextSpan objects that can be individually styled.
in the following example, “lorem” is in a TextSpan
with the default (inherited) text styling,
and “ipsum” is in a separate TextSpan with custom styling.
<topic_end>
<topic_start>
creating text excerpts
an excerpt displays the initial line(s) of text in a paragraph,
and handles the overflow text, often using an ellipsis.
in flutter, use the maxLines property of a text widget
to specify the number of lines to include in the excerpt,
and the overflow property for handling overflow text.
<topic_end>
<topic_start>
flutter for Xamarin.Forms developers
this document is meant for Xamarin.Forms developers
looking to apply their existing knowledge
to build mobile apps with flutter.
if you understand the fundamentals of the Xamarin.Forms framework,
then you can use this document as a jump start to flutter development.
your android and iOS knowledge and skill set
are valuable when building with flutter,
because flutter relies on the native operating system configurations,
similar to how you would configure your native Xamarin.Forms projects.
the flutter frameworks is also similar to how you create a single UI,
that is used on multiple platforms.
this document can be used as a cookbook by jumping around
and finding questions that are most relevant to your needs.
<topic_end>
<topic_start>
project setup
<topic_end>
<topic_start>
how does the app start?
for each platform in Xamarin.Forms,
you call the LoadApplication method,
which creates a new application and starts your app.
in flutter, the default main entry point is
main where you load your flutter app.
<code_start>
void main() {
  runApp(const MyApp());
}
<code_end>
in Xamarin.Forms, you assign a page to the
MainPage property in the application class.
in flutter, “everything is a widget”, even the application itself.
the following example shows MyApp, a simple application widget.
<code_start>
class MyApp extends StatelessWidget {
  /// this widget is the root of your application.
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const center(
      child: text(
        'hello world!',
        textDirection: TextDirection.ltr,
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do you create a page?
Xamarin.Forms has many types of pages;
ContentPage is the most common.
in flutter, you specify an application widget that holds your root page.
you can use a MaterialApp widget, which supports material design,
or you can use a CupertinoApp widget, which supports an iOS-style app,
or you can use the lower level WidgetsApp,
which you can customize in any way you want.
the following code defines the home page, a stateful widget.
in flutter, all widgets are immutable,
but two types of widgets are supported: stateful and stateless.
examples of a stateless widget are titles, icons, or images.
the following example uses MaterialApp,
which holds its root page in the home property.
<code_start>
class MyApp extends StatelessWidget {
  /// this widget is the root of your application.
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'flutter demo',
      home: MyHomePage(title: 'flutter demo home page'),
    );
  }
}
<code_end>
from here, your actual first page is another widget,
in which you create your state.
a stateful widget, such as MyHomePage below, consists of two parts.
the first part, which is itself immutable, creates a state object
that holds the state of the object. the state object persists over
the life of the widget.
<code_start>
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final string title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
<code_end>
the state object implements the build() method for the stateful widget.
when the state of the widget tree changes, call setState(),
which triggers a build of that portion of the UI.
make sure to call setState() only when necessary,
and only on the part of the widget tree that has changed,
or it can result in poor UI performance.
<code_start>
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        // take the value from the MyHomePage object that was created by
        // the app.build method, and use it to set the appbar title.
        title: text(widget.title),
      ),
      body: center(
        // center is a layout widget. it takes a single child and positions it
        // in the middle of the parent.
        child: column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <widget>[
            const text(
              'you have pushed the button this many times:',
            ),
            text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
<code_end>
in flutter, the UI (also known as widget tree), is immutable,
meaning you can’t change its state once it’s built.
you change fields in your state class, then call setState()
to rebuild the entire widget tree again.
this way of generating UI is different from Xamarin.Forms,
but there are many benefits to this approach.
<topic_end>
<topic_start>
views
<topic_end>
<topic_start>
what is the equivalent of a page or element in flutter?
how is react-style, or declarative, programming different from the
  traditional imperative style?
  for a comparison, see introduction to declarative UI.
ContentPage, TabbedPage, FlyoutPage are all types of pages
you might use in a Xamarin.Forms application.
these pages would then hold elements to display the various controls.
in Xamarin.Forms an entry or button are examples of an element.
in flutter, almost everything is a widget.
a page, called a route in flutter, is a widget.
buttons, progress bars, and animation controllers are all widgets.
when building a route, you create a widget tree.
flutter includes the material components library.
these are widgets that implement the material design guidelines.
material design is a flexible design system
optimized for all platforms, including iOS.
but flutter is flexible and expressive enough
to implement any design language.
for example, on iOS, you can use the cupertino widgets
to produce an interface that looks like apple’s iOS design language.
<topic_end>
<topic_start>
how do i update widgets?
in Xamarin.Forms, each page or element is a stateful class,
that has properties and methods.
you update your element by updating a property,
and this is propagated down to the native control.
in flutter, widgets are immutable and you can’t directly update them
by changing a property, instead you have to work with the widget’s state.
this is where the concept of stateful vs stateless widgets comes from.
a StatelessWidget is just what it sounds like—
a widget with no state information.
StatelessWidgets are useful when the part of the user interface
you are describing doesn’t depend on anything
other than the configuration information in the object.
for example, in Xamarin.Forms, this is similar
to placing an image with your logo.
the logo is not going to change during runtime,
so use a StatelessWidget in flutter.
if you want to dynamically change the UI based on data received
after making an HTTP call or a user interaction,
then you have to work with StatefulWidget
and tell the flutter framework that
the widget’s state has been updated,
so it can update that widget.
the important thing to note here is at the core
both stateless and stateful widgets behave the same.
they rebuild every frame, the difference is
the StatefulWidget has a state object
that stores state data across frames and restores it.
if you are in doubt, then always remember this rule: if a widget changes
(because of user interactions, for example) it’s stateful.
however, if a widget reacts to change, the containing parent widget can
still be stateless if it doesn’t itself react to change.
the following example shows how to use a StatelessWidget.
a common StatelessWidget is the text widget.
if you look at the implementation of the text widget
you’ll find it subclasses StatelessWidget.
<code_start>
const text(
  'i like flutter!',
  style: TextStyle(fontWeight: FontWeight.bold),
);
<code_end>
as you can see, the text widget has no state information associated with it,
it renders what is passed in its constructors and nothing more.
but, what if you want to make “i like flutter” change dynamically,
for example, when clicking a FloatingActionButton?
to achieve this, wrap the text widget in a StatefulWidget
and update it when the user clicks the button,
as shown in the following example:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  /// default placeholder text
  string textToShow = 'i like flutter';
  void _updateText() {
    setState(() {
      // update the text
      textToShow = 'flutter is awesome!';
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: center(child: Text(textToShow)),
      floatingActionButton: FloatingActionButton(
        onPressed: _updateText,
        tooltip: 'update text',
        child: const Icon(Icons.update),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i lay out my widgets? what is the equivalent of an XAML file?
in Xamarin.Forms, most developers write layouts in XAML,
though sometimes in c#.
in flutter, you write your layouts with a widget tree in code.
the following example shows how to display a simple widget with padding:
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(title: const Text('Sample app')),
    body: center(
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.only(left: 20, right: 30),
        ),
        onPressed: () {},
        child: const Text('Hello'),
      ),
    ),
  );
}
<code_end>
you can view the layouts that flutter has to offer in the
widget catalog.
<topic_end>
<topic_start>
how do i add or remove an element from my layout?
in Xamarin.Forms, you had to remove or add an element in code.
this involved either setting the content property or calling
add() or remove() if it was a list.
in flutter, because widgets are immutable there is no direct equivalent.
instead, you can pass a function to the parent that returns a widget,
and control that child’s creation with a boolean flag.
the following example shows how to toggle between two widgets
when the user clicks the FloatingActionButton:
<code_start>
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  /// default value for toggle
  bool toggle = true;
  void _toggle() {
    setState(() {
      toggle = !toggle;
    });
  }
  widget _getToggleChild() {
    if (toggle) {
      return const Text('Toggle one');
    }
    return CupertinoButton(
      onPressed: () {},
      child: const Text('Toggle two'),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: center(child: _getToggleChild()),
      floatingActionButton: FloatingActionButton(
        onPressed: _toggle,
        tooltip: 'update text',
        child: const Icon(Icons.update),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i animate a widget?
in Xamarin.Forms, you create simple animations using ViewExtensions that
include methods such as FadeTo and TranslateTo.
you would use these methods on a view
to perform the required animations.
then in code behind, or a behavior, this would fade in the image,
over a 1-second period.
in flutter, you animate widgets using the animation library
by wrapping widgets inside an animated widget.
use an AnimationController, which is an animation<double>
that can pause, seek, stop and reverse the animation.
it requires a ticker that signals when vsync happens,
and produces a linear interpolation between 0 and 1
on each frame while it’s running.
you then create one or moreAnimations and attach them to the controller.
for example, you might use CurvedAnimation
to implement an animation along an interpolated curve.
in this sense, the controller is the “master” source of the animation progress
and the CurvedAnimation computes the curve
that replaces the controller’s default linear motion.
like widgets, animations in flutter work with composition.
when building the widget tree, you assign the animation
to an animated property of a widget,
such as the opacity of a FadeTransition,
and tell the controller to start the animation.
the following example shows how to write a FadeTransition that fades
the widget into a logo when you press the FloatingActionButton:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const FadeAppTest());
}
class FadeAppTest extends StatelessWidget {
  /// this widget is the root of your application.
  const FadeAppTest({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'fade demo',
      home: MyFadeTest(title: 'fade demo'),
    );
  }
}
class MyFadeTest extends StatefulWidget {
  const MyFadeTest({super.key, required this.title});
  final string title;
  @override
  State<MyFadeTest> createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
  late final AnimationController controller;
  late final CurvedAnimation curve;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const duration(milliseconds: 2000),
      vsync: this,
    );
    curve = CurvedAnimation(
      parent: controller,
      curve: Curves.easeIn,
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: text(widget.title)),
      body: center(
        child: FadeTransition(
          opacity: curve,
          child: const FlutterLogo(size: 100),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          controller.forward();
        },
        tooltip: 'fade',
        child: const Icon(Icons.brush),
      ),
    );
  }
}
<code_end>
for more information, see animation & motion widgets,
the animations tutorial, and the animations overview.
<topic_end>
<topic_start>
how do i draw/paint on the screen?
Xamarin.Forms never had a built-in way to draw directly on the screen.
many would use SkiaSharp, if they needed a custom image drawn.
in flutter, you have direct access to the skia canvas
and can easily draw on screen.
flutter has two classes that help you draw to the canvas: CustomPaint
and CustomPainter, the latter of which implements your algorithm to draw to
the canvas.
to learn how to implement a signature painter in flutter,
see collin’s answer on custom paint.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MaterialApp(home: DemoApp()));
}
class DemoApp extends StatelessWidget {
  const DemoApp({super.key});
  @override
  widget build(BuildContext context) => const scaffold(body: signature());
}
class signature extends StatefulWidget {
  const signature({super.key});
  @override
  SignatureState createState() => SignatureState();
}
class SignatureState extends State<Signature> {
  List<Offset?> _points = <offset?>[];
  void _onPanUpdate(DragUpdateDetails details) {
    setState(() {
      final RenderBox referenceBox = context.findRenderObject() as RenderBox;
      final offset localPosition = referenceBox.globalToLocal(
        details.globalPosition,
      );
      _points = List.from(_points)..add(localPosition);
    });
  }
  @override
  widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: _onPanUpdate,
      onPanEnd: (details) => _points.add(null),
      child: CustomPaint(
        painter: SignaturePainter(_points),
        size: size.infinite,
      ),
    );
  }
}
class SignaturePainter extends CustomPainter {
  const SignaturePainter(this.points);
  final List<Offset?> points;
  @override
  void paint(Canvas canvas, size size) {
    final paint paint = paint()
      ..color = colors.black
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i]!, points[i + 1]!, paint);
      }
    }
  }
  @override
  bool shouldRepaint(SignaturePainter oldDelegate) =>
      oldDelegate.points != points;
}
<code_end>
<topic_end>
<topic_start>
where is the widget’s opacity?
on Xamarin.Forms, all VisualElements have an opacity.
in flutter, you need to wrap a widget in an
opacity widget to accomplish this.
<topic_end>
<topic_start>
how do i build custom widgets?
in Xamarin.Forms, you typically subclass VisualElement,
or use a pre-existing VisualElement, to override and
implement methods that achieve the desired behavior.
in flutter, build a custom widget by composing
smaller widgets (instead of extending them).
it is somewhat similar to implementing a custom control
based off a grid with numerous VisualElements added in,
while extending with custom logic.
for example, how do you build a CustomButton
that takes a label in the constructor?
create a CustomButton that composes a ElevatedButton
with a label, rather than by extending ElevatedButton:
<code_start>
class CustomButton extends StatelessWidget {
  const CustomButton(this.label, {super.key});
  final string label;
  @override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: text(label),
    );
  }
}
<code_end>
then use CustomButton, just as you’d use any other flutter widget:
<code_start>
@override
widget build(BuildContext context) {
  return const center(
    child: CustomButton('Hello'),
  );
}
<code_end>
<topic_end>
<topic_start>
navigation
<topic_end>
<topic_start>
how do i navigate between pages?
in Xamarin.Forms, the NavigationPage class
provides a hierarchical navigation experience
where the user is able to navigate through pages,
forwards and backwards.
flutter has a similar implementation,
using a navigator and routes.
a route is an abstraction for a page of an app,
and a navigator is a widget that manages routes.
a route roughly maps to a page.
the navigator works in a similar way to the Xamarin.Forms NavigationPage,
in that it can push() and pop() routes depending on
whether you want to navigate to, or back from, a view.
to navigate between pages, you have a couple options:
the following example builds a map.
<code_start>
void main() {
  runApp(
    MaterialApp(
      home: const MyAppHome(), // becomes the route named '/'
      routes: <string, WidgetBuilder>{
        '/a': (context) => const MyPage(title: 'page a'),
        '/b': (context) => const MyPage(title: 'page b'),
        '/c': (context) => const MyPage(title: 'page c'),
      },
    ),
  );
}
<code_end>
navigate to a route by pushing its name to the navigator.
<code_start>
Navigator.of(context).pushNamed('/b');
<code_end>
the navigator is a stack that manages your app’s routes.
pushing a route to the stack moves to that route.
popping a route from the stack, returns to the previous route.
this is done by awaiting on the future returned by push().
async/await is very similar to the .net implementation
and is explained in more detail in async UI.
for example, to start a location route
that lets the user select their location,
you might do the following:
<code_start>
object? coordinates = await Navigator.of(context).pushNamed('/location');
<code_end>
and then, inside your ‘location’ route, once the user has selected their
location, pop the stack with the result:
<code_start>
navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392});
<code_end>
<topic_end>
<topic_start>
how do i navigate to another app?
in Xamarin.Forms, to send the user to another application,
you use a specific URI scheme, using Device.OpenUrl("mailto://").
to implement this functionality in flutter,
create a native platform integration, or use an existing plugin,
such asurl_launcher, available with many other packages on pub.dev.
<topic_end>
<topic_start>
async UI
<topic_end>
<topic_start>
what is the equivalent of Device.BeginOnMainThread() in flutter?
dart has a single-threaded execution model,
with support for isolates (a way to run dart codes on another thread),
an event loop, and asynchronous programming.
unless you spawn an isolate,
your dart code runs in the main UI thread
and is driven by an event loop.
dart’s single-threaded model doesn’t mean you need to run everything
as a blocking operation that causes the UI to freeze.
much like Xamarin.Forms, you need to keep the UI thread free.
you would use async/await to perform tasks,
where you must wait for the response.
in flutter, use the asynchronous facilities that the dart language provides,
also named async/await, to perform asynchronous work.
this is very similar to c# and should be very easy to use
for any Xamarin.Forms developer.
for example, you can run network code without causing the UI to hang by
using async/await and letting dart do the heavy lifting:
<code_start>
future<void> loadData() async {
  final uri dataURL = uri.parse(
    'https://jsonplaceholder.typicode.com/posts',
  );
  final http.Response response = await http.get(dataURL);
  setState(() {
    data = jsonDecode(response.body);
  });
}
<code_end>
once the awaited network call is done,
update the UI by calling setState(),
which triggers a rebuild of the widget subtree and updates the data.
the following example loads data asynchronously
and displays it in a ListView:
<code_start>
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Map<String, dynamic>> data = <map<string, dynamic>>[];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  future<void> loadData() async {
    final uri dataURL = uri.parse(
      'https://jsonplaceholder.typicode.com/posts',
    );
    final http.Response response = await http.get(dataURL);
    setState(() {
      data = jsonDecode(response.body);
    });
  }
  widget getRow(int index) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text('Row ${data[index]['title']}'),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: ListView.builder(
        itemCount: data.length,
        itemBuilder: (context, index) {
          return getRow(index);
        },
      ),
    );
  }
}
<code_end>
refer to the next section for more information
on doing work in the background,
and how flutter differs from android.
<topic_end>
<topic_start>
how do you move work to a background thread?
since flutter is single threaded and runs an event loop,
you don’t have to worry about thread management
or spawning background threads.
this is very similar to Xamarin.Forms.
if you’re doing I/O-bound work, such as disk access or a network call,
then you can safely use async/await and you’re all set.
if, on the other hand, you need to do computationally intensive work
that keeps the CPU busy,
you want to move it to an isolate to avoid blocking the event loop,
like you would keep any sort of work out of the main thread.
this is similar to when you move things to a different
thread via Task.Run() in Xamarin.Forms.
for I/O-bound work, declare the function as an async function,
and await on long-running tasks inside the function:
<code_start>
future<void> loadData() async {
  final uri dataURL = uri.parse(
    'https://jsonplaceholder.typicode.com/posts',
  );
  final http.Response response = await http.get(dataURL);
  setState(() {
    data = jsonDecode(response.body);
  });
}
<code_end>
this is how you would typically do network or database calls,
which are both I/O operations.
however, there are times when you might be processing
a large amount of data and your UI hangs.
in flutter, use isolates to take advantage of multiple CPU cores
to do long-running or computationally intensive tasks.
isolates are separate execution threads that
do not share any memory with the main execution memory heap.
this is a difference between Task.Run().
this means you can’t access variables from the main thread,
or update your UI by calling setState().
the following example shows, in a simple isolate,
how to share data back to the main thread to update the UI.
<code_start>
future<void> loadData() async {
  final ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(dataLoader, receivePort.sendPort);
  // the 'echo' isolate sends its SendPort as the first message
  final SendPort sendPort = await receivePort.first as SendPort;
  final List<Map<String, dynamic>> msg = await sendReceive(
    sendPort,
    'https://jsonplaceholder.typicode.com/posts',
  );
  setState(() {
    data = msg;
  });
}
// the entry point for the isolate
static future<void> dataLoader(SendPort sendPort) async {
  // open the ReceivePort for incoming messages.
  final ReceivePort port = ReceivePort();
  // notify any other isolates what port this isolate listens to.
  sendPort.send(port.sendPort);
  await for (final dynamic msg in port) {
    final string url = msg[0] as string;
    final SendPort replyTo = msg[1] as SendPort;
    final uri dataURL = uri.parse(url);
    final http.Response response = await http.get(dataURL);
    // lots of JSON to parse
    replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>);
  }
}
Future<List<Map<String, dynamic>>> sendReceive(SendPort port, string msg) {
  final ReceivePort response = ReceivePort();
  port.send(<dynamic>[msg, response.sendPort]);
  return response.first as Future<List<Map<String, dynamic>>>;
}
<code_end>
here, dataLoader() is the isolate that runs in
its own separate execution thread.
in the isolate, you can perform more CPU intensive
processing (parsing a big JSON, for example),
or perform computationally intensive math,
such as encryption or signal processing.
you can run the full example below:
<code_start>
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Map<String, dynamic>> data = <map<string, dynamic>>[];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  bool get showLoadingDialog => data.isEmpty;
  future<void> loadData() async {
    final ReceivePort receivePort = ReceivePort();
    await Isolate.spawn(dataLoader, receivePort.sendPort);
    // the 'echo' isolate sends its SendPort as the first message
    final SendPort sendPort = await receivePort.first as SendPort;
    final List<Map<String, dynamic>> msg = await sendReceive(
      sendPort,
      'https://jsonplaceholder.typicode.com/posts',
    );
    setState(() {
      data = msg;
    });
  }
  // the entry point for the isolate
  static future<void> dataLoader(SendPort sendPort) async {
    // open the ReceivePort for incoming messages.
    final ReceivePort port = ReceivePort();
    // notify any other isolates what port this isolate listens to.
    sendPort.send(port.sendPort);
    await for (final dynamic msg in port) {
      final string url = msg[0] as string;
      final SendPort replyTo = msg[1] as SendPort;
      final uri dataURL = uri.parse(url);
      final http.Response response = await http.get(dataURL);
      // lots of JSON to parse
      replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>);
    }
  }
  Future<List<Map<String, dynamic>>> sendReceive(SendPort port, string msg) {
    final ReceivePort response = ReceivePort();
    port.send(<dynamic>[msg, response.sendPort]);
    return response.first as Future<List<Map<String, dynamic>>>;
  }
  widget getBody() {
    if (showloadingdialog) {
      return getProgressDialog();
    }
    return getListView();
  }
  widget getProgressDialog() {
    return const center(child: CircularProgressIndicator());
  }
  ListView getListView() {
    return ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index) {
        return getRow(index);
      },
    );
  }
  widget getRow(int index) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text('Row ${data[index]['title']}'),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: getBody(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i make network requests?
in Xamarin.Forms you would use HttpClient.
making a network call in flutter is easy
when you use the popular http package.
this abstracts away a lot of the networking
that you might normally implement yourself,
making it simple to make network calls.
to use the http package, add it to your dependencies in pubspec.yaml:
to make a network request,
call await on the async function http.get():
<code_start>
future<void> loadData() async {
  final uri dataURL = uri.parse(
    'https://jsonplaceholder.typicode.com/posts',
  );
  final http.Response response = await http.get(dataURL);
  setState(() {
    data = jsonDecode(response.body);
  });
}
<code_end>
<topic_end>
<topic_start>
how do i show the progress for a long-running task?
in Xamarin.Forms you would typically create a loading indicator,
either directly in XAML or through a 3rd party plugin such as AcrDialogs.
in flutter, use a ProgressIndicator widget.
show the progress programmatically by controlling
when it’s rendered through a boolean flag.
tell flutter to update its state before your long-running task starts,
and hide it after it ends.
in the example below, the build function is separated into three different
functions. if showLoadingDialog is true
(when widgets.length == 0), then render the ProgressIndicator.
otherwise, render the ListView with the data returned from a network call.
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Map<String, dynamic>> data = <map<string, dynamic>>[];
  @override
  void initState() {
    super.initState();
    loadData();
  }
  bool get showLoadingDialog => data.isEmpty;
  future<void> loadData() async {
    final uri dataURL = uri.parse(
      'https://jsonplaceholder.typicode.com/posts',
    );
    final http.Response response = await http.get(dataURL);
    setState(() {
      data = jsonDecode(response.body);
    });
  }
  widget getBody() {
    if (showloadingdialog) {
      return getProgressDialog();
    }
    return getListView();
  }
  widget getProgressDialog() {
    return const center(child: CircularProgressIndicator());
  }
  ListView getListView() {
    return ListView.builder(
      itemCount: data.length,
      itemBuilder: (context, index) {
        return getRow(index);
      },
    );
  }
  widget getRow(int index) {
    return padding(
      padding: const EdgeInsets.all(10),
      child: Text('Row ${data[index]['title']}'),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: getBody(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
project structure & resources
<topic_end>
<topic_start>
where do i store my image files?
Xamarin.Forms has no platform independent way of storing images,
you had to place images in the iOS xcasset folder,
or on android in the various drawable folders.
while android and iOS treat resources and assets as distinct items,
flutter apps have only assets.
all resources that would live in the
resources/drawable-* folders on android,
are placed in an assets’ folder for flutter.
flutter follows a simple density-based format like iOS.
assets might be 1.0x, 2.0x, 3.0x, or any other multiplier.
flutter doesn’t have dps but there are logical pixels,
which are basically the same as device-independent pixels.
flutter’s devicePixelRatio expresses the ratio
of physical pixels in a single logical pixel.
the equivalent to android’s density buckets are:
assets are located in any arbitrary folder—
flutter has no predefined folder structure.
you declare the assets (with location)
in the pubspec.yaml file, and flutter picks them up.
to add a new image asset called my_icon.png to our flutter project,
for example, and deciding that it should live in a folder we
arbitrarily called images, you would put the base image (1.0x)
in the images folder, and all the other variants in sub-folders
called with the appropriate ratio multiplier:
next, you’ll need to declare these images in your pubspec.yaml file:
you can directly access your images in an image.asset widget:
<code_start>
@override
widget build(BuildContext context) {
  return image.asset('images/my_icon.png');
}
<code_end>
or using AssetImage:
<code_start>
@override
widget build(BuildContext context) {
  return const image(
    image: AssetImage('images/my_image.png'),
  );
}
<code_end>
more detailed information can be found in adding assets and images.
<topic_end>
<topic_start>
where do i store strings? how do i handle localization?
unlike .net which has resx files,
flutter doesn’t currently have a dedicated system for handling strings.
at the moment, the best practice is to declare your copy text
in a class as static fields and access them from there. for example:
<code_start>
class strings {
  static const string welcomeMessage = 'welcome to flutter';
}
<code_end>
you can access your strings as such:
<code_start>
Text(Strings.welcomeMessage);
<code_end>
by default, flutter only supports US english for its strings.
if you need to add support for other languages,
include the flutter_localizations package.
you might also need to add dart’s intl
package to use i10n machinery, such as date/time formatting.
to use the flutter_localizations package,
specify the localizationsDelegates and
supportedLocales on the app widget:
<code_start>
import 'package:flutter_localizations/flutter_localizations.dart';
class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      localizationsDelegates: <localizationsdelegate<dynamic>>[
        // add app-specific localization delegate[s] here
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: <locale>[
        locale('en', 'us'), // english
        locale('he', 'il'), // hebrew
        // ... other locales the app supports
      ],
    );
  }
}
<code_end>
the delegates contain the actual localized values,
while the supportedLocales defines which locales the app supports.
the above example uses a MaterialApp,
so it has both a GlobalWidgetsLocalizations
for the base widgets localized values,
and a MaterialWidgetsLocalizations for the material widgets localizations.
if you use WidgetsApp for your app, you don’t need the latter.
note that these two delegates contain “default” values,
but you’ll need to provide one or more delegates
for your own app’s localizable copy,
if you want those to be localized too.
when initialized, the WidgetsApp (or MaterialApp)
creates a localizations widget for you,
with the delegates you specify.
the current locale for the device is always accessible
from the localizations widget from the current context
(in the form of a locale object), or using the window.locale.
to access localized resources, use the localizations.of() method
to access a specific localizations class that is provided by a given delegate.
use the intl_translation package to extract translatable copy
to arb files for translating, and importing them back into the app
for using them with intl.
for further details on internationalization and localization in flutter,
see the internationalization guide, which has sample code
with and without the intl package.
<topic_end>
<topic_start>
where is my project file?
in Xamarin.Forms you will have a csproj file.
the closest equivalent in flutter is pubspec.yaml,
which contains package dependencies and various project details.
similar to .net standard,
files within the same directory are considered part of the project.
<topic_end>
<topic_start>
what is the equivalent of nuget? how do i add dependencies?
in the .net ecosystem, native xamarin projects and Xamarin.Forms projects
had access to nuget and the built-in package management system.
flutter apps contain a native android app, native iOS app and flutter app.
in android, you add dependencies by adding to your gradle build script.
in iOS, you add dependencies by adding to your podfile.
flutter uses dart’s own build system, and the pub package manager.
the tools delegate the building of the native android and iOS wrapper apps
to the respective build systems.
in general, use pubspec.yaml to declare
external dependencies to use in flutter.
a good place to find flutter packages is on pub.dev.
<topic_end>
<topic_start>
application lifecycle
<topic_end>
<topic_start>
how do i listen to application lifecycle events?
in Xamarin.Forms, you have an application
that contains OnStart, OnResume and OnSleep.
in flutter, you can instead listen to similar lifecycle events
by hooking into the WidgetsBinding observer and listening to
the didChangeAppLifecycleState() change event.
the observable lifecycle events are:
for more details on the meaning of these states,
see the AppLifecycleStatus documentation.
<topic_end>
<topic_start>
layouts
<topic_end>
<topic_start>
what is the equivalent of a StackLayout?
in Xamarin.Forms you can create a StackLayout
with an orientation of horizontal or vertical.
flutter has a similar approach,
however you would use the row or column widgets.
if you notice the two code samples are identical
except the row and column widget.
the children are the same and this feature
can be exploited to develop rich layouts
that can change overtime with the same children.
<code_start>
@override
widget build(BuildContext context) {
  return const row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <widget>[
      Text('Row one'),
      Text('Row two'),
      Text('Row three'),
      Text('Row four'),
    ],
  );
}
<code_end>
<code_start>
@override
widget build(BuildContext context) {
  return const column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <widget>[
      Text('Column one'),
      Text('Column two'),
      Text('Column three'),
      Text('Column four'),
    ],
  );
<code_end>
<topic_end>
<topic_start>
what is the equivalent of a grid?
the closest equivalent of a grid would be a GridView.
this is much more powerful than what you are used to in Xamarin.Forms.
a GridView provides automatic scrolling when the
content exceeds its viewable space.
<code_start>
@override
widget build(BuildContext context) {
  return GridView.count(
    // create a grid with 2 columns. if you change the scrollDirection to
    // horizontal, this would produce 2 rows.
    crossAxisCount: 2,
    // generate 100 widgets that display their index in the list.
    children: List<Widget>.generate(
      100,
      (index) {
        return center(
          child: text(
            'item $index',
            style: Theme.of(context).textTheme.headlineMedium,
          ),
        );
      },
    ),
  );
}
<code_end>
you might have used a grid in Xamarin.Forms
to implement widgets that overlay other widgets.
in flutter, you accomplish this with the stack widget.
this sample creates two icons that overlap each other.
<code_start>
@override
widget build(BuildContext context) {
  return const stack(
    children: <widget>[
      icon(
        icons.add_box,
        size: 24,
        color: colors.black,
      ),
      positioned(
        left: 10,
        child: icon(
          icons.add_circle,
          size: 24,
          color: colors.black,
        ),
      ),
    ],
  );
}
<code_end>
<topic_end>
<topic_start>
what is the equivalent of a ScrollView?
in Xamarin.Forms, a ScrollView wraps around a VisualElement,
and if the content is larger than the device screen, it scrolls.
in flutter, the closest match is the SingleChildScrollView widget.
you simply fill the widget with the content that you want to be scrollable.
<code_start>
@override
widget build(BuildContext context) {
  return const SingleChildScrollView(
    child: Text('Long content'),
  );
}
<code_end>
if you have many items you want to wrap in a scroll,
even of different widget types, you might want to use a ListView.
this might seem like overkill, but in flutter this is
far more optimized and less intensive than a Xamarin.Forms ListView,
which is backing on to platform specific controls.
<code_start>
@override
widget build(BuildContext context) {
  return ListView(
    children: const <widget>[
      Text('Row one'),
      Text('Row two'),
      Text('Row three'),
      Text('Row four'),
    ],
  );
}
<code_end>
<topic_end>
<topic_start>
how do i handle landscape transitions in flutter?
landscape transitions can be handled automatically by setting the
configChanges property in the AndroidManifest.xml:
<topic_end>
<topic_start>
gesture detection and touch event handling
<topic_end>
<topic_start>
how do i add GestureRecognizers to a widget in flutter?
in Xamarin.Forms, elements might contain a click event you can attach to.
many elements also contain a command that is tied to this event.
alternatively you would use the TapGestureRecognizer.
in flutter there are two very similar ways:
if the widget supports event detection, pass a function to it and
handle it in the function. for example, the ElevatedButton has an
onPressed parameter:
<code_start>
@override
widget build(BuildContext context) {
  return ElevatedButton(
    onPressed: () {
      developer.log('click');
    },
    child: const Text('Button'),
  );
}
<code_end>
if the widget doesn’t support event detection, wrap the
widget in a GestureDetector and pass a function
to the onTap parameter.
<code_start>
class SampleApp extends StatelessWidget {
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: GestureDetector(
          onTap: () {
            developer.log('tap');
          },
          child: const FlutterLogo(size: 200),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i handle other gestures on widgets?
in Xamarin.Forms you would add a GestureRecognizer to the view.
you would normally be limited to TapGestureRecognizer,
PinchGestureRecognizer, PanGestureRecognizer, SwipeGestureRecognizer,
DragGestureRecognizer and DropGestureRecognizer unless you built your own.
in flutter, using the GestureDetector,
you can listen to a wide range of gestures such as:
the following example shows a GestureDetector
that rotates the flutter logo on a double tap:
<code_start>
class RotatingFlutterDetector extends StatefulWidget {
  const RotatingFlutterDetector({super.key});
  @override
  State<RotatingFlutterDetector> createState() =>
      _RotatingFlutterDetectorState();
}
class _RotatingFlutterDetectorState extends State<RotatingFlutterDetector>
    with SingleTickerProviderStateMixin {
  late final AnimationController controller;
  late final CurvedAnimation curve;
  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const duration(milliseconds: 2000),
      vsync: this,
    );
    curve = CurvedAnimation(parent: controller, curve: Curves.easeIn);
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: center(
        child: GestureDetector(
          onDoubleTap: () {
            if (controller.iscompleted) {
              controller.reverse();
            } else {
              controller.forward();
            }
          },
          child: RotationTransition(
            turns: curve,
            child: const FlutterLogo(size: 200),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
listviews and adapters
<topic_end>
<topic_start>
what is the equivalent to a ListView in flutter?
the equivalent to a ListView in flutter is … a ListView!
in a Xamarin.Forms ListView, you create a ViewCell
and possibly a DataTemplateSelectorand pass it into the ListView,
which renders each row with what your
DataTemplateSelector or ViewCell returns.
however, you often have to make sure you turn on cell recycling
otherwise you will run into memory issues and slow scrolling speeds.
due to flutter’s immutable widget pattern,
you pass a list of widgets to your ListView,
and flutter takes care of making sure that scrolling is fast and smooth.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatelessWidget {
  const SampleAppPage({super.key});
  List<Widget> _getListData() {
    return List<Widget>.generate(
      100,
      (index) => padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $index'),
      ),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: ListView(children: _getListData()),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i know which list item has been clicked?
in Xamarin.Forms, the ListView has an ItemTapped method
to find out which item was clicked.
there are many other techniques you might have used
such as checking when SelectedItem or EventToCommand
behaviors change.
in flutter, use the touch handling provided by the passed-in widgets.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  // this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> _getListData() {
    return List<Widget>.generate(
      100,
      (index) => GestureDetector(
        onTap: () {
          developer.log('Row $index tapped');
        },
        child: padding(
          padding: const EdgeInsets.all(10),
          child: Text('Row $index'),
        ),
      ),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: ListView(children: _getListData()),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
how do i update a ListView dynamically?
in Xamarin.Forms, if you bound the
ItemsSource property to an ObservableCollection,
you would just update the list in your ViewModel.
alternatively, you could assign a new list to the ItemSource property.
in flutter, things work a little differently.
if you update the list of widgets inside a setState() method,
you would quickly see that your data did not change visually.
this is because when setState() is called,
the flutter rendering engine looks at the widget tree
to see if anything has changed.
when it gets to your ListView, it performs a == check,
and determines that the two ListViews are the same.
nothing has changed, so no update is required.
for a simple way to update your ListView,
create a new list inside of setState(),
and copy the data from the old list to the new list.
while this approach is simple, it is not recommended for large data sets,
as shown in the next example.
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> widgets = <widget>[];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 100; i++) {
      widgets.add(getRow(i));
    }
  }
  widget getRow(int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widgets = List<Widget>.from(widgets);
          widgets.add(getRow(widgets.length));
          developer.log('Row $index');
        });
      },
      child: padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $index'),
      ),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: ListView(children: widgets),
    );
  }
}
<code_end>
the recommended, efficient, and effective way to build a list
uses a ListView.Builder.
this method is great when you have a dynamic list
or a list with very large amounts of data.
this is essentially the equivalent of RecyclerView on android,
which automatically recycles list elements for you:
<code_start>
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  List<Widget> widgets = [];
  @override
  void initState() {
    super.initState();
    for (int i = 0; i < 100; i++) {
      widgets.add(getRow(i));
    }
  }
  widget getRow(int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widgets.add(getRow(widgets.length));
          developer.log('Row $index');
        });
      },
      child: padding(
        padding: const EdgeInsets.all(10),
        child: Text('Row $index'),
      ),
    );
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: ListView.builder(
        itemCount: widgets.length,
        itemBuilder: (context, index) {
          return getRow(index);
        },
      ),
    );
  }
}
<code_end>
instead of creating a ListView, create a ListView.builder
that takes two key parameters: the initial length of the list,
and an item builder function.
the item builder function is similar to the getView function
in an android adapter; it takes a position,
and returns the row you want rendered at that position.
finally, but most importantly, notice that the onTap() function
doesn’t recreate the list anymore, but instead adds to it.
for more information, see
your first flutter app codelab.
<topic_end>
<topic_start>
working with text
<topic_end>
<topic_start>
how do i set custom fonts on my text widgets?
in Xamarin.Forms, you would have to add a custom font in each native project.
then, in your element you would assign this font name
to the FontFamily attribute using filename#fontname
and just fontname for iOS.
in flutter, place the font file in a folder and reference it
in the pubspec.yaml file, similar to how you import images.
then assign the font to your text widget:
<code_start>
@override
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(title: const Text('Sample app')),
    body: const center(
      child: text(
        'this is a custom font text',
        style: TextStyle(fontFamily: 'mycustomfont'),
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
how do i style my text widgets?
along with fonts, you can customize other styling elements on a text widget.
the style parameter of a text widget takes a TextStyle object,
where you can customize many parameters, such as:
<topic_end>
<topic_start>
form input
<topic_end>
<topic_start>
how do i retrieve user input?
Xamarin.Forms elements allow you to directly query the element
to determine the state of its properties,
or whether it’s bound to a property in a ViewModel.
retrieving information in flutter is handled by specialized widgets
and is different from how you are used to.
if you have a TextFieldor a TextFormField,
you can supply a TextEditingController
to retrieve user input:
<code_start>
import 'package:flutter/material.dart';
class MyForm extends StatefulWidget {
  const MyForm({super.key});
  @override
  State<MyForm> createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
  /// create a text controller and use it to retrieve the current value
  /// of the TextField.
  final TextEditingController myController = TextEditingController();
  @override
  void dispose() {
    // clean up the controller when disposing of the widget.
    myController.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Retrieve text input')),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: TextField(controller: myController),
      ),
      floatingActionButton: FloatingActionButton(
        // when the user presses the button, show an alert dialog with the
        // text that the user has typed into our text field.
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // retrieve the text that the user has entered using the
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'show me the value!',
        child: const Icon(Icons.text_fields),
      ),
    );
  }
}
<code_end>
you can find more information and the full code listing in
retrieve the value of a text field,
from the flutter cookbook.
<topic_end>
<topic_start>
what is the equivalent of a placeholder on an entry?
in Xamarin.Forms, some elements support a placeholder property
that you can assign a value to. for example:
in flutter, you can easily show a “hint” or a placeholder text
for your input by adding an InputDecoration object
to the decoration constructor parameter for the text widget.
<code_start>
TextField(
  decoration: InputDecoration(hintText: 'this is a hint'),
),
<code_end>
<topic_end>
<topic_start>
how do i show validation errors?
with Xamarin.Forms, if you wished to provide a visual hint of a
validation error, you would need to create new properties and
VisualElements surrounding the elements that had validation errors.
in flutter, you pass through an InputDecoration object to the
decoration constructor for the text widget.
however, you don’t want to start off by showing an error.
instead, when the user has entered invalid data,
update the state, and pass a new InputDecoration object.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'sample app',
      home: SampleAppPage(),
    );
  }
}
class SampleAppPage extends StatefulWidget {
  const SampleAppPage({super.key});
  @override
  State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
  string? _errorText;
  string? _getErrorText() {
    return _errorText;
  }
  bool isEmail(String em) {
    const string emailRegexp =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|'
        r'(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|'
        r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    final RegExp regExp = RegExp(emailRegexp);
    return regExp.hasMatch(em);
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Sample app')),
      body: center(
        child: TextField(
          onSubmitted: (text) {
            setState(() {
              if (!isemail(text)) {
                _errorText = 'error: this is not an email';
              } else {
                _errorText = null;
              }
            });
          },
          decoration: InputDecoration(
            hintText: 'this is a hint',
            errorText: _getErrorText(),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
flutter plugins
<topic_end>
<topic_start>
interacting with hardware, third party services, and the platform
<topic_end>
<topic_start>
how do i interact with the platform, and with platform native code?
flutter doesn’t run code directly on the underlying platform;
rather, the dart code that makes up a flutter app is run natively
on the device, “sidestepping” the SDK provided by the platform.
that means, for example, when you perform a network request in dart,
it runs directly in the dart context.
you don’t use the android or iOS APIs
you normally take advantage of when writing native apps.
your flutter app is still hosted in a native app’s
ViewController or activity as a view,
but you don’t have direct access to this, or the native framework.
this doesn’t mean flutter apps can’t interact with those native APIs,
or with any native code you have. flutter provides platform channels
that communicate and exchange data with the
ViewController or activity that hosts your flutter view.
platform channels are essentially an asynchronous messaging mechanism
that bridges the dart code with the host ViewController
or activity and the iOS or android framework it runs on.
you can use platform channels to execute a method on the native side,
or to retrieve some data from the device’s sensors, for example.
in addition to directly using platform channels,
you can use a variety of pre-made plugins
that encapsulate the native and dart code for a specific goal.
for example, you can use a plugin to access
the camera roll and the device camera directly from flutter,
without having to write your own integration.
plugins are found on pub.dev,
dart and flutter’s open source package repository.
some packages might support native integrations on iOS,
or android, or both.
if you can’t find a plugin on pub.dev that fits your needs,
you can write your own, and publish it on pub.dev.
<topic_end>
<topic_start>
how do i access the GPS sensor?
use the geolocator community plugin.
<topic_end>
<topic_start>
how do i access the camera?
the camera plugin is popular for accessing the camera.
<topic_end>
<topic_start>
how do i log in with facebook?
to log in with facebook, use the
flutter_facebook_login community plugin.
<topic_end>
<topic_start>
how do i use firebase features?
most firebase functions are covered by first party plugins.
these plugins are first-party integrations, maintained by the flutter team:
you can also find some third-party firebase plugins on pub.dev
that cover areas not directly covered by the first-party plugins.
<topic_end>
<topic_start>
how do i build my own custom native integrations?
if there is platform-specific functionality that flutter
or its community plugins are missing,
you can build your own following the
developing packages and plugins page.
flutter’s plugin architecture, in a nutshell,
is much like using an event bus in android:
you fire off a message and let the receiver process and emit a result
back to you. in this case, the receiver is code running on the native side
on android or iOS.
<topic_end>
<topic_start>
themes (styles)
<topic_end>
<topic_start>
how do i theme my app?
flutter comes with a beautiful, built-in implementation of material design,
which handles much of the styling and theming needs
that you would typically do.
Xamarin.Forms does have a global ResourceDictionary
where you can share styles across your app.
alternatively, there is theme support currently in preview.
in flutter, you declare themes in the top level widget.
to take full advantage of material components in your app,
you can declare a top level widget MaterialApp
as the entry point to your application.
MaterialApp is a convenience widget
that wraps a number of widgets that are commonly required
for applications implementing material design.
it builds upon a WidgetsApp by adding material-specific functionality.
you can also use a WidgetsApp as your app widget,
which provides some of the same functionality,
but is not as rich as MaterialApp.
to customize the colors and styles of any child components,
pass a ThemeData object to the MaterialApp widget.
for example, in the following code,
the color scheme from seed is set to deepPurple and text selection color is red.
<code_start>
class SampleApp extends StatelessWidget {
  /// this widget is the root of your application.
  const SampleApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'sample app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        textSelectionTheme:
            const TextSelectionThemeData(selectionColor: colors.red),
      ),
      home: const SampleAppPage(),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
databases and local storage
<topic_end>
<topic_start>
how do i access shared preferences or UserDefaults?
Xamarin.Forms developers will likely be familiar with the
Xam.Plugins.Settings plugin.
in flutter, access equivalent functionality using the
shared_preferences plugin. this plugin wraps the
functionality of both UserDefaults and the android
equivalent, SharedPreferences.
<topic_end>
<topic_start>
how do i access SQLite in flutter?
in Xamarin.Forms most applications would use the sqlite-net-pcl
plugin to access SQLite databases.
in flutter, on macOS, android, and iOS,
access this functionality using the
sqflite plugin.
<topic_end>
<topic_start>
debugging
<topic_end>
<topic_start>
what tools can i use to debug my app in flutter?
use the DevTools suite for debugging flutter or dart apps.
DevTools includes support for profiling, examining the heap,
inspecting the widget tree, logging diagnostics, debugging,
observing executed lines of code,
debugging memory leaks and memory fragmentation.
for more information, see the DevTools documentation.
<topic_end>
<topic_start>
notifications
<topic_end>
<topic_start>
how do i set up push notifications?
in android, you use firebase cloud messaging to set up
push notifications for your app.
in flutter, access this functionality using the
firebase_messaging plugin.
for more information on using the firebase cloud messaging API, see the
firebase_messaging plugin documentation.
<topic_end>
<topic_start>
introduction to declarative UI
this introduction describes the conceptual difference between the
declarative style used by flutter, and the imperative style used by
many other UI frameworks.
<topic_end>
<topic_start>
why a declarative UI?
frameworks from win32 to web to android and iOS typically use an imperative
style of UI programming. this might be the style you’re most familiar
with—where you manually construct a full-functioned UI entity,
such as a UIView or equivalent, and later mutate it using methods and
setters when the UI changes.
in order to lighten the burden on developers from having to program how to
transition between various UI states, flutter, by contrast,
lets the developer describe the current UI state and leaves the
transitioning to the framework.
this, however, requires a slight shift in thinking for how to manipulate UI.
<topic_end>
<topic_start>
how to change UI in a declarative framework
consider a simplified example below:
in the imperative style, you would typically go to ViewB’s owner
and retrieve the instance b using selectors or with findViewById or similar,
and invoke mutations on it (and implicitly invalidate it). for example:
you might also need to replicate this configuration in the constructor of
ViewB since the source of truth for the UI might outlive instance b itself.
in the declarative style, view configurations (such as flutter’s widgets)
are immutable and are only lightweight “blueprints”. to change the UI,
a widget triggers a rebuild on itself (most commonly by calling setState()
on StatefulWidgets in flutter) and constructs a new widget subtree.
<code_start>
// declarative style
return ViewB(
  color: red,
  child: const ViewC(),
);
<code_end>
here, rather than mutating an old instance b when the UI changes,
flutter constructs new widget instances. the framework manages many of the
responsibilities of a traditional UI object (such as maintaining the
state of the layout) behind the scenes with RenderObjects.
RenderObjects persist between frames and flutter’s lightweight widgets
tell the framework to mutate the RenderObjects between states.
the flutter framework handles the rest.
<topic_end>
<topic_start>
flutter concurrency for swift developers
both dart and swift support concurrent programming. 
this guide should help you understand how
concurrency works in dart and how it compares to swift.
with this understanding, you can create
high-performing iOS apps.
when developing in the apple ecosystem, 
some tasks might take a long time to complete. 
these tasks include fetching or processing large amounts of data.
iOS developers typically use grand central dispatch (gcd)
to schedule tasks using a shared thread pool.
with GCD, developers add tasks to dispatch queues
and GCD decides on which thread to execute them.
but, GCD spins up threads to 
handle remaining work items.
this means you can end up with a large number of threads 
and the system can become over committed.
with swift, the structured concurrency model reduced the number 
of threads and context switches. 
now, each core has only one thread.
dart has a single-threaded execution model, 
with support for isolates, an event loop, and asynchronous code. 
an isolate is dart’s implementation of a lightweight thread.
unless you spawn an isolate, your dart code runs in the 
main UI thread driven by an event loop. 
flutter’s event loop is 
equivalent to the iOS main loop—in other words, 
the looper attached to the main thread.
dart’s single-threaded model doesn’t mean 
you are required to run everything 
as a blocking operation that causes the UI to freeze. 
instead, use the asynchronous 
features that the dart language provides, 
such as async/await.
<topic_end>
<topic_start>
asynchronous programming
an asynchronous operation allows other operations 
to execute before it completes. 
both dart and swift support asynchronous functions 
using the async and await keywords. 
in both cases, async marks that a function 
performs asynchronous work, 
and await tells the system to await a result 
from function. this means that the dart VM could 
suspend the function, if necessary. 
for more details on asynchronous programming, check out
concurrency in dart.
<topic_end>
<topic_start>
leveraging the main thread/isolate
for apple operating systems, the primary (also called the main) 
thread is where the application begins running. 
rendering the user interface always happens on the main thread. 
one difference between swift and dart is that
swift might use different threads for different tasks, 
and swift doesn’t guarantee which thread is used. 
so, when dispatching UI updates in swift, 
you might need to ensure that the work occurs on the main thread.
say you want to write a function that fetches the 
weather asynchronously and 
displays the results.
in GCD, to manually dispatch a process to the main thread, 
you might do something like the following.
first, define the weather enum:
next, define the view model and mark it as an ObservableObject 
so that it can return a value of type weather?. 
use GCD create to a DispatchQueue to 
send the work to the pool of threads
finally, display the results:
more recently, swift introduced actors to support 
synchronization for shared, mutable state. 
to ensure that work is performed on the main thread,
define a view model class that is marked as a @mainactor, 
with a load() function that internally calls an 
asynchronous function using task.
next, define the view model as a state object using @stateobject, 
with a load() function that can be called by the view model:
in dart, all work runs on the main isolate by default. 
to implement the same example in dart, 
first, create the weather enum:
<code_start>
enum weather {
  rainy,
  windy,
  sunny,
}
<code_end>
then, define a simple view model (similar to what was created in SwiftUI), 
to fetch the weather. in dart, a future object represents a value to be
provided in the future. a future is similar to swift’s ObservableObject. 
in this example, a function within the view model
returns a Future<Weather> object:
<code_start>
@immutable
class HomePageViewModel {
  const HomePageViewModel();
  Future<Weather> load() async {
    await future.delayed(const duration(seconds: 1));
    return weather.sunny;
  }
}
<code_end>
the load() function in this example shares 
similarities with the swift code. 
the dart function is marked as async because
it uses the await keyword.
additionally, a dart function marked as async
automatically returns a future.
in other words, you don’t have to create a 
future instance manually 
inside functions marked as async.
for the last step, display the weather value. 
in flutter, FutureBuilder and 
StreamBuilder
widgets are used to display the results of a future in the UI. 
the following example uses a FutureBuilder:
<code_start>
class HomePage extends StatelessWidget {
  const HomePage({super.key});
  final HomePageViewModel viewModel = const HomePageViewModel();
  @override
  widget build(BuildContext context) {
    return CupertinoPageScaffold(
      // feed a FutureBuilder to your widget tree.
      child: FutureBuilder<Weather>(
        // specify the future that you want to track.
        future: viewModel.load(),
        builder: (context, snapshot) {
          // a snapshot is of type `asyncsnapshot` and contains the
          // state of the future. by looking if the snapshot contains
          // an error or if the data is null, you can decide what to
          // show to the user.
          if (snapshot.hasdata) {
            return center(
              child: text(
                snapshot.data.toString(),
              ),
            );
          } else {
            return const center(
              child: CupertinoActivityIndicator(),
            );
          }
        },
      ),
    );
  }
}
<code_end>
for the complete example, check out the
async_weather file on GitHub.
<topic_end>
<topic_start>
leveraging a background thread/isolate
flutter apps can run on a variety of multi-core hardware, 
including devices running macOS and iOS. 
to improve the performance of these applications, 
you must sometimes run tasks on different cores
concurrently. this is especially important 
to avoid blocking UI rendering with long-running operations.
in swift, you can leverage GCD to run tasks on global queues
with different quality of service class (qos) properties. 
this indicates the task’s priority.
in dart, you can offload computation to a worker isolate, 
often called a background worker. 
a common scenario spawns a simple worker isolate and 
returns the results in a message when the worker exits. 
as of dart 2.19, you can use isolate.run() to 
spawn an isolate and run computations:
in flutter, you can also use the compute function 
to spin up an isolate to run a callback function:
in this case, the callback function is a top-level
function as shown below:
you can find more information on dart at
learning dart as a swift developer,
and more information on flutter at
flutter for SwiftUI developers or
flutter for UIKit developers.
<topic_end>
<topic_start>
upgrading flutter
no matter which one of the flutter release channels
you follow, you can use the flutter command to upgrade your
flutter SDK or the packages that your app depends on.
<topic_end>
<topic_start>
upgrading the flutter SDK
to update the flutter SDK use the flutter upgrade command:
this command gets the most recent version of the flutter SDK
that’s available on your current flutter channel.
if you are using the stable channel
and want an even more recent version of the flutter SDK,
switch to the beta channel using flutter channel beta,
and then run flutter upgrade.
<topic_end>
<topic_start>
keeping informed
we publish migration guides for known breaking changes.
we send announcements regarding these changes to the
flutter announcements mailing list.
to avoid being broken by future versions of flutter,
consider submitting your tests to our test registry.
<topic_end>
<topic_start>
switching flutter channels
flutter has two release channels:
stable and beta.
<topic_end>
<topic_start>
the stable channel
we recommend the stable channel for new users
and for production app releases.
the team updates this channel about every three months.
the channel might receive occasional hot fixes
for high-severity or high-impact issues.
the continuous integration for the flutter team’s plugins and packages
includes testing against the latest stable release.
the latest documentation for the stable branch
is at: https://api.flutter.dev
<topic_end>
<topic_start>
the beta channel
the beta channel has the latest stable release.
this is the most recent version of flutter that we have heavily tested.
this channel has passed all our public testing,
has been verified against test suites for google products that use flutter,
and has been vetted against contributed private test suites.
the beta channel receives regular hot fixes
to address newly discovered important issues.
the beta channel is essentially the same as the stable channel
but updated monthly instead of quarterly.
indeed, when the stable channel is updated,
it is updated to the latest beta release.
<topic_end>
<topic_start>
other channels
we currently have one other channel, master.
people who contribute to flutter use this channel.
this channel is not as thoroughly tested as
the beta and stable channels.
we do not recommend using this channel as
it is more likely to contain serious regressions.
the latest documentation for the master branch
is at: https://main-api.flutter.dev
<topic_end>
<topic_start>
changing channels
to view your current channel, use the following command:
to change to another channel, use flutter channel <channel-name>.
once you’ve changed your channel, use flutter upgrade
to download the latest flutter SDK and dependent packages for that channel.
for example:
info note
  if you need a specific version of the flutter SDK,
  you can download it from the flutter SDK archive.
<topic_end>
<topic_start>
upgrading packages
if you’ve modified your pubspec.yaml file, or you want to update
only the packages that your app depends upon
(instead of both the packages and flutter itself),
then use one of the flutter pub commands.
to update to the latest compatible versions of
all the dependencies listed in the pubspec.yaml file,
use the upgrade command:
to update to the latest possible version of
all the dependencies listed in the pubspec.yaml file,
use the upgrade --major-versions command:
this also automatically update the constraints
in the pubspec.yaml file.
to identify out-of-date package dependencies and get advice
on how to update them, use the outdated command. for details, see
the dart pub outdated documentation.
<topic_end>
<topic_start>
flutter SDK archive
the stable channel contains the
most stable flutter builds.
to learn more, check out flutter’s channels.
error important
  if you develop apps in china, check out using flutter in china.
to learn what’s new in the major flutter releases,
check out the release notes page.
a note on provenance: provenance
  describes how software artifacts are built, including
  what the download contains and who created it.
  to view provenance in a more readable format
  and where nothing is downloaded, run the following
  command using the provenance file URL from a release (you might need to 
  download jq to easily parse the JSON).
<topic_end>
<topic_start>
stable channel (windows)
select from the following scrollable list:
<topic_end>
<topic_start>
beta channel (windows)
select from the following scrollable list:
<topic_end>
<topic_start>
stable channel (macos)
select from the following scrollable list:
<topic_end>
<topic_start>
beta channel (macos)
select from the following scrollable list:
<topic_end>
<topic_start>
stable channel (linux)
select from the following scrollable list:
<topic_end>
<topic_start>
beta channel (linux)
select from the following scrollable list:
<topic_end>
<topic_start>
master channel
installation bundles are not available for master.
however, you can get the SDK directly from
GitHub repo by cloning the master channel,
and then triggering a download of the SDK dependencies:
for additional details on how our installation bundles are structured,
see installation bundles.
<topic_end>
<topic_start>
what's new
this page contains current and recent announcements
of what’s new on the flutter website and blog.
find past what’s new information on the
what’s new archive page.
you might also check out the
flutter SDK release notes.
to stay on top of flutter announcements including
breaking changes,
join the flutter-announce google group.
for dart, you can join the dart announce google group,
and review the dart changelog.
<topic_end>
<topic_start>
15 february 2024: Valentine’s-Day-adjacent 3.19 release
flutter 3.19 is live! for more information,
check out the flutter 3.19 umbrella blog post
and the flutter 3.19 technical blog post.
you might also check out the dart 3.3 release blog post.
docs updated or added since the 3.16 release
other updates
for past releases, check out the
what’s new archive page.
<topic_end>
<topic_start>
flutter release notes
this page links to announcements and release notes for
releases to the stable channel.
info note
  for information about bug-fix releases, check out
  hotfixes to the stable channel on the flutter wiki.
<topic_end>
<topic_start>
breaking changes and migration guides
as described in the breaking change policy,
on occasion we publish guides
for migrating code across a breaking change.
to be notified about future breaking changes,
join the groups flutter announce and dart announce.
when facing dart errors after upgrading flutter,
consider using the dart fix command
to automatically migrate your code.
not every breaking change is supported in this way,
but many are.
to avoid being broken by future versions of flutter,
consider submitting your tests to our test registry.
the following guides are available. they are sorted by
release, and listed in alphabetical order:
<topic_end>
<topic_start>
not yet released to stable
<topic_end>
<topic_start>
released in flutter 3.19
<topic_end>
<topic_start>
released in flutter 3.16
<topic_end>
<topic_start>
released in flutter 3.13
<topic_end>
<topic_start>
released in flutter 3.10
<topic_end>
<topic_start>
released in flutter 3.7
<topic_end>
<topic_start>
released in flutter 3.3
<topic_end>
<topic_start>
released in flutter 3
<topic_end>
<topic_start>
released in flutter 2.10
<topic_end>
<topic_start>
released in flutter 2.5
<topic_end>
<topic_start>
reverted change in 2.2
the following breaking change was reverted in release 2.2:
<topic_end>
<topic_start>
released in flutter 2.2
<topic_end>
<topic_start>
released in flutter 2
<topic_end>
<topic_start>
released in flutter 1.22
<topic_end>
<topic_start>
released in flutter 1.20
<topic_end>
<topic_start>
released in flutter 1.17
<topic_end>
<topic_start>
flutter compatibility policy
the flutter team tries to balance the need for API stability with the
need to keep evolving APIs to fix bugs, improve API ergonomics,
and provide new features in a coherent manner.
to this end, we have created a test registry where you can provide
unit tests for your own applications or libraries that we run
on every change to help us track changes that would break
existing applications. our commitment is that we won’t make any
changes that break these tests without working with the developers of
those tests to (a) determine if the change is sufficiently valuable,
and (b) provide fixes for the code so that the tests continue to pass.
if you would like to provide tests as part of this program, please
submit a PR to the flutter/tests repository. 
the README on that repository describes 
the process in detail.
<topic_end>
<topic_start>
announcements and migration guides
if we do make a breaking change (defined as a change that caused one
or more of these submitted tests to require changes), we will announce
the change on our flutter-announce
mailing list as well as in our release notes.
we provide a list of guides for migrating code affected by
breaking changes.
<topic_end>
<topic_start>
deprecation policy
we will, on occasion, deprecate certain APIs rather than outright
break them overnight. this is independent of our compatibility policy
which is exclusively based on whether submitted tests fail, as
described above.
deprecated APIs are removed after a migration grace period. this grace
period is one calendar year after being released on the stable channel,
or after 4 stable releases, whichever is longer.
when a deprecation does reach end of life, we follow the same procedures
listed above for making breaking changes in removing the deprecated API.
<topic_end>
<topic_start>
dart and other libraries used by flutter
the dart language itself has a separate breaking-change policy,
with announcements on dart announce.
in general, the flutter team doesn’t currently have any commitment
regarding breaking changes for other dependencies.
for example, it’s possible that a new version of
flutter using a new version of skia
(the graphics engine used by some platforms on flutter)
or harfbuzz (the font shaping engine used by flutter)
would have changes that affect contributed tests.
such changes wouldn’t necessarily be accompanied by a
migration guide.
<topic_end>
<topic_start>
codelabs
the flutter codelabs provide a guided,
hands-on coding experience. some codelabs
run in DartPad—no downloads required!
<topic_end>
<topic_start>
good for beginners
if you’re new to flutter, we recommend starting with
one of the following codelabs:
building your first flutter app (workshop)
an instructor-led version of our very popular
“write your first flutter app” codelab
(listed below).
your first flutter app
create a simple app that automatically generates cool-sounding names,
such as “newstay”, “lightstream”, “mainbrake”, or “graypine”.
this app is responsive and runs on mobile, desktop, and web.
(this also replaces the previous “write your first flutter app”
for mobile, part 1 and part 2 codelabs.)
write your first flutter app on the web
implement a simple web app in DartPad (no downloads
required!) that displays a sign-in screen
containing three text fields. as the user fills out the
fields, a progress bar animates along the top of the
sign-in area. this codelab is written specifically for
the web, but if you have downloaded and configured
android and iOS tooling, the completed app
works on android and iOS devices, as well.
<topic_end>
<topic_start>
next steps
records and patterns in dart 3
discover dart 3’s new records and patterns features.
learn how you can use them in a flutter app to help you
write more readable and maintainable dart code.
building scrolling experiences in flutter (workshop)
start with an app that performs simple, straightforward scrolling
and enhance it to create fancy and custom scrolling effects
by using slivers.
dart null safety in action (workshop)
an instructor-led workshop introducing the features
that enable dart’s null-safe type system.
how to manage application states using inherited widgets (workshop)
learn how to manage the state of your app’s data by
using the InheritedWidget class, one of the
low-level state management classes provided
by flutter.
<topic_end>
<topic_start>
designing a flutter UI
learn about material design and basic flutter concepts,
like layout and animations:
how to debug layout issues with the flutter inspector
not an official codelab, but step-by-step instructions on
how to debug common layout problems using the flutter
inspector and layout explorer.
implicit animations
use DartPad (no downloads required!) to learn how to use
implicit animations to add motion and create
visual effects for the widgets in your UI.
building beautiful transitions with material motion for flutter
learn how to use the material animations package to
add pre-built transitions to a material app called reply.
take your flutter app from boring to beautiful
learn how to use some of the features in material 3
to make your app more beautiful and more responsive.
MDC-101 flutter: material components (mdc) basics
learn the basics of using material components by building
a simple app with core components.  the four MDC codelabs
guide you through building an e-commerce app called shrine.
you’ll start by building a login page using several of MDC
flutter’s components.
MDC-102 flutter: material structure and layout
learn how to use material for structure and layout in flutter.
continue building the e-commerce app, introduced in MDC-101,
by adding navigation, structure, and data.
MDC-103 flutter: material theming with color, shape, elevation, and type
discover how material components for flutter make it
easy to differentiate your product, and express your
brand through design. continue building your e-commerce
app by adding a home screen that displays products.
MDC-104 flutter: material advanced components
improve your design and learn to use our advanced
component backdrop menu. finish your e-commerce app
by adding a backdrop with a menu that filters
products by the selected category.
adaptive apps in flutter
learn how to build a flutter app that adapts to the
platform that it’s running on, be that android, iOS,
the web, windows, macOS, or linux.
building next generation UIs in flutter
learn how to build a flutter app that uses the power of flutter_animate,
fragment shaders, and particle fields. you will craft a user interface that
evokes those science fiction movies and TV shows we all love
watching when we aren’t coding.
<topic_end>
<topic_start>
using flutter with
learn how to use flutter with other technologies.
<topic_end>
<topic_start>
monetizing flutter
adding AdMob ads to a flutter app
learn how to add an AdMob banner, an interstitial ad,
and a rewarded ad to an app called awesome drawing quiz,
a game that lets players guess the name of the drawing.
adding an AdMob banner and native inline ads to a flutter app
learn how to implement inline banner and native ads
to a travel booking app that lists possible
flight destinations.
adding in-app purchases to your flutter app
extend a simple gaming app that uses the dash mascot as
currency to offer three types of in-app purchases:
consumable, non-consumable, and subscription.
<topic_end>
<topic_start>
flutter and firebase
add a user authentication flow to a flutter app using FirebaseUI
learn how to add firebase authentication to a flutter app
with only a few lines of code.
get to know firebase for flutter (workshop)
an instructor-led version of our popular
“get to know firebase for flutter” codelab
(listed below).
get to know firebase for flutter
build an event RSVP and guestbook chat app on both android
and iOS using flutter, authenticating users with firebase
authentication, and sync data using cloud firestore.
local development for your flutter apps using the firebase emulator suite
learn how to use the firebase emulator suite when
developing with flutter. you will also learn to use
the auth and firestore emulators.
<topic_end>
<topic_start>
flutter and TensorFlow
create a custom text-classification model with TensorFlow lite model maker
create a flutter app to classify texts with TensorFlow
learn how to run a text-classification inference from a flutter
app with TensorFlow serving through REST and gRPC.
train a comment-spam detection model with TensorFlow lite model maker
learn how to install the TensorFlow lite model maker with colab,
how to use a data loader, and how to build a model.
<topic_end>
<topic_start>
flutter and other technologies
adding google maps to a flutter app
display a google map in an app, retrieve data from a
web service, and display the data as markers on the map.
adding WebView to your flutter app
with the WebView flutter plugin you can add a WebView
widget to your android or iOS flutter app.
build voice bots for mobile with dialogflow and flutter (workshop)
an instructor-led version of the dialogflow
and flutter codelab (listed below).
build voice bots for android with dialogflow and flutter
learn how to build a mobile FAQ bot that can answer most
common questions about the tool dialogflow. end users
can interact with the text interface or stream a voice
interaction via the built-in microphone of a mobile device.
introduction to flame with flutter
build a breakout clone using the flame 2d game engine and
embed it in a flutter wrapper. you will use flame’s effects
to animate and remove components, along with the google_fonts and
flutter_animate packages, to make the whole game look well designed.
using FFI in a flutter plugin
learn how to use dart’s FFI (foreign function interface)
library, ffigen, allowing you to leverage
existing native libraries that provide a
c interface.
create haikus about google products with the PaLM API and flutter
learn how to build an app that uses the PaLM API to
generate haikus based on google product names. the
PaLM API gives you access to google’s
state-of-the-art large language models.
<topic_end>
<topic_start>
testing
learn how to test your flutter application.
<topic_end>
<topic_start>
writing platform-specific code
learn how to write code that’s targeted for specific platforms,
like iOS, android, desktop, or the web.
how to write a flutter plugin
learn how to write a plugin by creating a music plugin
for iOS and android that processes audio on the host platform.
then make an example app that uses your plugin to make a music keyboard.
using a plugin with a flutter web app
finish an app that reports the number of stars on a GitHub repository.
use dart DevTools to do some simple debugging, and
host your app on firebase and, finally, use a flutter plugin to
launch the app and open the hosted privacy policy.
write a flutter desktop application
build a flutter desktop app (windows, linux, or macOS)
that accesses GitHub APIs to retrieve your repositories,
assigned issues, and pull requests. as part of this task,
create and use plugins to interact with native APIs and desktop applications,
and use code generation to build type-safe client libraries for GitHub’s APIs.
adding a home screen widget to your flutter app NEW
learn how to add a home screen widget to your flutter app
on iOS. this applies to your home screen, lock screen, or the
today view.
<topic_end>
<topic_start>
other resources
for dart-specific codelabs, see the
codelabs page on the dart site.
we also recommend the following online class:
info note
  if you have trouble viewing any of the codelabs
  on codelabs.developers.google.com, try
  this mirror of the flutter codelabs.
<topic_end>
<topic_start>
cookbook
this cookbook contains recipes that demonstrate how to solve common problems 
while writing flutter apps. each recipe is self-contained and can be used as a
reference to help you build up an application.
<topic_end>
<topic_start>
animation
<topic_end>
<topic_start>
design
<topic_end>
<topic_start>
effects
<topic_end>
<topic_start>
forms
<topic_end>
<topic_start>
games
<topic_end>
<topic_start>
gestures
<topic_end>
<topic_start>
images
<topic_end>
<topic_start>
lists
<topic_end>
<topic_start>
maintenance
<topic_end>
<topic_start>
navigation
<topic_end>
<topic_start>
networking
<topic_end>
<topic_start>
persistence
<topic_end>
<topic_start>
plugins
<topic_end>
<topic_start>
testing
<topic_end>
<topic_start>
integration
<topic_end>
<topic_start>
unit
<topic_end>
<topic_start>
widget
<topic_end>
<topic_start>
casual games toolkit
the flutter casual games toolkit pulls together new and existing resources
so you can accelerate development of games on mobile platforms.
this page outlines where you can find these available resources.
<topic_end>
<topic_start>
why flutter for games?
the flutter framework can create performant apps for six target platforms
from the desktop to mobile devices to the web.
with flutter’s benefits of cross-platform development, performance, and
open source licensing, it makes a great choice for games.
casual games fall into two categories: turn-based games
and real-time games.
you might be familiar with both types of games,
though perhaps you didn’t think about them in quite this way.
turn-based games cover games meant for a mass market with
simple rules and gameplay.
this includes board games, card games, puzzles, and strategy games.
these games respond to simple user input,
like tapping on a card or entering a number or letter.
these games are well suited for flutter.
real-time games cover games a series of actions require real time responses.
these include endless runner games, racing games, and so on.
you might want to create a game with advanced features like collision detection,
camera views, game loops, and the like.
these types of games could use an open source game engine like the
flame game engine built using flutter.
<topic_end>
<topic_start>
what’s included in the toolkit
the casual games toolkit provides the following free resources.
a repository that includes three new game templates that provide
a starting point for building a casual game.
a base game template
that includes the basics for:
a card game template
that includes everything in the base template plus:
an endless runner template created in partnership
with the open source game engine, flame. it implements:
a sample game built on top of the endless runner template,
called SuperDash. you can play the game on iOS, android,
or web, view the open source code repo, or 
read how the game was created in 6 weeks.
the included game templates and cookbook recipes make certain choices
to accelerate development.
they include specific packages, like provider, google_mobile_ads,
in_app_purchase, audioplayers, crashlytics, and games_services.
if you prefer other packages, you can change the code to use them.
the flutter team understands that monetization might be a future consideration.
cookbook recipes for advertising and in-app purchases have been added.
as explained on the games page,
you can leverage up to $900 in offers when you integrate google services,
such as cloud, firebase, and ads, into your game.
error important
terms and conditions apply.
  you must connect your firebase and GCP accounts to use credits for
  firebase services and verify your business email during sign up to earn
  an additional $100 on top of the normal $300 credit.
  for the ads offer, check your region’s eligibility.
<topic_end>
<topic_start>
get started
are you ready? to get started:
review the README file for the first type of game you want to create.
review the codelabs and cookbook recipes.
<topic_end>
<topic_start>
example games
for google I/O 2022, both the flutter team and very good ventures created new
games.
VGV created the I/O pinball game using the flame engine.
to learn about this game,
check out I/O pinball powered by flutter and firebase on medium
and play the game in your browser.
the flutter team created I/O flip, a virtual CCG.
to learn more about I/O flip,
check out how it’s made: I/O FLIP adds a twist to a classic card game with generative AI
on the google developers blog and play the game in your browser.
<topic_end>
<topic_start>
other resources
once you feel ready to go beyond these games templates,
investigate other resources that our community recommended.
package_2 flutter package
api API documentation
science codelab 
book_5 cookbook recipe
handyman desktop application
photo_album game assets
quick_reference_all guide
book_5 special effects
handyman spriter pro
package_2 rive
package_2 spriteWidget
package_2 app_review
package_2 audioplayers
science user authentication using firebase
science add firebase to your flutter game
quick_reference_all firebase crashlytics overview
package_2 firebase_crashlytics
package_2 win32_gamepad
photo_album CraftPix
photo_album game developer studio
handyman GIMP
package_2 flame
package_2 bonfire
package_2 forge2d
book_5 add achievements and leaderboards to your game
book_5 add multiplayer support to your game
package_2 games_services
science use the foreign function interface in a flutter plugin
handyman tiled
book_5 add advertising to your flutter game
science add AdMob ads to a flutter app
science add in-app purchases to your flutter app
quick_reference_all gaming UX and revenue optimizations for apps (pdf)
package_2 shared_preferences
package_2 sqflite
package_2 cbl_flutter (couchbase lite)
api paint API
book_5 special effects
science build next generation UIs in flutter
<topic_end>
<topic_start>
add achievements and leaderboards to your mobile game
gamers have various motivations for playing games.
in broad strokes, there are four major motivations: 
immersion, achievement, cooperation, and competition.
no matter the game you build, some players want to achieve in it.
this could be trophies won or secrets unlocked.
some players want to compete in it.
this could be hitting high scores or accomplishing speedruns.
these two ideas map to the concepts of achievements and leaderboards.
ecosystems such as the app store and google play provide
centralized services for achievements and leaderboards.
players can view achievements from all their games in one place and
developers don’t need to re-implement them for every game.
this recipe demonstrates how to use the games_services package 
to add achievements and leaderboard functionality to your mobile game.
<topic_end>
<topic_start>
1. enable platform services
to enable games services, set up game center on iOS and
google play games services on android.
<topic_end>
<topic_start>
iOS
to enable game center (gamekit) on iOS:
open your flutter project in xcode.
open ios/Runner.xcworkspace
select the root runner project.
go to the signing & capabilities tab.
click the + button to add game center as a capability.
close xcode.
if you haven’t already,
register your game in app store connect
and from the my app section press the + icon.
still in app store connect, look for the game center section. you
can find it in services as of this writing. on the game
center page, you might want to set up a leaderboard and several
achievements, depending on your game. take note of the IDs of the
leaderboards and achievements you create.
<topic_end>
<topic_start>
android
to enable play games services on android:
if you haven’t already, go to google play console
and register your game there.
still in google play console, select play games services → setup
and management → configuration from the navigation menu and
follow their instructions.
this takes a significant amount of time and patience.
among other things, you’ll need to set up an
OAuth consent screen in google cloud console.
if at any point you feel lost, consult the
official play games services guide.
when done, you can start adding leaderboards and achievements in
play games services → setup and management. create the exact
same set as you did on the iOS side. make note of IDs.
go to play games services → setup and management → publishing.
click publish. don’t worry, this doesn’t actually publish your
game. it only publishes the achievements and leaderboard. once a
leaderboard, for example, is published this way, it cannot be
unpublished.
go to play games services → setup and management →
configuration → credentials.
find the get resources button.
it returns an XML file with the play games services IDs.
add a file at android/app/src/main/res/values/games-ids.xml
containing the XML you received in the previous step.
<topic_end>
<topic_start>
2. sign in to the game service
now that you have set up game center and play games services, and
have your achievement & leaderboard IDs ready, it’s finally dart time.
add a dependency on the games_services package.
before you can do anything else, you have to sign the player into
the game service.
<code_start>
try {
  await GamesServices.signIn();
} on PlatformException catch (e) {
  // ... deal with failures ...
}
<code_end>
the sign in happens in the background. it takes several seconds, so
don’t call signIn() before runApp() or the players will be forced to
stare at a blank screen every time they start your game.
the API calls to the games_services API can fail for a multitude of
reasons. therefore, every call should be wrapped in a try-catch block as
in the previous example. the rest of this recipe omits exception
handling for clarity.
lightbulb tip
  it’s a good practice to create a controller. this would be a
  ChangeNotifier, a bloc, or some other piece of logic that wraps around
  the raw functionality of the games_services plugin.
<topic_end>
<topic_start>
3. unlock achievements
register achievements in google play console and app store connect,
and take note of their IDs. now you can award any of those
achievements from your dart code:
<code_start>
await GamesServices.unlock(
  achievement: achievement(
    androidID: 'your android id',
    iOSID: 'your ios id',
  ),
);
<code_end>
the player’s account on google play games or apple game center now
lists the achievement.
to display the achievements UI from your game, call the
games_services API:
<code_start>
await GamesServices.showAchievements();
<code_end>
this displays the platform achievements UI as an overlay on your game.
to display the achievements in your own UI, use
GamesServices.loadAchievements().
<topic_end>
<topic_start>
4. submit scores
when the player finishes a play-through, your game can submit the result
of that play session into one or more leaderboards.
for example, a platformer game like super mario can submit both the
final score and the time taken to complete the level, to two separate
leaderboards.
in the first step, you registered a leaderboard in google play
console and app store connect, and took note of its ID. using this
ID, you can submit new scores for the player:
<code_start>
await GamesServices.submitScore(
  score: score(
    iOSLeaderboardID: 'some_id_from_app_store',
    androidLeaderboardID: 'some_id_from_gplay',
    value: 100,
  ),
);
<code_end>
you don’t need to check whether the new score is the player’s
highest. the platform game services handle that for you.
to display the leaderboard as an overlay over your game, make the
following call:
<code_start>
await GamesServices.showLeaderboards(
  iOSLeaderboardID: 'some_id_from_app_store',
  androidLeaderboardID: 'some_id_from_gplay',
);
<code_end>
if you want to display the leaderboard scores in your own UI, you
can fetch them with GamesServices.loadLeaderboardScores().
<topic_end>
<topic_start>
5. next steps
there’s more to the games_services plugin. with this plugin, you can:
some achievements can be incremental. for example: “you have collected
all 10 pieces of the McGuffin.”
each game has different needs from game services.
to start, you might want to create this controller 
in order to keep all achievements & leaderboards logic in one place:
<code_start>
import 'dart:async';
import 'package:games_services/games_services.dart';
import 'package:logging/logging.dart';
/// allows awarding achievements and leaderboard scores,
/// and also showing the platforms' UI overlays for achievements
/// and leaderboards.
///
/// a facade of `package:games_services`.
class GamesServicesController {
  static final logger _log = Logger('GamesServicesController');
  final completer<bool> _signedInCompleter = completer();
  future<bool> get signedIn => _signedInCompleter.future;
  /// unlocks an achievement on game center / play games.
  ///
  /// you must provide the achievement ids via the [ios] and [android]
  /// parameters.
  ///
  /// does nothing when the game isn't signed into the underlying
  /// games service.
  future<void> awardAchievement(
      {required string iOS, required string android}) async {
    if (!await signedIn) {
      _log.warning('Trying to award achievement when not logged in.');
      return;
    }
    try {
      await GamesServices.unlock(
        achievement: achievement(
          androidID: android,
          iOSID: iOS,
        ),
      );
    } catch (e) {
      _log.severe('Cannot award achievement: $e');
    }
  }
  /// signs into the underlying games service.
  future<void> initialize() async {
    try {
      await GamesServices.signIn();
      // the API is unclear so we're checking to be sure. the above call
      // returns a string, not a boolean, and there's no documentation
      // as to whether every non-error result means we're safely signed in.
      final signedIn = await GamesServices.isSignedIn;
      _signedInCompleter.complete(signedIn);
    } catch (e) {
      _log.severe('Cannot log into GamesServices: $e');
      _signedInCompleter.complete(false);
    }
  }
  /// launches the platform's UI overlay with achievements.
  future<void> showAchievements() async {
    if (!await signedIn) {
      _log.severe('Trying to show achievements when not logged in.');
      return;
    }
    try {
      await GamesServices.showAchievements();
    } catch (e) {
      _log.severe('Cannot show achievements: $e');
    }
  }
  /// launches the platform's UI overlay with leaderboard(s).
  future<void> showLeaderboard() async {
    if (!await signedIn) {
      _log.severe('Trying to show leaderboard when not logged in.');
      return;
    }
    try {
      await GamesServices.showLeaderboards(
        // TODO: when ready, change both these leaderboard IDs.
        iOSLeaderboardID: 'some_id_from_app_store',
        androidLeaderboardID: 'some_id_from_gplay',
      );
    } catch (e) {
      _log.severe('Cannot show leaderboard: $e');
    }
  }
  /// submits [score] to the leaderboard.
  future<void> submitLeaderboardScore(int score) async {
    if (!await signedIn) {
      _log.warning('Trying to submit leaderboard when not logged in.');
      return;
    }
    _log.info('Submitting $score to leaderboard.');
    try {
      await GamesServices.submitScore(
        score: score(
          // TODO: when ready, change these leaderboard IDs.
          iOSLeaderboardID: 'some_id_from_app_store',
          androidLeaderboardID: 'some_id_from_gplay',
          value: score,
        ),
      );
    } catch (e) {
      _log.severe('Cannot submit leaderboard score: $e');
    }
  }
}
<code_end>
<topic_end>
<topic_start>
more information
the flutter casual games toolkit includes the following templates:
<topic_end>
<topic_start>
add ads to your mobile flutter app or game
many developers use advertising to monetize their mobile apps and games.
this allows their app to be downloaded free of charge, 
which improves the app’s popularity.
to add ads to your flutter project, use
AdMob, 
google’s mobile advertising platform.
this recipe demonstrates how to use the
google_mobile_ads
package to add a banner ad to your app or game.
info note
  apart from AdMob, the google_mobile_ads package also supports
  ad manager, a platform intended for large publishers. integrating ad
  manager resembles integrating AdMob, but it won’t be covered in this
  cookbook recipe. to use ad manager, follow the
  ad manager documentation.
<topic_end>
<topic_start>
1. get AdMob app IDs
go to AdMob and set up an
account. this could take some time because you need to provide
banking information, sign contracts, and so on.
with the AdMob account ready, create two apps in AdMob: one for
android and one for iOS.
open the app settings section.
get the AdMob app IDs for both the android app and the iOS app.
they resemble ca-app-pub-1234567890123456~1234567890. note the
tilde (~) between the two numbers.
<topic_end>
<topic_start>
2. platform-specific setup
update your android and iOS configurations to include your app IDs.
<topic_end>
<topic_start>
android
add your AdMob app ID to your android app.
open the app’s android/app/src/main/AndroidManifest.xml file.
add a new <meta-data> tag.
set the android:name element with a value of
com.google.android.gms.ads.APPLICATION_ID.
set the android:value element with the value to your own AdMob app
ID that you got in the previous step. 
include them in quotes as shown:
<topic_end>
<topic_start>
iOS
add your AdMob app ID to your iOS app.
open your app’s ios/Runner/Info.plist file.
enclose GADApplicationIdentifier with a key tag.
enclose your AdMob app ID with a string tag. you created this AdMob
app ID in step 1.
<topic_end>
<topic_start>
3. add the google_mobile_ads plugin
to add the google_mobile_ads plugin as a dependency, run
flutter pub add:
info note
  once you add the plugin, your android app might fail to build with a
  DexArchiveMergerException:
to resolve this, execute the flutter run command in the terminal, not
  through an IDE plugin. the flutter tool can detect the issue and ask
  whether it should try to solve it. answer y, and the problem goes away.
  you can return to running your app from an IDE after that.
<topic_end>
<topic_start>
4. initialize the mobile ads SDK
you need to initialize the mobile ads SDK before loading ads.
call MobileAds.instance.initialize() to initialize the mobile ads
SDK.
<code_start>
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  unawaited(MobileAds.instance.initialize());
  runApp(MyApp());
}
<code_end>
run the initialization step at startup, as shown above, 
so that the AdMob SDK has enough time to initialize before it is needed.
info note
MobileAds.instance.initialize() returns a future but, the
  way the SDK is built, you don’t need to await it.
  if you try to load an ad before that future is completed, 
  the SDK will gracefully wait until the initialization, and then load the ad.
  you can await the future
  if you want to know the exact time when the AdMob SDK is ready.
<topic_end>
<topic_start>
5. load a banner ad
to show an ad, you need to request it from AdMob.
to load a banner ad, construct a BannerAd instance, and
call load() on it.
info note
  the following code snippet refers to fields such a adSize, adUnitId
  and _bannerAd. this will all make more sense in a later step.
<code_start>
/// loads a banner ad.
void _loadAd() {
  final bannerAd = BannerAd(
    size: widget.adSize,
    adUnitId: widget.adUnitId,
    request: const AdRequest(),
    listener: BannerAdListener(
      // called when an ad is successfully received.
      onAdLoaded: (ad) {
        if (!mounted) {
          ad.dispose();
          return;
        }
        setState(() {
          _bannerAd = ad as BannerAd;
        });
      },
      // called when an ad request failed.
      onAdFailedToLoad: (ad, error) {
        debugPrint('BannerAd failed to load: $error');
        ad.dispose();
      },
    ),
  );
  // start loading.
  bannerAd.load();
}
<code_end>
to view a complete example, check out the last step of this recipe.
<topic_end>
<topic_start>
6. show banner ad
once you have a loaded instance of BannerAd, use AdWidget to show it.
it’s a good idea to wrap the widget in a SafeArea (so that no part of
the ad is obstructed by device notches) and a SizedBox (so that it has
its specified, constant size before and after loading).
<code_start>
@override
widget build(BuildContext context) {
  return SafeArea(
    child: SizedBox(
      width: widget.adSize.width.toDouble(),
      height: widget.adSize.height.toDouble(),
      child: _bannerAd == null
          // nothing to render yet.
          ? SizedBox()
          // the actual ad.
          : AdWidget(ad: _bannerAd!),
    ),
  );
}
<code_end>
you must dispose of an ad when you no longer need to access it. the best
practice for when to call dispose() is either after the AdWidget is
removed from the widget tree or in the
BannerAdListener.onAdFailedToLoad() callback.
<code_start>
_bannerAd?.dispose();
<code_end>
<topic_end>
<topic_start>
7. configure ads
to show anything beyond test ads, you have to register ad units.
open AdMob.
create an ad unit for each of the AdMob apps.
this asks for the ad unit’s format. AdMob provides many formats
beyond banner ads — interstitials, rewarded ads, app open ads, and
so on. 
the API for those is similar, and documented in the 
AdMob documentation
and through 
official samples.
choose banner ads.
get the ad unit IDs for both the android app and the iOS app.
you can find these in the ad units section. they look something
like ca-app-pub-1234567890123456/1234567890. the format resembles
the app ID but with a slash (/) between the two numbers. this
distinguishes an ad unit ID from an app ID.
add these ad unit IDs to the constructor of BannerAd,
depending on the target app platform.
<code_start>
final string adUnitId = Platform.isAndroid
    // use this ad unit on android...
    ? 'ca-app-pub-3940256099942544/6300978111'
    // ... or this one on iOS.
    : 'ca-app-pub-3940256099942544/2934735716';
<code_end>
<topic_end>
<topic_start>
8. final touches
to display the ads in a published app or game (as opposed to debug or
testing scenarios), your app must meet additional requirements:
your app must be reviewed and approved before it can fully serve
ads.
follow AdMob’s app readiness guidelines.
for example, your app must be listed on at least one of the
supported stores such as google play store or apple app store.
you must create an app-ads.txt
file and publish it on your developer website.
to learn more about app and game monetization, 
visit the official sites
of AdMob
and ad manager.
<topic_end>
<topic_start>
9. complete example
the following code implements a simple stateful widget that loads a
banner ad and shows it.
<code_start>
import 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class MyBannerAdWidget extends StatefulWidget {
  /// the requested size of the banner. defaults to [adsize.banner].
  final AdSize adSize;
  /// the AdMob ad unit to show.
  ///
  /// TODO: replace this test ad unit with your own ad unit
  final string adUnitId = Platform.isAndroid
      // use this ad unit on android...
      ? 'ca-app-pub-3940256099942544/6300978111'
      // ... or this one on iOS.
      : 'ca-app-pub-3940256099942544/2934735716';
  MyBannerAdWidget({
    super.key,
    this.adSize = AdSize.banner,
  });
  @override
  State<MyBannerAdWidget> createState() => _MyBannerAdWidgetState();
}
class _MyBannerAdWidgetState extends State<MyBannerAdWidget> {
  /// the banner ad to show. this is `null` until the ad is actually loaded.
  BannerAd? _bannerAd;
  @override
  widget build(BuildContext context) {
    return SafeArea(
      child: SizedBox(
        width: widget.adSize.width.toDouble(),
        height: widget.adSize.height.toDouble(),
        child: _bannerAd == null
            // nothing to render yet.
            ? SizedBox()
            // the actual ad.
            : AdWidget(ad: _bannerAd!),
      ),
    );
  }
  @override
  void initState() {
    super.initState();
    _loadAd();
  }
  @override
  void dispose() {
    _bannerAd?.dispose();
    super.dispose();
  }
  /// loads a banner ad.
  void _loadAd() {
    final bannerAd = BannerAd(
      size: widget.adSize,
      adUnitId: widget.adUnitId,
      request: const AdRequest(),
      listener: BannerAdListener(
        // called when an ad is successfully received.
        onAdLoaded: (ad) {
          if (!mounted) {
            ad.dispose();
            return;
          }
          setState(() {
            _bannerAd = ad as BannerAd;
          });
        },
        // called when an ad request failed.
        onAdFailedToLoad: (ad, error) {
          debugPrint('BannerAd failed to load: $error');
          ad.dispose();
        },
      ),
    );
    // start loading.
    bannerAd.load();
  }
}
<code_end>
lightbulb tip
  in many cases, you will want to load the ad outside a widget.
for example, you can load it in a ChangeNotifier, a BLoC, a controller,
  or whatever else you are using for app-level state. this way, you can
  preload a banner ad in advance, and have it ready to show for when the
  user navigates to a new screen.
verify that you have loaded the BannerAd instance before showing it with
  an AdWidget, and that you dispose of the instance when it is no longer
  needed.
<topic_end>
<topic_start>
add multiplayer support using firestore
multiplayer games need a way to synchronize game states between players.
broadly speaking, two types of multiplayer games exist:
high tick rate.
these games need to synchronize game states many times per second
with low latency.
these would include action games, sports games, fighting games.
low tick rate.
these games only need to synchronize game states occasionally
with latency having less impact.
these would include card games, strategy games, puzzle games.
this resembles the differentiation between real-time versus turn-based
games, though the analogy falls short.
for example, real-time strategy games run—as the name suggests—in
real-time, but that doesn’t correlate to a high tick rate.
these games can simulate much of what happens
in between player interactions on local machines.
therefore, they don’t need to synchronize game states that often.
if you can choose low tick rates as a developer, you should.
low tick lowers latency requirements and server costs.
sometimes, a game requires high tick rates of synchronization.
for those cases, solutions such as firestore don’t make a good fit.
pick a dedicated multiplayer server solution such as nakama.
nakama has a dart package.
if you expect that your game requires a low tick rate of synchronization,
continue reading.
this recipe demonstrates how to use the
cloud_firestore package
to implement multiplayer capabilities in your game.
this recipe doesn’t require a server.
it uses two or more clients sharing game state using cloud firestore.
<topic_end>
<topic_start>
1. prepare your game for multiplayer
write your game code to allow changing the game state
in response to both local events and remote events.
a local event could be a player action or some game logic.
a remote event could be a world update coming from the server.
to simplify this cookbook recipe, start with
the card template that you’ll find
in the flutter/games repository.
run the following command to clone that repository:
open the project in templates/card.
info note
  you can ignore this step and follow the recipe with your own game
  project. adapt the code at appropriate places.
<topic_end>
<topic_start>
2. install firestore
cloud firestore is a horizontally scaling,
NoSQL document database in the cloud.
it includes built-in live synchronization.
this is perfect for our needs.
it keeps the game state updated in the cloud database,
so every player sees the same state.
if you want a quick, 15-minute primer on cloud firestore,
check out the following video:
to add firestore to your flutter project,
follow the first two steps of the
get started with cloud firestore guide:
the desired outcomes include:
you don’t need to write any dart code in this step.
as soon as you understand the step of writing
dart code in that guide, return to this recipe.
<topic_end>
<topic_start>
3. initialize firestore
open lib/main.dart and import the plugins,
 as well as the firebase_options.dart file
 that was generated by flutterfire configure in the previous step.
<code_start>
import 'package:cloud_firestore/cloud_firestore.dart';
 import 'package:firebase_core/firebase_core.dart';
 import 'firebase_options.dart';
<code_end>
add the following code just above the call to runApp()
 in lib/main.dart:
<code_start>
WidgetsFlutterBinding.ensureInitialized();
 await Firebase.initializeApp(
   options: DefaultFirebaseOptions.currentPlatform,
 );
<code_end>
this ensures that firebase is initialized on game startup.
add the firestore instance to the app.
 that way, any widget can access this instance.
 widgets can also react to the instance missing, if needed.
to do this with the card template, you can use
 the provider package
 (which is already installed as a dependency).
replace the boilerplate runApp(MyApp()) with the following:
<code_start>
runApp(
   provider.value(
     value: FirebaseFirestore.instance,
     child: MyApp(),
   ),
 );
<code_end>
put the provider above MyApp, not inside it.
 this enables you to test the app without firebase.
info note
   in case you are not working with the card template,
   you must either install the provider package
   or use your own method of accessing the FirebaseFirestore
   instance from various parts of your codebase.
<topic_end>
<topic_start>
4. create a firestore controller class
though you can talk to firestore directly,
you should write a dedicated controller class
to make the code more readable and maintainable.
how you implement the controller depends on your game
and on the exact design of your multiplayer experience.
for the case of the card template,
you could synchronize the contents of the two circular playing areas.
it’s not enough for a full multiplayer experience,
but it’s a good start.
to create a controller, copy,
then paste the following code into a new file called
lib/multiplayer/firestore_controller.dart.
<code_start>
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import '../game_internals/board_state.dart';
import '../game_internals/playing_area.dart';
import '../game_internals/playing_card.dart';
class FirestoreController {
  static final _log = Logger('FirestoreController');
  final FirebaseFirestore instance;
  final BoardState boardState;
  /// for now, there is only one match. but in order to be ready
  /// for match-making, put it in a firestore collection called matches.
  late final _matchRef = instance.collection('matches').doc('match_1');
  late final _areaOneRef = _matchRef
      .collection('areas')
      .doc('area_one')
      .withconverter<list<playingcard>>(
          fromFirestore: _cardsFromFirestore, toFirestore: _cardsToFirestore);
  late final _areaTwoRef = _matchRef
      .collection('areas')
      .doc('area_two')
      .withconverter<list<playingcard>>(
          fromFirestore: _cardsFromFirestore, toFirestore: _cardsToFirestore);
  StreamSubscription? _areaOneFirestoreSubscription;
  StreamSubscription? _areaTwoFirestoreSubscription;
  StreamSubscription? _areaOneLocalSubscription;
  StreamSubscription? _areaTwoLocalSubscription;
  FirestoreController({required this.instance, required this.boardState}) {
    // subscribe to the remote changes (from firestore).
    _areaOneFirestoreSubscription = _areaOneRef.snapshots().listen((snapshot) {
      _updateLocalFromFirestore(boardState.areaOne, snapshot);
    });
    _areaTwoFirestoreSubscription = _areaTwoRef.snapshots().listen((snapshot) {
      _updateLocalFromFirestore(boardState.areaTwo, snapshot);
    });
    // subscribe to the local changes in game state.
    _areaOneLocalSubscription = boardState.areaOne.playerChanges.listen((_) {
      _updateFirestoreFromLocalAreaOne();
    });
    _areaTwoLocalSubscription = boardState.areaTwo.playerChanges.listen((_) {
      _updateFirestoreFromLocalAreaTwo();
    });
    _log.fine('Initialized');
  }
  void dispose() {
    _areaOneFirestoreSubscription?.cancel();
    _areaTwoFirestoreSubscription?.cancel();
    _areaOneLocalSubscription?.cancel();
    _areaTwoLocalSubscription?.cancel();
    _log.fine('Disposed');
  }
  /// takes the raw JSON snapshot coming from firestore and attempts to
  /// convert it into a list of [playingcard]s.
  List<PlayingCard> _cardsFromFirestore(
    DocumentSnapshot<Map<String, dynamic>> snapshot,
    SnapshotOptions? options,
  ) {
    final data = snapshot.data()?['cards'] as list?;
    if (data == null) {
      _log.info('No data found on firestore, returning empty list');
      return [];
    }
    final list = List.castFrom<Object?, Map<String, object?>>(data);
    try {
      return list.map((raw) => PlayingCard.fromJson(raw)).toList();
    } catch (e) {
      throw FirebaseControllerException(
          'failed to parse data from firestore: $e');
    }
  }
  /// takes a list of [playingcard]s and converts it into a JSON object
  /// that can be saved into firestore.
  Map<String, object?> _cardsToFirestore(
    List<PlayingCard> cards,
    SetOptions? options,
  ) {
    return {'cards': cards.map((c) => c.toJson()).toList()};
  }
  /// updates firestore with the local state of [area].
  future<void> _updateFirestoreFromLocal(
      PlayingArea area, DocumentReference<List<PlayingCard>> ref) async {
    try {
      _log.fine('Updating firestore with local data (${area.cards}) ...');
      await ref.set(area.cards);
      _log.fine('... done updating.');
    } catch (e) {
      throw FirebaseControllerException(
          'failed to update firestore with local data (${area.cards}): $e');
    }
  }
  /// sends the local state of `boardstate.areaone` to firestore.
  void _updateFirestoreFromLocalAreaOne() {
    _updateFirestoreFromLocal(boardState.areaOne, _areaOneRef);
  }
  /// sends the local state of `boardstate.areatwo` to firestore.
  void _updateFirestoreFromLocalAreaTwo() {
    _updateFirestoreFromLocal(boardState.areaTwo, _areaTwoRef);
  }
  /// updates the local state of [area] with the data from firestore.
  void _updateLocalFromFirestore(
      PlayingArea area, DocumentSnapshot<List<PlayingCard>> snapshot) {
    _log.fine('Received new data from firestore (${snapshot.data()})');
    final cards = snapshot.data() ?? [];
    if (listequals(cards, area.cards)) {
      _log.fine('No change');
    } else {
      _log.fine('Updating local data with firestore data ($cards)');
      area.replaceWith(cards);
    }
  }
}
class FirebaseControllerException implements exception {
  final string message;
  FirebaseControllerException(this.message);
  @override
  string toString() => 'firebasecontrollerexception: $message';
}
<code_end>
notice the following features of this code:
the controller’s constructor takes a BoardState.
this enables the controller to manipulate the local state of the game.
the controller subscribes to both local changes to update firestore
and to remote changes to update the local state and UI.
the fields _areaOneRef and _areaTwoRef are
firebase document references.
they describe where the data for each area resides,
and how to convert between the local dart objects (list<playingcard>)
and remote JSON objects (map<string, dynamic>).
the firestore API lets us subscribe to these references
with .snapshots(), and write to them with .set().
<topic_end>
<topic_start>
5. use the firestore controller
open the file responsible for starting the play session:
 lib/play_session/play_session_screen.dart in the case of the
 card template.
 you instantiate the firestore controller from this file.
import firebase and the controller:
<code_start>
import 'package:cloud_firestore/cloud_firestore.dart';
 import '../multiplayer/firestore_controller.dart';
<code_end>
add a nullable field to the _PlaySessionScreenState class
 to contain a controller instance:
<code_start>
FirestoreController? _firestoreController;
<code_end>
in the initState() method of the same class,
 add code that tries to read the FirebaseFirestore instance
 and, if successful, constructs the controller.
 you added the FirebaseFirestore instance to main.dart
 in the initialize firestore step.
<code_start>
final firestore = context.read<FirebaseFirestore?>();
 if (firestore == null) {
   _log.warning("Firestore instance wasn't provided. "
       'running without _firestoreController.');
 } else {
   _firestoreController = FirestoreController(
     instance: firestore,
     boardState: _boardState,
   );
 }
<code_end>
dispose of the controller using the dispose() method
 of the same class.
<code_start>
_firestoreController?.dispose();
<code_end>
<topic_end>
<topic_start>
6. test the game
run the game on two separate devices
 or in 2 different windows on the same device.
watch how adding a card to an area on one device
 makes it appear on the other one.
open the firebase web console
 and navigate to your project’s firestore database.
watch how it updates the data in real time.
 you can even edit the data in the console
 and see all running clients update.
<topic_end>
<topic_start>
troubleshooting
the most common issues you might encounter when testing
firebase integration include the following:
<topic_end>
<topic_start>
7. next steps
at this point, the game has near-instant and
dependable synchronization of state across clients.
it lacks actual game rules:
what cards can be played when, and with what results.
this depends on the game itself and is left to you to try.
at this point, the shared state of the match only includes
the two playing areas and the cards within them.
you can save other data into _matchRef, too,
like who the players are and whose turn it is.
if you’re unsure where to start,
follow a firestore codelab or two
to familiarize yourself with the API.
at first, a single match should suffice
for testing your multiplayer game with colleagues and friends.
as you approach the release date,
think about authentication and match-making.
thankfully, firebase provides a
built-in way to authenticate users
and the firestore database structure can handle multiple matches.
instead of a single match_1,
you can populate the matches collection with as many records as needed.
an online match can start in a “waiting” state,
with only the first player present.
other players can see the “waiting” matches in some kind of lobby.
once enough players join a match, it becomes “active”.
once again, the exact implementation depends on
the kind of online experience you want.
the basics remain the same:
a large collection of documents,
each representing one active or potential match.
<topic_end>
<topic_start>
flutter news toolkit
the flutter news toolkit enables you to accelerate
development of a mobile news app.
the toolkit assists you in building a customized
template app with prebuilt features required
for most news apps, such authentication and
monetization. after generating your
template app, your primary tasks are to connect to your
data source, and to customize the UI to reflect
your brand.
the flutter news toolkit includes critical features,
such as:
you can use these pre-integrated features out of the box,
or modify and swap them with other functionality that
you prefer.
generating your template app requires answering
a few simple questions, as described on the
flutter news toolkit overview doc page.
for complete documentation on how to configure your project,
create a template app, develop the app, how to
handle authentication, theming, work with an API
server, and much more, check out the
flutter news toolkit documentation.
you might also check out:
info note
  this is an early release of the news toolkit and,
  while it has been tested by early adopters, it
  might have issues or rough edges. please don’t
  hesitate to file an issue.
<topic_end>
<topic_start>
building user interfaces with flutter
flutter widgets are built using a modern framework that takes
inspiration from react. the central idea is that you build
your UI out of widgets. widgets describe what their view
should look like given their current configuration and state.
when a widget’s state changes, the widget rebuilds its description,
which the framework diffs against the previous description in order
to determine the minimal changes needed in the underlying render
tree to transition from one state to the next.
info note
  if you would like to become better acquainted with flutter by diving
  into some code, check out building layouts,
  and adding interactivity to your flutter app.
<topic_end>
<topic_start>
hello world
the minimal flutter app simply calls the runApp()
function with a widget:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const center(
      child: text(
        'hello, world!',
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}
<code_end>
the runApp() function takes the given
widget and makes it the root of the widget tree.
in this example, the widget tree consists of two widgets,
the center widget and its child, the text widget.
the framework forces the root widget to cover the screen,
which means the text “hello, world” ends up centered on screen.
the text direction needs to be specified in this instance;
when the MaterialApp widget is used,
this is taken care of for you, as demonstrated later.
when writing an app, you’ll commonly author new widgets that
are subclasses of either StatelessWidget or StatefulWidget,
depending on whether your widget manages any state.
a widget’s main job is to implement a build() function,
which describes the widget in terms of other, lower-level widgets.
the framework builds those widgets in turn until the process
bottoms out in widgets that represent the underlying RenderObject,
which computes and describes the geometry of the widget.
<topic_end>
<topic_start>
basic widgets
flutter comes with a suite of powerful basic widgets,
of which the following are commonly used:
below are some simple widgets that combine these and other widgets:
<code_start>
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget {
  const MyAppBar({required this.title, super.key});
  // fields in a widget subclass are always marked "final".
  final widget title;
  @override
  widget build(BuildContext context) {
    return container(
      height: 56, // in logical pixels
      padding: const EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(color: colors.blue[500]),
      // row is a horizontal, linear layout.
      child: row(
        children: [
          const IconButton(
            icon: Icon(Icons.menu),
            tooltip: 'navigation menu',
            onPressed: null, // null disables the button
          ),
          // expanded expands its child
          // to fill the available space.
          expanded(
            child: title,
          ),
          const IconButton(
            icon: Icon(Icons.search),
            tooltip: 'search',
            onPressed: null,
          ),
        ],
      ),
    );
  }
}
class MyScaffold extends StatelessWidget {
  const MyScaffold({super.key});
  @override
  widget build(BuildContext context) {
    // material is a conceptual piece
    // of paper on which the UI appears.
    return material(
      // column is a vertical, linear layout.
      child: column(
        children: [
          MyAppBar(
            title: text(
              'example title',
              style: theme.of(context) //
                  .primarytexttheme
                  .titlelarge,
            ),
          ),
          const expanded(
            child: center(
              child: Text('Hello, world!'),
            ),
          ),
        ],
      ),
    );
  }
}
void main() {
  runApp(
    const MaterialApp(
      title: 'my app', // used by the OS task switcher
      home: SafeArea(
        child: MyScaffold(),
      ),
    ),
  );
}
<code_end>
be sure to have a uses-material-design: true entry in the flutter
section of your pubspec.yaml file. it allows you to use the predefined
set of material icons. it’s generally a good idea to include this line
if you are using the materials library.
many material design widgets need to be inside of a MaterialApp
to display properly, in order to inherit theme data.
therefore, run the application with a MaterialApp.
the MyAppBar widget creates a container with a height of 56
device-independent pixels with an internal padding of 8 pixels,
both on the left and the right. inside the container,
MyAppBar uses a row layout to organize its children.
the middle child, the title widget, is marked as expanded,
which means it expands to fill any remaining available space
that hasn’t been consumed by the other children.
you can have multiple expanded children and determine the
ratio in which they consume the available space using the
flex argument to expanded.
the MyScaffold widget organizes its children in a vertical column.
at the top of the column it places an instance of MyAppBar,
passing the app bar a text widget to use as its title.
passing widgets as arguments to other widgets is a powerful technique
that lets you create generic widgets that can be reused in a wide
variety of ways. finally, MyScaffold uses an
expanded to fill the remaining space with its body,
which consists of a centered message.
for more information, check out layouts.
<topic_end>
<topic_start>
using material components
flutter provides a number of widgets that help you build apps
that follow material design. a material app starts with the
MaterialApp widget, which builds a number of useful widgets
at the root of your app, including a navigator,
which manages a stack of widgets identified by strings,
also known as “routes”. the navigator lets you transition smoothly
between screens of your application. using the MaterialApp
widget is entirely optional but a good practice.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      title: 'flutter tutorial',
      home: TutorialHome(),
    ),
  );
}
class TutorialHome extends StatelessWidget {
  const TutorialHome({super.key});
  @override
  widget build(BuildContext context) {
    // scaffold is a layout for
    // the major material components.
    return scaffold(
      appBar: AppBar(
        leading: const IconButton(
          icon: Icon(Icons.menu),
          tooltip: 'navigation menu',
          onPressed: null,
        ),
        title: const Text('Example title'),
        actions: const [
          IconButton(
            icon: Icon(Icons.search),
            tooltip: 'search',
            onPressed: null,
          ),
        ],
      ),
      // body is the majority of the screen.
      body: const center(
        child: Text('Hello, world!'),
      ),
      floatingActionButton: const FloatingActionButton(
        tooltip: 'add', // used by assistive technologies
        onPressed: null,
        child: Icon(Icons.add),
      ),
    );
  }
}
<code_end>
now that the code has switched from MyAppBar and MyScaffold to the
AppBar and scaffold widgets, and from material.dart,
the app is starting to look a bit more material.
for example, the app bar has a shadow and the title text inherits the
correct styling automatically. a floating action button is also added.
notice that widgets are passed as arguments to other widgets.
the scaffold widget takes a number of different widgets as
named arguments, each of which are placed in the scaffold
layout in the appropriate place. similarly, the
AppBar widget lets you pass in widgets for the
leading widget, and the actions of the title widget.
this pattern recurs throughout the framework and is something you
might consider when designing your own widgets.
for more information, check out material components widgets.
info note
  material is one of the 2 bundled designs included with flutter.
  to create an iOS-centric design,
  check out the cupertino components package,
  which has its own versions of
  CupertinoApp, and CupertinoNavigationBar.
<topic_end>
<topic_start>
handling gestures
most applications include some form of user interaction with the system.
the first step in building an interactive application is to detect
input gestures. see how that works by creating a simple button:
<code_start>
import 'package:flutter/material.dart';
class MyButton extends StatelessWidget {
  const MyButton({super.key});
  @override
  widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        print('MyButton was tapped!');
      },
      child: container(
        height: 50,
        padding: const EdgeInsets.all(8),
        margin: const EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5),
          color: Colors.lightGreen[500],
        ),
        child: const center(
          child: Text('Engage'),
        ),
      ),
    );
  }
}
void main() {
  runApp(
    const MaterialApp(
      home: scaffold(
        body: center(
          child: MyButton(),
        ),
      ),
    ),
  );
}
<code_end>
the GestureDetector widget doesn’t have a visual
representation but instead detects gestures made by the
user. when the user taps the container,
the GestureDetector calls its onTap() callback, in this
case printing a message to the console. you can use
GestureDetector to detect a variety of input gestures,
including taps, drags, and scales.
many widgets use a GestureDetector to provide
optional callbacks for other widgets. for example, the
IconButton, ElevatedButton, and
FloatingActionButton widgets have onPressed()
callbacks that are triggered when the user taps the widget.
for more information, check out gestures in flutter.
<topic_end>
<topic_start>
changing widgets in response to input
so far, this page has used only stateless widgets.
stateless widgets receive arguments from their parent widget,
which they store in final member variables.
when a widget is asked to build(), it uses these stored
values to derive new arguments for the widgets it creates.
in order to build more complex experiences—for example,
to react in more interesting ways to user input—applications
typically carry some state. flutter uses StatefulWidgets to capture
this idea. StatefulWidgets are special widgets that know how to generate
state objects, which are then used to hold state.
consider this basic example, using the ElevatedButton mentioned earlier:
<code_start>
import 'package:flutter/material.dart';
class counter extends StatefulWidget {
  // this class is the configuration for the state.
  // it holds the values (in this case nothing) provided
  // by the parent and used by the build  method of the
  // state. fields in a widget subclass are always marked
  // "final".
  const counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int _counter = 0;
  void _increment() {
    setState(() {
      // this call to setState tells the flutter framework
      // that something has changed in this state, which
      // causes it to rerun the build method below so that
      // the display can reflect the updated values. if you
      // change _counter without calling setState(), then
      // the build method won't be called again, and so
      // nothing would appear to happen.
      _counter++;
    });
  }
  @override
  widget build(BuildContext context) {
    // this method is rerun every time setState is called,
    // for instance, as done by the _increment method above.
    // the flutter framework has been optimized to make
    // rerunning build methods fast, so that you can just
    // rebuild anything that needs updating rather than
    // having to individually changes instances of widgets.
    return row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <widget>[
        ElevatedButton(
          onPressed: _increment,
          child: const Text('Increment'),
        ),
        const SizedBox(width: 16),
        Text('Count: $_counter'),
      ],
    );
  }
}
void main() {
  runApp(
    const MaterialApp(
      home: scaffold(
        body: center(
          child: counter(),
        ),
      ),
    ),
  );
}
<code_end>
you might wonder why StatefulWidget and state are separate objects.
in flutter, these two types of objects have different life cycles.
widgets are temporary objects, used to construct a presentation of
the application in its current state. state objects, on the other
hand, are persistent between calls to
build(), allowing them to remember information.
the example above accepts user input and directly uses
the result in its build() method.  in more complex applications,
different parts of the widget hierarchy might be
responsible for different concerns; for example, one
widget might present a complex user interface
with the goal of gathering specific information,
such as a date or location, while another widget might
use that information to change the overall presentation.
in flutter, change notifications flow “up” the widget
hierarchy by way of callbacks, while current state flows
“down” to the stateless widgets that do presentation.
the common parent that redirects this flow is the state.
the following slightly more complex example shows how
this works in practice:
<code_start>
import 'package:flutter/material.dart';
class CounterDisplay extends StatelessWidget {
  const CounterDisplay({required this.count, super.key});
  final int count;
  @override
  widget build(BuildContext context) {
    return Text('Count: $count');
  }
}
class CounterIncrementor extends StatelessWidget {
  const CounterIncrementor({required this.onPressed, super.key});
  final VoidCallback onPressed;
  @override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: const Text('Increment'),
    );
  }
}
class counter extends StatefulWidget {
  const counter({super.key});
  @override
  State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
  int _counter = 0;
  void _increment() {
    setState(() {
      ++_counter;
    });
  }
  @override
  widget build(BuildContext context) {
    return row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <widget>[
        CounterIncrementor(onPressed: _increment),
        const SizedBox(width: 16),
        CounterDisplay(count: _counter),
      ],
    );
  }
}
void main() {
  runApp(
    const MaterialApp(
      home: scaffold(
        body: center(
          child: counter(),
        ),
      ),
    ),
  );
}
<code_end>
notice the creation of two new stateless widgets,
cleanly separating the concerns of displaying the counter
(counterdisplay) and changing the counter (counterincrementor).
although the net result is the same as the previous example,
the separation of responsibility allows greater complexity to
be encapsulated in the individual widgets,
while maintaining simplicity in the parent.
for more information, check out:
<topic_end>
<topic_start>
bringing it all together
what follows is a more complete example that brings together
these concepts: a hypothetical shopping application displays various
products offered for sale, and maintains a shopping cart for
intended purchases. start by defining the presentation class,
ShoppingListItem:
<code_start>
import 'package:flutter/material.dart';
class product {
  const product({required this.name});
  final string name;
}
typedef CartChangedCallback = Function(Product product, bool inCart);
class ShoppingListItem extends StatelessWidget {
  ShoppingListItem({
    required this.product,
    required this.inCart,
    required this.onCartChanged,
  }) : super(key: ObjectKey(product));
  final product product;
  final bool inCart;
  final CartChangedCallback onCartChanged;
  color _getColor(BuildContext context) {
    // the theme depends on the BuildContext because different
    // parts of the tree can have different themes.
    // the BuildContext indicates where the build is
    // taking place and therefore which theme to use.
    return inCart //
        ? colors.black54
        : Theme.of(context).primaryColor;
  }
  TextStyle? _getTextStyle(BuildContext context) {
    if (!incart) return null;
    return const TextStyle(
      color: colors.black54,
      decoration: TextDecoration.lineThrough,
    );
  }
  @override
  widget build(BuildContext context) {
    return ListTile(
      onTap: () {
        onCartChanged(product, inCart);
      },
      leading: CircleAvatar(
        backgroundColor: _getColor(context),
        child: text(product.name[0]),
      ),
      title: text(product.name, style: _getTextStyle(context)),
    );
  }
}
void main() {
  runApp(
    MaterialApp(
      home: scaffold(
        body: center(
          child: ShoppingListItem(
            product: const product(name: 'chips'),
            inCart: true,
            onCartChanged: (product, inCart) {},
          ),
        ),
      ),
    ),
  );
}
<code_end>
the ShoppingListItem widget follows a common pattern
for stateless widgets.  it stores the values it receives
in its constructor in final member variables,
which it then uses during its build() function.
for example, the inCart boolean toggles between two visual
appearances: one that uses the primary color from the current
theme, and another that uses gray.
when the user taps the list item, the widget doesn’t modify
its inCart value directly. instead, the widget calls the
onCartChanged function it received from its parent widget.
this pattern lets you store state higher in the widget
hierarchy, which causes the state to persist for longer periods of time.
in the extreme, the state stored on the widget passed to
runApp() persists for the lifetime of the
application.
when the parent receives the onCartChanged callback,
the parent updates its internal state, which triggers
the parent to rebuild and create a new instance
of ShoppingListItem with the new inCart value.
although the parent creates a new instance of
ShoppingListItem when it rebuilds, that operation is cheap
because the framework compares the newly built widgets with the previously
built widgets and applies only the differences to the underlying
RenderObject.
here’s an example parent widget that stores mutable state:
<code_start>
import 'package:flutter/material.dart';
class product {
  const product({required this.name});
  final string name;
}
typedef CartChangedCallback = Function(Product product, bool inCart);
class ShoppingListItem extends StatelessWidget {
  ShoppingListItem({
    required this.product,
    required this.inCart,
    required this.onCartChanged,
  }) : super(key: ObjectKey(product));
  final product product;
  final bool inCart;
  final CartChangedCallback onCartChanged;
  color _getColor(BuildContext context) {
    // the theme depends on the BuildContext because different
    // parts of the tree can have different themes.
    // the BuildContext indicates where the build is
    // taking place and therefore which theme to use.
    return inCart //
        ? colors.black54
        : Theme.of(context).primaryColor;
  }
  TextStyle? _getTextStyle(BuildContext context) {
    if (!incart) return null;
    return const TextStyle(
      color: colors.black54,
      decoration: TextDecoration.lineThrough,
    );
  }
  @override
  widget build(BuildContext context) {
    return ListTile(
      onTap: () {
        onCartChanged(product, inCart);
      },
      leading: CircleAvatar(
        backgroundColor: _getColor(context),
        child: text(product.name[0]),
      ),
      title: text(
        product.name,
        style: _getTextStyle(context),
      ),
    );
  }
}
class ShoppingList extends StatefulWidget {
  const ShoppingList({required this.products, super.key});
  final List<Product> products;
  // the framework calls createState the first time
  // a widget appears at a given location in the tree.
  // if the parent rebuilds and uses the same type of
  // widget (with the same key), the framework re-uses
  // the state object instead of creating a new state object.
  @override
  State<ShoppingList> createState() => _ShoppingListState();
}
class _ShoppingListState extends State<ShoppingList> {
  final _shoppingCart = <product>{};
  void _handleCartChanged(Product product, bool inCart) {
    setState(() {
      // when a user changes what's in the cart, you need
      // to change _shoppingCart inside a setState call to
      // trigger a rebuild.
      // the framework then calls build, below,
      // which updates the visual appearance of the app.
      if (!incart) {
        _shoppingCart.add(product);
      } else {
        _shoppingCart.remove(product);
      }
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Shopping list'),
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(vertical: 8),
        children: widget.products.map((product) {
          return ShoppingListItem(
            product: product,
            inCart: _shoppingCart.contains(product),
            onCartChanged: _handleCartChanged,
          );
        }).tolist(),
      ),
    );
  }
}
void main() {
  runApp(const MaterialApp(
    title: 'shopping app',
    home: ShoppingList(
      products: [
        product(name: 'eggs'),
        product(name: 'flour'),
        product(name: 'chocolate chips'),
      ],
    ),
  ));
}
<code_end>
the ShoppingList class extends StatefulWidget,
which means this widget stores mutable state.
when the ShoppingList widget is first inserted
into the tree, the framework calls the createState() function
to create a fresh instance of _ShoppingListState to associate with that
location in the tree. (notice that subclasses of
state are typically named with leading underscores to
indicate that they are private implementation details.)
when this widget’s parent rebuilds, the parent creates a new instance
of ShoppingList, but the framework reuses the _ShoppingListState
instance that is already in the tree rather than calling
createState again.
to access properties of the current ShoppingList,
the _ShoppingListState can use its widget property.
if the parent rebuilds and creates a new ShoppingList,
the _ShoppingListState rebuilds with the new widget value.
if you wish to be notified when the widget property changes,
override the didUpdateWidget() function, which is passed
an oldWidget to let you compare the old widget with
the current widget.
when handling the onCartChanged callback, the _ShoppingListState
mutates its internal state by either adding or removing a product from
_shoppingCart. to signal to the framework that it changed its internal
state, it wraps those calls in a setState() call.
calling setState marks this widget as dirty and schedules it to be rebuilt
the next time your app needs to update the screen.
if you forget to call setState when modifying the internal
state of a widget, the framework won’t know your widget is
dirty and might not call the widget’s build() function,
which means the user interface might not update to reflect
the changed state.  by managing state in this way,
you don’t need to write separate code for creating and
updating child widgets. instead, you simply implement the build
function, which handles both situations.
<topic_end>
<topic_start>
responding to widget lifecycle events
after calling createState() on the StatefulWidget,
the framework inserts the new state object into the tree and
then calls initState() on the state object.
a subclass of state can override initState to do work
that needs to happen just once. for example, override initState
to configure animations or to subscribe to platform services.
implementations of initState are required to start
by calling super.initState.
when a state object is no longer needed,
the framework calls dispose() on the state object.
override the dispose function to do cleanup work.
for example, override dispose to cancel timers or to
unsubscribe from platform services. implementations of
dispose typically end by calling super.dispose.
for more information, check out state.
<topic_end>
<topic_start>
keys
use keys to control which widgets the framework matches up
with other widgets when a widget rebuilds. by default, the
framework matches widgets in the current and previous build
according to their runtimeType and the order in which they appear.
with keys, the framework requires that the two widgets have
the same key as well as the same runtimeType.
keys are most useful in widgets that build many instances of
the same type of widget. for example, the ShoppingList widget,
which builds just enough ShoppingListItem instances to
fill its visible region:
without keys, the first entry in the current build
would always sync with the first entry in the previous build,
even if, semantically, the first entry in the list just
scrolled off screen and is no longer visible in the viewport.
by assigning each entry in the list a “semantic” key,
the infinite list can be more efficient because the
framework syncs entries with matching semantic keys
and therefore similar (or identical) visual appearances.
moreover, syncing the entries semantically means that
state retained in stateful child widgets remains attached
to the same semantic entry rather than the entry in the
same numerical position in the viewport.
for more information, check out the key API.
<topic_end>
<topic_start>
global keys
use global keys to uniquely identify child widgets.
global keys must be globally unique across the entire
widget hierarchy, unlike local keys which need
only be unique among siblings. because they are
globally unique, a global key can be used to
retrieve the state associated with a widget.
for more information, check out the GlobalKey API.
<topic_end>
<topic_start>
widget catalog
create beautiful apps faster with flutter’s collection of visual, structural,
platform, and interactive widgets. in addition to browsing widgets by category,
you can also see all the widgets in the widget index.
make your app accessible.
bring animations to your app.
manage assets, display images, and show icons.
async patterns to your flutter application.
widgets you absolutely need to know before building your first flutter app.
beautiful and high-fidelity widgets for current iOS design language.
take user input in addition to input widgets in material components and cupertino.
respond to touch events and route users to different views.
arrange other widgets columns, rows, grids, and many other layouts.
widgets implementing the material 2 design guidelines.
visual, behavioral, and motion-rich widgets implementing the material 3 design specification.Material 3 is the default flutter interface as of flutter 3.16. to learn more about this transition, check out flutter support for material 3.
these widgets apply visual effects to the children without changing their layout, size, or position.
scroll multiple widgets as children of the parent.
manage the theme of your app, makes your app responsive to screen sizes, or add padding.
display and style text.
<topic_end>
<topic_start>
widget of the week
100+ short, 1-minute explainer videos to
help you quickly get started with flutter widgets.
see more widget of the weeks
<topic_end>
<topic_start>
layouts in flutter
<topic_end>
<topic_start>
what's the point?
the core of flutter’s layout mechanism is widgets.
in flutter, almost everything is a widget—even
layout models are widgets. the images, icons,
and text that you see in a flutter app are all widgets.
but things you don’t see are also widgets,
such as the rows, columns, and grids that arrange,
constrain, and align the visible widgets.
you create a layout by composing widgets to build more complex widgets.
for example, the first screenshot below shows 3 icons with a label
under each one:
the second screenshot displays the visual layout, showing a row of
3 columns where each column contains an icon and a label.
info note
  most of the screenshots in this tutorial are displayed with
  debugPaintSizeEnabled set to true so you can see the visual layout.
  for more information, see
  debugging layout issues visually, a section in
  using the flutter inspector.
here’s a diagram of the widget tree for this UI:
most of this should look as you might expect, but you might be wondering
about the containers (shown in pink). container is a widget class
that allows you to customize its child widget. use a container when
you want to add padding, margins, borders, or background color,
to name some of its capabilities.
in this example, each text widget is placed in a container
to add margins. the entire row is also placed in a
container to add padding around the row.
the rest of the UI in this example is controlled by properties.
set an icon’s color using its color property.
use the text.style property to set the font, its color, weight, and so on.
columns and rows have properties that allow you to specify how their
children are aligned vertically or horizontally, and how much space
the children should occupy.
<topic_end>
<topic_start>
lay out a widget
how do you lay out a single widget in flutter? this section
shows you how to create and display a simple widget.
it also shows the entire code for a simple hello world app.
in flutter, it takes only a few steps to put text, an icon,
or an image on the screen.
<topic_end>
<topic_start>
1. select a layout widget
choose from a variety of layout widgets based
on how you want to align or constrain the visible widget,
as these characteristics are typically passed on to the
contained widget.
this example uses center which centers its content
horizontally and vertically.
<topic_end>
<topic_start>
2. create a visible widget
for example, create a text widget:
<code_start>
Text('Hello world'),
<code_end>
create an image widget:
<code_start>
return image.asset(
  image,
  fit: BoxFit.cover,
);
<code_end>
create an icon widget:
<code_start>
icon(
  icons.star,
  color: colors.red[500],
),
<code_end>
<topic_end>
<topic_start>
3. add the visible widget to the layout widget
all layout widgets have either of the following:
add the text widget to the center widget:
<code_start>
const center(
  child: Text('Hello world'),
),
<code_end>
<topic_end>
<topic_start>
4. add the layout widget to the page
a flutter app is itself a widget, and most widgets have a build()
method. instantiating and returning a widget in the app’s build() method
displays the widget.
<topic_end>
<topic_start>
material apps
for a material app, you can use a scaffold widget;
it provides a default banner, background color,
and has API for adding drawers, snack bars, and bottom sheets.
then you can add the center widget directly to the body
property for the home page.
<code_start>
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const string appTitle = 'flutter layout demo';
    return MaterialApp(
      title: appTitle,
      home: scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: const center(
          child: Text('Hello world'),
        ),
      ),
    );
  }
}
<code_end>
info note
  the material library implements widgets that follow material
  design principles. when designing your UI, you can exclusively use
  widgets from the standard widgets library, or you can use
  widgets from the material library. you can mix widgets from both
  libraries, you can customize existing widgets,
  or you can build your own set of custom widgets.
<topic_end>
<topic_start>
cupertino apps
to create a cupertino app, use CupertinoApp and CupertinoPageScaffold widgets.
unlike material, it doesn’t provide a default banner or background color.
you need to set these yourself.
to add an iOS-styled navigation bar to the top of your app, add a
CupertinoNavigationBar widget to the navigationBar
property of your scaffold.
you can use the colors that CupertinoColors provides to
configure your widgets to match iOS design.
to learn what other UI components you can add, check out the
cupertino library.
<code_start>
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const CupertinoApp(
      title: 'flutter layout demo',
      theme: CupertinoThemeData(
        brightness: brightness.light,
        primaryColor: CupertinoColors.systemBlue,
      ),
      home: CupertinoPageScaffold(
        navigationBar: CupertinoNavigationBar(
          backgroundColor: CupertinoColors.systemGrey,
          middle: Text('Flutter layout demo'),
        ),
        child: center(
          child: column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <widget>[
              Text('Hello world'),
            ],
          ),
        ),
      ),
    );
  }
}
<code_end>
info note
  the cupertino library implements widgets that follow
  apple’s human interface guidelines for iOS.
  when designing your UI, you can use
  widgets from the standard widgets library, or the cupertino library.
  you can mix widgets from both libraries, you can customize existing widgets,
  or you can build your own set of custom widgets.
<topic_end>
<topic_start>
Non-Material apps
for a non-Material app, you can add the center widget to the app’s
build() method:
<code_start>
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return container(
      decoration: const BoxDecoration(color: colors.white),
      child: const center(
        child: text(
          'hello world',
          textDirection: TextDirection.ltr,
          style: TextStyle(
            fontSize: 32,
            color: colors.black87,
          ),
        ),
      ),
    );
  }
}
<code_end>
by default, a non-Material app doesn’t include an AppBar, title,
or background color. if you want these features in a non-Material app,
you have to build them yourself. this app changes the background
color to white and the text to dark grey to mimic a material app.
that’s it! when you run the app, you should see hello world.
app source code:
<topic_end>
<topic_start>
lay out multiple widgets vertically and horizontally
one of the most common layout patterns is to arrange
widgets vertically or horizontally. you can use a
row widget to arrange widgets horizontally,
and a column widget to arrange widgets vertically.
<topic_end>
<topic_start>
what's the point?
to create a row or column in flutter, you add a list of children
widgets to a row or column widget. in turn,
each child can itself be a row or column, and so on.
the following example shows how it is possible to nest rows or
columns inside of rows or columns.
this layout is organized as a row. the row contains two children:
a column on the left, and an image on the right:
the left column’s widget tree nests rows and columns.
you’ll implement some of pavlova’s layout code in
nesting rows and columns.
info note
row and column are basic primitive widgets for horizontal
  and vertical layouts—these low-level widgets allow for maximum
  customization. flutter also offers specialized, higher level widgets
  that might be sufficient for your needs. for example,
  instead of row you might prefer ListTile,
  an easy-to-use widget with properties for leading and trailing icons,
  and up to 3 lines of text.  instead of column, you might prefer
  ListView, a column-like layout that automatically scrolls
  if its content is too long to fit the available space.
  for more information, see common layout widgets.
<topic_end>
<topic_start>
aligning widgets
you control how a row or column aligns its children using the
mainAxisAlignment and crossAxisAlignment properties.
for a row, the main axis runs horizontally and the cross axis runs
vertically. for a column, the main axis runs vertically and the cross
axis runs horizontally.
the MainAxisAlignment and CrossAxisAlignment
enums offer a variety of constants for controlling alignment.
info note
  when you add images to your project,
  you need to update the pubspec.yaml file to access
  them—this example uses image.asset to display
  the images.  for more information, see this example’s
  pubspec.yaml file or adding assets and images.
  you don’t need to do this if you’re referencing online
  images using image.network.
in the following example, each of the 3 images is 100 pixels wide.
the render box (in this case, the entire screen)
is more than 300 pixels wide, so setting the main axis
alignment to spaceEvenly divides the free horizontal
space evenly between, before, and after each image.
app source: row_column
columns work the same way as rows. the following example shows a column
of 3 images, each is 100 pixels high. the height of the render box
(in this case, the entire screen) is more than 300 pixels, so
setting the main axis alignment to spaceEvenly divides the free vertical
space evenly between, above, and below each image.
app source: row_column
<topic_end>
<topic_start>
sizing widgets
when a layout is too large to fit a device, a yellow
and black striped pattern appears along the affected edge.
here is an example of a row that is too wide:
widgets can be sized to fit within a row or column by using the
expanded widget. to fix the previous example where the
row of images is too wide for its render box,
wrap each image with an expanded widget.
app source: sizing
perhaps you want a widget to occupy twice as much space as its
siblings. for this, use the expanded widget flex property,
an integer that determines the flex factor for a widget.
the default flex factor is 1. the following code sets
the flex factor of the middle image to 2:
app source: sizing
<topic_end>
<topic_start>
packing widgets
by default, a row or column occupies as much space along its main axis
as possible, but if you want to pack the children closely together,
set its mainAxisSize to MainAxisSize.min. the following example
uses this property to pack the star icons together.
app source: pavlova
<topic_end>
<topic_start>
nesting rows and columns
the layout framework allows you to nest rows and columns
inside of rows and columns as deeply as you need.
let’s look at the code for the outlined
section of the following layout:
the outlined section is implemented as two rows. the ratings row contains
five stars and the number of reviews. the icons row contains three
columns of icons and text.
the widget tree for the ratings row:
the ratings variable creates a row containing a smaller row
of 5 star icons, and text:
<code_start>
final stars = row(
  mainAxisSize: MainAxisSize.min,
  children: [
    Icon(Icons.star, color: colors.green[500]),
    Icon(Icons.star, color: colors.green[500]),
    Icon(Icons.star, color: colors.green[500]),
    const Icon(Icons.star, color: colors.black),
    const Icon(Icons.star, color: colors.black),
  ],
);
final ratings = container(
  padding: const EdgeInsets.all(20),
  child: row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      stars,
      const text(
        '170 reviews',
        style: TextStyle(
          color: colors.black,
          fontWeight: FontWeight.w800,
          fontFamily: 'roboto',
          letterSpacing: 0.5,
          fontSize: 20,
        ),
      ),
    ],
  ),
);
<code_end>
lightbulb tip
  to minimize the visual confusion that can result from
  heavily nested layout code, implement pieces of the UI
  in variables and functions.
the icons row, below the ratings row, contains 3 columns;
each column contains an icon and two lines of text,
as you can see in its widget tree:
the iconList variable defines the icons row:
<code_start>
const descTextStyle = TextStyle(
  color: colors.black,
  fontWeight: FontWeight.w800,
  fontFamily: 'roboto',
  letterSpacing: 0.5,
  fontSize: 18,
  height: 2,
);
// DefaultTextStyle.merge() allows you to create a default text
// style that is inherited by its child and all subsequent children.
final iconList = DefaultTextStyle.merge(
  style: descTextStyle,
  child: container(
    padding: const EdgeInsets.all(20),
    child: row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        column(
          children: [
            Icon(Icons.kitchen, color: colors.green[500]),
            const Text('PREP:'),
            const text('25 min'),
          ],
        ),
        column(
          children: [
            Icon(Icons.timer, color: colors.green[500]),
            const Text('COOK:'),
            const text('1 hr'),
          ],
        ),
        column(
          children: [
            Icon(Icons.restaurant, color: colors.green[500]),
            const Text('FEEDS:'),
            const text('4-6'),
          ],
        ),
      ],
    ),
  ),
);
<code_end>
the leftColumn variable contains the ratings and icons rows,
as well as the title and text that describes the pavlova:
<code_start>
final leftColumn = container(
  padding: const EdgeInsets.fromLTRB(20, 30, 20, 20),
  child: column(
    children: [
      titleText,
      subTitle,
      ratings,
      iconList,
    ],
  ),
);
<code_end>
the left column is placed in a SizedBox to constrain its width.
finally, the UI is constructed with the entire row (containing the
left column and the image) inside a card.
the pavlova image is from pixabay.
you can embed an image from the net using image.network() but,
for this example, the image is saved to an images directory in the project,
added to the pubspec file, and accessed using images.asset().
for more information, see adding assets and images.
<code_start>
body: center(
  child: container(
    margin: const EdgeInsets.fromLTRB(0, 40, 0, 30),
    height: 600,
    child: card(
      child: row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 440,
            child: leftColumn,
          ),
          mainImage,
        ],
      ),
    ),
  ),
),
<code_end>
lightbulb tip
  the pavlova example runs best horizontally on a wide device,
  such as a tablet.  if you are running this example in the iOS simulator,
  you can select a different device using the hardware > device menu.
  for this example, we recommend the iPad pro.
  you can change its orientation to landscape mode using
  hardware > rotate. you can also change the size of the
  simulator window (without changing the number of logical pixels)
  using window > scale.
app source: pavlova
<topic_end>
<topic_start>
common layout widgets
flutter has a rich library of layout widgets.
here are a few of those most commonly used.
the intent is to get you up and running as quickly as possible,
rather than overwhelm you with a complete list.
for information on other available widgets,
refer to the widget catalog,
or use the search box in the API reference docs.
also, the widget pages in the API docs often make suggestions
about similar widgets that might better suit your needs.
the following widgets fall into two categories: standard widgets
from the widgets library, and specialized widgets from the
material library. any app can use the widgets library but
only material apps can use the material components library.
<topic_end>
<topic_start>
standard widgets
<topic_end>
<topic_start>
material widgets
<topic_end>
<topic_start>
container
many layouts make liberal use of containers to separate
widgets using padding, or to add borders or margins.
you can change the device’s background by placing the
entire layout into a container and changing its background
color or image.
<topic_end>
<topic_start>
summary (container)
<topic_end>
<topic_start>
examples (container)
this layout consists of a column with two rows, each containing
2 images. a container is used to change the background color
of the column to a lighter grey.
a container is also used to add a rounded border and margins
to each image:
<code_start>
widget _buildDecoratedImage(int imageIndex) => expanded(
      child: container(
        decoration: BoxDecoration(
          border: border.all(width: 10, color: colors.black38),
          borderRadius: const BorderRadius.all(Radius.circular(8)),
        ),
        margin: const EdgeInsets.all(4),
        child: Image.asset('images/pic$imageIndex.jpg'),
      ),
    );
widget _buildImageRow(int imageIndex) => row(
      children: [
        _buildDecoratedImage(imageIndex),
        _buildDecoratedImage(imageIndex + 1),
      ],
    );
<code_end>
you can find more container examples in the tutorial.
app source: container
<topic_end>
<topic_start>
GridView
use GridView to lay widgets out as a two-dimensional
list. GridView provides two pre-fabricated lists,
or you can build your own custom grid. when a GridView
detects that its contents are too long to fit the render box,
it automatically scrolls.
<topic_end>
<topic_start>
summary (gridview)
info note
  when displaying a two-dimensional list where it’s important which
  row and column a cell occupies (for example,
  it’s the entry in the “calorie” column for the “avocado” row), use
  table or DataTable.
<topic_end>
<topic_start>
examples (gridview)
uses GridView.extent to create a grid with tiles a maximum
  150 pixels wide.
app source: grid_and_list
uses GridView.count to create a grid that’s 2 tiles
  wide in portrait mode, and 3 tiles wide in landscape mode.
  the titles are created by setting the footer property for
  each GridTile.
dart code:
grid_list_demo.dart
<code_start>
widget _buildGrid() => GridView.extent(
    maxCrossAxisExtent: 150,
    padding: const EdgeInsets.all(4),
    mainAxisSpacing: 4,
    crossAxisSpacing: 4,
    children: _buildGridTileList(30));
// the images are saved with names pic0.jpg, pic1.jpg...pic29.jpg.
// the list.generate() constructor allows an easy way to create
// a list when objects have a predictable naming pattern.
List<Container> _buildGridTileList(int count) => list.generate(
    count, (i) => container(child: image.asset('images/pic$i.jpg')));
<code_end>
<topic_end>
<topic_start>
ListView
ListView, a column-like widget, automatically
provides scrolling when its content is too long for
its render box.
<topic_end>
<topic_start>
summary (listview)
<topic_end>
<topic_start>
examples (listview)
uses ListView to display a list of businesses using
  ListTiles. a divider separates the theaters from
  the restaurants.
app source: grid_and_list
uses ListView to display the colors from
  the material 2 design palette
  for a particular color family.
dart code:
colors_demo.dart
<code_start>
widget _buildList() {
  return ListView(
    children: [
      _tile('CineArts at the empire', '85 w portal ave', icons.theaters),
      _tile('The castro theater', '429 castro st', icons.theaters),
      _tile('Alamo drafthouse cinema', '2550 mission st', icons.theaters),
      _tile('Roxie theater', '3117 16th st', icons.theaters),
      _tile('United artists stonestown twin', '501 buckingham way',
          icons.theaters),
      _tile('AMC metreon 16', '135 4th st #3000', icons.theaters),
      const divider(),
      _tile('K\'s kitchen', '757 monterey blvd', icons.restaurant),
      _tile('Emmy\'s restaurant', '1923 ocean ave', icons.restaurant),
      _tile('Chaiya thai restaurant', '272 claremont blvd', icons.restaurant),
      _tile('La ciccia', '291 30th st', icons.restaurant),
    ],
  );
}
ListTile _tile(String title, string subtitle, IconData icon) {
  return ListTile(
    title: text(title,
        style: const TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 20,
        )),
    subtitle: text(subtitle),
    leading: icon(
      icon,
      color: colors.blue[500],
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
stack
use stack to arrange widgets on top of a base
widget—often an image. the widgets can completely
or partially overlap the base widget.
<topic_end>
<topic_start>
summary (stack)
<topic_end>
<topic_start>
examples (stack)
uses stack to overlay a container
  (that displays its text on a translucent
  black background) on top of a CircleAvatar.
  the stack offsets the text using the alignment property and
  alignments.
app source: card_and_stack
uses stack to overlay an icon on top of an image.
dart code:
bottom_navigation_demo.dart
<code_start>
widget _buildStack() {
  return stack(
    alignment: const alignment(0.6, 0.6),
    children: [
      const CircleAvatar(
        backgroundImage: AssetImage('images/pic.jpg'),
        radius: 100,
      ),
      container(
        decoration: const BoxDecoration(
          color: colors.black45,
        ),
        child: const text(
          'mia b',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: colors.white,
          ),
        ),
      ),
    ],
  );
}
<code_end>
<topic_end>
<topic_start>
card
a card, from the material library,
contains related nuggets of information and can
be composed from almost any widget, but is often used with
ListTile. card has a single child,
but its child can be a column, row, list, grid,
or other widget that supports multiple children.
by default, a card shrinks its size to 0 by 0 pixels.
you can use SizedBox to constrain the size of a card.
in flutter, a card features slightly rounded corners
and a drop shadow, giving it a 3d effect.
changing a card’s elevation property allows you to control
the drop shadow effect. setting the elevation to 24,
for example, visually lifts the card further from the
surface and causes the shadow to become more dispersed.
for a list of supported elevation values, see elevation in the
material guidelines.
specifying an unsupported value disables the drop shadow entirely.
<topic_end>
<topic_start>
summary (card)
<topic_end>
<topic_start>
examples (card)
a card containing 3 ListTiles and sized by wrapping
  it with a SizedBox. a divider separates the first
  and second ListTiles.
app source: card_and_stack
a card containing an image and text.
dart code:
cards_demo.dart
<code_start>
widget _buildCard() {
  return SizedBox(
    height: 210,
    child: card(
      child: column(
        children: [
          ListTile(
            title: const text(
              '1625 main street',
              style: TextStyle(fontWeight: FontWeight.w500),
            ),
            subtitle: const Text('My city, CA 99984'),
            leading: icon(
              icons.restaurant_menu,
              color: colors.blue[500],
            ),
          ),
          const divider(),
          ListTile(
            title: const text(
              '(408) 555-1212',
              style: TextStyle(fontWeight: FontWeight.w500),
            ),
            leading: icon(
              icons.contact_phone,
              color: colors.blue[500],
            ),
          ),
          ListTile(
            title: const text('costa@example.com'),
            leading: icon(
              icons.contact_mail,
              color: colors.blue[500],
            ),
          ),
        ],
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
ListTile
use ListTile, a specialized row widget from the
material library, for an easy way to create a row
containing up to 3 lines of text and optional leading
and trailing icons. ListTile is most commonly used in
card or ListView, but can be used elsewhere.
<topic_end>
<topic_start>
summary (listtile)
<topic_end>
<topic_start>
examples (listtile)
a card containing 3 ListTiles.
app source: card_and_stack
uses ListTile with leading widgets.
dart code:
list_demo.dart
<topic_end>
<topic_start>
constraints
to fully understand flutter’s layout system, you need
to learn how flutter positions and sizes
the components in a layout. for more information,
see understanding constraints.
<topic_end>
<topic_start>
videos
the following videos, part of the
flutter in focus series,
explain stateless and stateful widgets.
flutter in focus playlist
each episode of the
widget of the week series
focuses on a widget. several of them includes layout widgets.
flutter widget of the week playlist
<topic_end>
<topic_start>
other resources
the following resources might help when writing layout code.
<topic_end>
<topic_start>
build a flutter layout
<topic_end>
<topic_start>
what you’ll learn
this tutorial explains how to design and build layouts in flutter.
if you use the example code provided, you can build the following app.
photo by dino reichmuth on unsplash.
text by switzerland tourism.
to get a better overview of the layout mechanism, start with
flutter’s approach to layout.
<topic_end>
<topic_start>
diagram the layout
in this section, consider what type of user experience you want for
your app users.
consider how to position the components of your user interface.
a layout consists of the total end result of these positionings.
consider planning your layout to speed up your coding.
using visual cues to know where something goes on screen can be a great help.
use whichever method you prefer, like an interface design tool or a pencil
and a sheet of paper. figure out where you want to place elements on your
screen before writing code. it’s the programming version of the adage:
“measure twice, cut once.”
ask these questions to break the layout down to its basic elements.
identify the larger elements. in this example, you arrange the image, title,
buttons, and description into a column.
diagram each row.
row 1, the title section, has three children:
a column of text, a star icon, and a number.
its first child, the column, contains two lines of text.
that first column might need more space.
row 2, the button section, has three children: each child contains
a column which then contains an icon and text.
after diagramming the layout, consider how you would code it.
would you write all the code in one class?
or, would you create one class for each part of the layout?
to follow flutter best practices, create one class, or widget,
to contain each part of your layout.
when flutter needs to re-render part of a UI,
it updates the smallest part that changes.
this is why flutter makes “everything a widget”.
if only the text changes in a text widget, flutter redraws only that text.
flutter changes the least amount of the UI possible in response to user input.
for this tutorial, write each element you have identified as its own widget.
<topic_end>
<topic_start>
create the app base code
in this section, shell out the basic flutter app code to start your app.
set up your flutter environment.
create a new flutter app.
replace the contents of lib/main.dart with the following code.
this app uses a parameter for the app title and the title shown
on the app’s appBar. this decision simplifies the code.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const string appTitle = 'flutter layout demo';
    return MaterialApp(
      title: appTitle,
      home: scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: const center(
          child: Text('Hello world'),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
add the title section
in this section, create a TitleSection widget that resembles
the following layout.
<topic_end>
<topic_start>
add the TitleSection widget
add the following code after the MyApp class.
<code_start>
class TitleSection extends StatelessWidget {
  const TitleSection({
    super.key,
    required this.name,
    required this.location,
  });
  final string name;
  final string location;
  @override
  widget build(BuildContext context) {
    return padding(
      padding: const EdgeInsets.all(32),
      child: row(
        children: [
          expanded(
            /*1*/
            child: column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /*2*/
                padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: text(
                    name,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                text(
                  location,
                  style: TextStyle(
                    color: colors.grey[500],
                  ),
                ),
              ],
            ),
          ),
          /*3*/
          icon(
            icons.star,
            color: colors.red[500],
          ),
          const text('41'),
        ],
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
change the app body to a scrolling view
in the body property, replace the center widget with a
SingleChildScrollView widget.
within the SingleChildScrollView widget, replace the text widget with a
column widget.
these code updates change the app in the following ways.
<topic_end>
<topic_start>
update the app to display the title section
add the TitleSection widget as the first element in the children list.
this places it at the top of the screen.
pass the provided name and location to the TitleSection constructor.
lightbulb tip
<topic_end>
<topic_start>
add the button section
in this section, add the buttons that will add functionality to your app.
the button section contains three columns that use the same layout:
an icon over a row of text.
plan to distribute these columns in one row so each takes the same
amount of space. paint all text and icons with the primary color.
<topic_end>
<topic_start>
add the ButtonSection widget
add the following code after the TitleSection widget to contain the code
to build the row of buttons.
<code_start>
class ButtonSection extends StatelessWidget {
  const ButtonSection({super.key});
  @override
  widget build(BuildContext context) {
    final color color = Theme.of(context).primaryColor;
// ···
  }
}
<code_end>
<topic_end>
<topic_start>
create a widget to make buttons
as the code for each column could use the same syntax,
create a widget named ButtonWithText.
the widget’s constructor accepts a color, icon data, and a label for the button.
using these values, the widget builds a column with an icon and a stylized
text widget as its children.
to help separate these children, a padding widget the text widget
is wrapped with a padding widget.
add the following code after the ButtonSection class.
<code_start>
class ButtonSection extends StatelessWidget {
  const ButtonSection({super.key});
// ···
}
class ButtonWithText extends StatelessWidget {
  const ButtonWithText({
    super.key,
    required this.color,
    required this.icon,
    required this.label,
  });
  final color color;
  final IconData icon;
  final string label;
  @override
  widget build(BuildContext context) {
    return column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        icon(icon, color: color),
        padding(
          padding: const EdgeInsets.only(top: 8),
          child: text(
            label,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
              color: color,
            ),
          ),
        ),
      ],
    );
  }
<code_end>
<topic_end>
<topic_start>
position the buttons with a row widget
add the following code into the ButtonSection widget.
<code_start>
class ButtonSection extends StatelessWidget {
  const ButtonSection({super.key});
  @override
  widget build(BuildContext context) {
    final color color = Theme.of(context).primaryColor;
    return SizedBox(
      child: row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          ButtonWithText(
            color: color,
            icon: icons.call,
            label: 'call',
          ),
          ButtonWithText(
            color: color,
            icon: icons.near_me,
            label: 'route',
          ),
          ButtonWithText(
            color: color,
            icon: icons.share,
            label: 'share',
          ),
        ],
      ),
    );
  }
}
class ButtonWithText extends StatelessWidget {
  const ButtonWithText({
    super.key,
    required this.color,
    required this.icon,
    required this.label,
  });
  final color color;
  final IconData icon;
  final string label;
  @override
  widget build(BuildContext context) {
    return column(
// ···
    );
  }
}
<code_end>
<topic_end>
<topic_start>
update the app to display the button section
add the button section to the children list.
<topic_end>
<topic_start>
add the text section
in this section, add the text description to this app.
<topic_end>
<topic_start>
add the TextSection widget
add the following code as a separate widget after the ButtonSection widget.
<code_start>
class TextSection extends StatelessWidget {
  const TextSection({
    super.key,
    required this.description,
  });
  final string description;
  @override
  widget build(BuildContext context) {
    return padding(
      padding: const EdgeInsets.all(32),
      child: text(
        description,
        softWrap: true,
      ),
    );
  }
}
<code_end>
by setting softWrap to true, text lines fill the column width before
wrapping at a word boundary.
<topic_end>
<topic_start>
update the app to display the text section
add a new TextSection widget as a child after the ButtonSection.
when adding the TextSection widget, set its description property to
the text of the location description.
<topic_end>
<topic_start>
add the image section
in this section, add the image file to complete your layout.
<topic_end>
<topic_start>
configure your app to use supplied images
to configure your app to reference images, modify its pubspec.yaml file.
create an images directory at the top of the project.
download the lake.jpg image and add it to the new images directory.
info
  you can’t use wget to save this binary file.
  you can download the image from unsplash
  under the unsplash license. the small size comes in at 94.4 kB.
to include images, add an assets tag to the pubspec.yaml file
at the root directory of your app.
when you add assets, it serves as the set of pointers to the images
available to your code.
lightbulb tip
text in the pubspec.yaml respects whitespace and text case.
write the changes to the file as given in the previous example.
this change might require you to restart the running program to
display the image.
<topic_end>
<topic_start>
create the ImageSection widget
define the following ImageSection widget after the other declarations.
<code_start>
class ImageSection extends StatelessWidget {
  const ImageSection({super.key, required this.image});
  final string image;
  @override
  widget build(BuildContext context) {
    return image.asset(
      image,
      width: 600,
      height: 240,
      fit: BoxFit.cover,
    );
  }
}
<code_end>
the BoxFit.cover value tells flutter to display the image with
two constraints. first, display the image as small as possible.
second, cover all the space that the layout allotted, called the render box.
<topic_end>
<topic_start>
update the app to display the image section
add an ImageSection widget as the first child in the children list.
set the image property to the path of the image you added in
configure your app to use supplied images.
<topic_end>
<topic_start>
congratulations
that’s it! when you hot reload the app, your app should look like this.
<topic_end>
<topic_start>
resources
you can access the resources used in this tutorial from these locations:
dart code: main.dart
image: ch-photo
pubspec: pubspec.yaml
<topic_end>
<topic_start>
next steps
to add interactivity to this layout, follow the
interactivity tutorial.
<topic_end>
<topic_start>
lists & grids
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
use lists
displaying lists of data is a fundamental pattern for mobile apps.
flutter includes the ListView
widget to make working with lists a breeze.
<topic_end>
<topic_start>
create a ListView
using the standard ListView constructor is
perfect for lists that contain only a few items.
the built-in ListTile
widget is a way to give items a visual structure.
<code_start>
ListView(
  children: const <widget>[
    ListTile(
      leading: Icon(Icons.map),
      title: Text('Map'),
    ),
    ListTile(
      leading: Icon(Icons.photo_album),
      title: Text('Album'),
    ),
    ListTile(
      leading: Icon(Icons.phone),
      title: Text('Phone'),
    ),
  ],
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'basic list';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: ListView(
          children: const <widget>[
            ListTile(
              leading: Icon(Icons.map),
              title: Text('Map'),
            ),
            ListTile(
              leading: Icon(Icons.photo_album),
              title: Text('Album'),
            ),
            ListTile(
              leading: Icon(Icons.phone),
              title: Text('Phone'),
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
create a horizontal list
you might want to create a list that scrolls
horizontally rather than vertically.
the ListView widget supports horizontal lists.
use the standard ListView constructor, passing in a horizontal
scrollDirection, which overrides the default vertical direction.
<code_start>
ListView(
  // this next line does the trick.
  scrollDirection: axis.horizontal,
  children: <widget>[
    container(
      width: 160,
      color: colors.red,
    ),
    container(
      width: 160,
      color: colors.blue,
    ),
    container(
      width: 160,
      color: colors.green,
    ),
    container(
      width: 160,
      color: colors.yellow,
    ),
    container(
      width: 160,
      color: colors.orange,
    ),
  ],
),
<code_end>
<topic_end>
<topic_start>
interactive example
desktop and web only:
  this example works in the browser and on the desktop.
  however, as this list scrolls on the horizontal axis
  (left to right or right to left),
  hold shift while using the mouse scroll wheel to scroll the list.
to learn more, read the breaking change page on the
  default drag for scrolling devices.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'horizontal list';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: container(
          margin: const EdgeInsets.symmetric(vertical: 20),
          height: 200,
          child: ListView(
            // this next line does the trick.
            scrollDirection: axis.horizontal,
            children: <widget>[
              container(
                width: 160,
                color: colors.red,
              ),
              container(
                width: 160,
                color: colors.blue,
              ),
              container(
                width: 160,
                color: colors.green,
              ),
              container(
                width: 160,
                color: colors.yellow,
              ),
              container(
                width: 160,
                color: colors.orange,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
create a grid list
in some cases, you might want to display your items as a grid rather than
a normal list of items that come one after the next.
for this task, use the GridView widget.
the simplest way to get started using grids is by using the
GridView.count() constructor,
because it allows you to specify how many rows or columns you’d like.
to visualize how GridView works,
generate a list of 100 widgets that display their index in the list.
<code_start>
GridView.count(
  // create a grid with 2 columns. if you change the scrollDirection to
  // horizontal, this produces 2 rows.
  crossAxisCount: 2,
  // generate 100 widgets that display their index in the list.
  children: list.generate(100, (index) {
    return center(
      child: text(
        'item $index',
        style: Theme.of(context).textTheme.headlineSmall,
      ),
    );
  }),
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'grid list';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: GridView.count(
          // create a grid with 2 columns. if you change the scrollDirection to
          // horizontal, this produces 2 rows.
          crossAxisCount: 2,
          // generate 100 widgets that display their index in the list.
          children: list.generate(100, (index) {
            return center(
              child: text(
                'item $index',
                style: Theme.of(context).textTheme.headlineSmall,
              ),
            );
          }),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
create lists with different types of items
you might need to create lists that display different types of content.
for example, you might be working on a list that shows a heading
followed by a few items related to the heading, followed by another heading,
and so on.
here’s how you can create such a structure with flutter:
<topic_end>
<topic_start>
1. create a data source with different types of items
<topic_end>
<topic_start>
types of items
to represent different types of items in a list, define
a class for each type of item.
in this example, create an app that shows a header followed by five
messages. therefore, create three classes: ListItem, HeadingItem,
and MessageItem.
<code_start>
/// the base class for the different types of items the list can contain.
abstract class ListItem {
  /// the title line to show in a list item.
  widget buildTitle(BuildContext context);
  /// the subtitle line, if any, to show in a list item.
  widget buildSubtitle(BuildContext context);
}
/// a ListItem that contains data to display a heading.
class HeadingItem implements ListItem {
  final string heading;
  HeadingItem(this.heading);
  @override
  widget buildTitle(BuildContext context) {
    return text(
      heading,
      style: Theme.of(context).textTheme.headlineSmall,
    );
  }
  @override
  widget buildSubtitle(BuildContext context) => const SizedBox.shrink();
}
/// a ListItem that contains data to display a message.
class MessageItem implements ListItem {
  final string sender;
  final string body;
  MessageItem(this.sender, this.body);
  @override
  widget buildTitle(BuildContext context) => text(sender);
  @override
  widget buildSubtitle(BuildContext context) => text(body);
}
<code_end>
<topic_end>
<topic_start>
create a list of items
most of the time, you would fetch data from the internet or a local
database and convert that data into a list of items.
for this example, generate a list of items to work with. the list
contains a header followed by five messages. each message has one
of 3 types: ListItem, HeadingItem, or MessageItem.
<code_start>
final items = List<ListItem>.generate(
  1000,
  (i) => i % 6 == 0
      ? HeadingItem('Heading $i')
      : MessageItem('Sender $i', 'message body $i'),
);
<code_end>
<topic_end>
<topic_start>
2. convert the data source into a list of widgets
to convert each item into a widget,
use the ListView.builder() constructor.
in general, provide a builder function that checks for what type
of item you’re dealing with, and returns the appropriate widget
for that type of item.
<code_start>
ListView.builder(
  // let the ListView know how many items it needs to build.
  itemCount: items.length,
  // provide a builder function. this is where the magic happens.
  // convert each item into a widget based on the type of item it is.
  itemBuilder: (context, index) {
    final item = items[index];
    return ListTile(
      title: item.buildTitle(context),
      subtitle: item.buildSubtitle(context),
    );
  },
)
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    MyApp(
      items: List<ListItem>.generate(
        1000,
        (i) => i % 6 == 0
            ? HeadingItem('Heading $i')
            : MessageItem('Sender $i', 'message body $i'),
      ),
    ),
  );
}
class MyApp extends StatelessWidget {
  final List<ListItem> items;
  const MyApp({super.key, required this.items});
  @override
  widget build(BuildContext context) {
    const title = 'mixed list';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: ListView.builder(
          // let the ListView know how many items it needs to build.
          itemCount: items.length,
          // provide a builder function. this is where the magic happens.
          // convert each item into a widget based on the type of item it is.
          itemBuilder: (context, index) {
            final item = items[index];
            return ListTile(
              title: item.buildTitle(context),
              subtitle: item.buildSubtitle(context),
            );
          },
        ),
      ),
    );
  }
}
/// the base class for the different types of items the list can contain.
abstract class ListItem {
  /// the title line to show in a list item.
  widget buildTitle(BuildContext context);
  /// the subtitle line, if any, to show in a list item.
  widget buildSubtitle(BuildContext context);
}
/// a ListItem that contains data to display a heading.
class HeadingItem implements ListItem {
  final string heading;
  HeadingItem(this.heading);
  @override
  widget buildTitle(BuildContext context) {
    return text(
      heading,
      style: Theme.of(context).textTheme.headlineSmall,
    );
  }
  @override
  widget buildSubtitle(BuildContext context) => const SizedBox.shrink();
}
/// a ListItem that contains data to display a message.
class MessageItem implements ListItem {
  final string sender;
  final string body;
  MessageItem(this.sender, this.body);
  @override
  widget buildTitle(BuildContext context) => text(sender);
  @override
  widget buildSubtitle(BuildContext context) => text(body);
}
<code_end>
<topic_end>
<topic_start>
list with spaced items
perhaps you want to create a list where all list items
are spaced evenly, so that the items take up the visible space.
for example, the four items in the following image are spaced evenly,
with “item 0” at the top, and “item 3” at the bottom.
at the same time, you might want to allow users
to scroll through the list when the list of items won’t fit,
maybe because a device is too small, a user resized a window,
or the number of items exceeds the screen size.
typically, you use spacer to tune the spacing between widgets,
or expanded to expand a widget to fill the available space.
however, these solutions are not possible inside scrollable widgets,
because they need a finite height constraint.
this recipe demonstrates how to use LayoutBuilder and ConstrainedBox
to space out list items evenly when there is enough space, and to allow
users to scroll when there is not enough space,
using the following steps:
<topic_end>
<topic_start>
1. add a LayoutBuilder with a SingleChildScrollView
start by creating a LayoutBuilder. you need to provide
a builder callback function with two parameters:
in this recipe, you won’t be using the BuildContext,
but you will need the BoxConstraints in the next step.
inside the builder function, return a SingleChildScrollView.
this widget ensures that the child widget can be scrolled,
even when the parent container is too small.
<code_start>
LayoutBuilder(builder: (context, constraints) {
  return SingleChildScrollView(
    child: placeholder(),
  );
});
<code_end>
<topic_end>
<topic_start>
2. add a ConstrainedBox inside the SingleChildScrollView
in this step, add a ConstrainedBox
as the child of the SingleChildScrollView.
the ConstrainedBox widget imposes additional constraints to its child.
configure the constraint by setting the minHeight parameter to be
the maxHeight of the LayoutBuilder constraints.
this ensures that the child widget 
is constrained to have a minimum height equal to the available
space provided by the LayoutBuilder constraints,
namely the maximum height of the BoxConstraints.
<code_start>
LayoutBuilder(builder: (context, constraints) {
  return SingleChildScrollView(
    child: ConstrainedBox(
      constraints: BoxConstraints(minHeight: constraints.maxHeight),
      child: placeholder(),
    ),
  );
});
<code_end>
however, you don’t set the maxHeight parameter,
because you need to allow the child to be larger
than the LayoutBuilder size,
in case the items don’t fit the screen.
<topic_end>
<topic_start>
3. create a column with spaced items
finally, add a column as the child of the ConstrainedBox.
to space the items evenly, 
set the mainAxisAlignment to MainAxisAlignment.spaceBetween.
<code_start>
LayoutBuilder(builder: (context, constraints) {
  return SingleChildScrollView(
    child: ConstrainedBox(
      constraints: BoxConstraints(minHeight: constraints.maxHeight),
      child: column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          ItemWidget(text: 'item 1'),
          ItemWidget(text: 'item 2'),
          ItemWidget(text: 'item 3'),
        ],
      ),
    ),
  );
});
<code_end>
alternatively, you can use the spacer widget 
to tune the spacing between the items,
or the expanded widget, if you want one widget to take more space than others.
for that, you have to wrap the column with an IntrinsicHeight widget,
which forces the column widget to size itself to a minimum height,
instead of expanding infinitely.
<code_start>
LayoutBuilder(builder: (context, constraints) {
  return SingleChildScrollView(
    child: ConstrainedBox(
      constraints: BoxConstraints(minHeight: constraints.maxHeight),
      child: IntrinsicHeight(
        child: column(
          children: [
            ItemWidget(text: 'item 1'),
            spacer(),
            ItemWidget(text: 'item 2'),
            expanded(
              child: ItemWidget(text: 'item 3'),
            ),
          ],
        ),
      ),
    ),
  );
});
<code_end>
lightbulb tip
  play around with different devices, resizing the app,
  or resizing the browser window, and see how the item list adapts
  to the available space.
<topic_end>
<topic_start>
interactive example
this example shows a list of items that are spaced evenly within a column.
the list can be scrolled up and down when the items don’t fit the screen.
the number of items is defined by the variable items,
change this value to see what happens when the items won’t fit the screen.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const SpacedItemsList());
class SpacedItemsList extends StatelessWidget {
  const SpacedItemsList({super.key});
  @override
  widget build(BuildContext context) {
    const items = 4;
    return MaterialApp(
      title: 'flutter demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        cardTheme: CardTheme(color: colors.blue.shade50),
        useMaterial3: true,
      ),
      home: scaffold(
        body: LayoutBuilder(builder: (context, constraints) {
          return SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(minHeight: constraints.maxHeight),
              child: column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: list.generate(
                    items, (index) => ItemWidget(text: 'item $index')),
              ),
            ),
          );
        }),
      ),
    );
  }
}
class ItemWidget extends StatelessWidget {
  const ItemWidget({
    super.key,
    required this.text,
  });
  final string text;
  @override
  widget build(BuildContext context) {
    return card(
      child: SizedBox(
        height: 100,
        child: center(child: text(text)),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
work with long lists
the standard ListView constructor works well
for small lists. to work with lists that contain
a large number of items, it’s best to use the
ListView.builder constructor.
in contrast to the default ListView constructor, which requires
creating all items at once, the ListView.builder() constructor
creates items as they’re scrolled onto the screen.
<topic_end>
<topic_start>
1. create a data source
first, you need a data source. for example, your data source
might be a list of messages, search results, or products in a store.
most of the time, this data comes from the internet or a database.
for this example, generate a list of 10,000 strings using the
list.generate constructor.
<code_start>
List<String>.generate(10000, (i) => 'item $i'),
<code_end>
<topic_end>
<topic_start>
2. convert the data source into widgets
to display the list of strings, render each string as a widget
using ListView.builder().
in this example, display each string on its own line.
<code_start>
ListView.builder(
  itemCount: items.length,
  prototypeItem: ListTile(
    title: text(items.first),
  ),
  itemBuilder: (context, index) {
    return ListTile(
      title: text(items[index]),
    );
  },
)
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    MyApp(
      items: List<String>.generate(10000, (i) => 'item $i'),
    ),
  );
}
class MyApp extends StatelessWidget {
  final List<String> items;
  const MyApp({super.key, required this.items});
  @override
  widget build(BuildContext context) {
    const title = 'long list';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: ListView.builder(
          itemCount: items.length,
          prototypeItem: ListTile(
            title: text(items.first),
          ),
          itemBuilder: (context, index) {
            return ListTile(
              title: text(items[index]),
            );
          },
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
children’s extent
to specify each item’s extent, you can use either itemExtent or prototypeItem.
specifying either is more efficient than letting the children determine their own extent
because the scrolling machinery can make use of the foreknowledge of the children’s
extent to save work, for example when the scroll position changes drastically.
<topic_end>
<topic_start>
scrolling
flutter has many built-in widgets that automatically
scroll and also offers a variety of widgets
that you can customize to create specific scrolling
behavior.
<topic_end>
<topic_start>
basic scrolling
many flutter widgets support scrolling out of the box
and do most of the work for you. for example,
SingleChildScrollView automatically scrolls its
child when necessary. other useful widgets include
ListView and GridView.
you can check out more of these widgets on the
scrolling page of the widget catalog.
<topic_end>
<topic_start>
infinite scrolling
when you have a long list of items
in your ListView or GridView (including an infinite list),
you can build the items on demand
as they scroll into view. this provides a much
more performant scrolling experience.
for more information, check out
ListView.builder or GridView.builder.
<topic_end>
<topic_start>
specialized scrollable widgets
the following widgets provide more specific scrolling
behavior.
a video on using DraggableScrollableSheet
turn the scrollable area into a wheel! ListWheelScrollView
<topic_end>
<topic_start>
fancy scrolling
perhaps you want to implement elastic scrolling,
also called scroll bouncing. or maybe you want to
implement other dynamic scrolling effects, like parallax scrolling.
or perhaps you want a scrolling header with very specific behavior,
such as shrinking or disappearing.
you can achieve all this and more using the
flutter sliver* classes.
a sliver refers to a piece of the scrollable area.
you can define and insert a sliver into a CustomScrollView
to have finer-grained control over that area.
for more information, check out
using slivers to achieve fancy scrolling
and the sliver classes.
<topic_end>
<topic_start>
nested scrolling widgets
how do you nest a scrolling widget
inside another scrolling widget
without hurting scrolling performance?
do you set the ShrinkWrap property to true,
or do you use a sliver?
check out the “shrinkwrap vs slivers” video:
<topic_end>
<topic_start>
using slivers to achieve fancy scrolling
a sliver is a portion of a scrollable area that you
can define to behave in a special way.
you can use slivers to achieve custom scrolling effects,
such as elastic scrolling.
for a free, instructor-led video workshop that uses DartPad,
check out the following video about using slivers.
<topic_end>
<topic_start>
resources
for more information on implementing fancy scrolling effects
in flutter, see the following resources:
a free article on medium that
    explains how to implement custom scrolling
    using the sliver classes.
a one-minute widget-of-the-week
    video that gives an overview of the
    SliverAppBar widget.
a one-minute widget-of-the-week
    video that gives an overview of the SliverList
    and SliverGrid widgets.
a 50-minute episode of the boring show
    where ian hickson, flutter’s tech lead, and filip hracek
    discuss the power of slivers.
<topic_end>
<topic_start>
API docs
to learn more about the available sliver APIs,
check out these related API docs:
<topic_end>
<topic_start>
place a floating app bar above a list
to make it easier for users to view a list of items,
you might want to hide the app bar as the user scrolls down the list.
this is especially true if your app displays a “tall”
app bar that occupies a lot of vertical space.
typically, you create an app bar by providing an appBar property to the
scaffold widget. this creates a fixed app bar that always remains above
the body of the scaffold.
moving the app bar from a scaffold widget into a
CustomScrollView allows you to create an app bar
that scrolls offscreen as you scroll through a
list of items contained inside the CustomScrollView.
this recipe demonstrates how to use a CustomScrollView to display a list of
items with an app bar on top that scrolls offscreen as the user scrolls
down the list using the following steps:
<topic_end>
<topic_start>
1. create a CustomScrollView
to create a floating app bar, place the app bar inside a
CustomScrollView that also contains the list of items.
this synchronizes the scroll position of the app bar and the list of items.
you might think of the CustomScrollView widget as a ListView
that allows you to mix and match different types of scrollable lists
and widgets together.
the scrollable lists and widgets provided to the
CustomScrollView are known as slivers. there are several types
of slivers, such as SliverList, SliverGrid, and SliverAppBar.
in fact, the ListView and GridView widgets use the SliverList and
SliverGrid widgets to implement scrolling.
for this example, create a CustomScrollView that contains a
SliverAppBar and a SliverList. in addition, remove any app bars
that you provide to the scaffold widget.
<code_start>
scaffold(
  // no appBar property provided, only the body.
  body: CustomScrollView(
      // add the app bar and list of items as slivers in the next steps.
      slivers: <widget>[]),
);
<code_end>
<topic_end>
<topic_start>
2. use SliverAppBar to add a floating app bar
next, add an app bar to the CustomScrollView.
flutter provides the SliverAppBar widget which,
much like the normal AppBar widget,
uses the SliverAppBar to display a title,
tabs, images and more.
however, the SliverAppBar also gives you the ability to create a “floating”
app bar that scrolls offscreen as the user scrolls down the list.
furthermore, you can configure the SliverAppBar to shrink and
expand as the user scrolls.
to create this effect:
<code_start>
CustomScrollView(
  slivers: [
    // add the app bar to the CustomScrollView.
    const SliverAppBar(
      // provide a standard title.
      title: text(title),
      // allows the user to reveal the app bar if they begin scrolling
      // back up the list of items.
      floating: true,
      // display a placeholder widget to visualize the shrinking size.
      flexibleSpace: placeholder(),
      // make the initial height of the SliverAppBar larger than normal.
      expandedHeight: 200,
    ),
  ],
)
<code_end>
lightbulb tip
  play around with the
  various properties you can pass to the SliverAppBar widget,
  and use hot reload to see the results. for example, use an image
  widget for the flexibleSpace property to create a background image that
  shrinks in size as it’s scrolled offscreen.
<topic_end>
<topic_start>
3. add a list of items using a SliverList
now that you have the app bar in place, add a list of items to the
CustomScrollView. you have two options: a SliverList
or a SliverGrid.  if you need to display a list of items one after the other,
use the SliverList widget.
if you need to display a grid list, use the SliverGrid widget.
the SliverList and SliverGrid widgets take one required parameter: a
SliverChildDelegate, which provides a list
of widgets to SliverList or SliverGrid.
for example, the SliverChildBuilderDelegate
allows you to create a list of items that are built lazily as you scroll,
just like the ListView.builder widget.
<code_start>
// next, create a SliverList
SliverList(
  // use a delegate to build items as they're scrolled on screen.
  delegate: SliverChildBuilderDelegate(
    // the builder function returns a ListTile with a title that
    // displays the index of the current item.
    (context, index) => ListTile(title: Text('Item #$index')),
    // builds 1000 ListTiles
    childCount: 1000,
  ),
)
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'floating app bar';
    return MaterialApp(
      title: title,
      home: scaffold(
        // no appbar provided to the scaffold, only a body with a
        // CustomScrollView.
        body: CustomScrollView(
          slivers: [
            // add the app bar to the CustomScrollView.
            const SliverAppBar(
              // provide a standard title.
              title: text(title),
              // allows the user to reveal the app bar if they begin scrolling
              // back up the list of items.
              floating: true,
              // display a placeholder widget to visualize the shrinking size.
              flexibleSpace: placeholder(),
              // make the initial height of the SliverAppBar larger than normal.
              expandedHeight: 200,
            ),
            // next, create a SliverList
            SliverList(
              // use a delegate to build items as they're scrolled on screen.
              delegate: SliverChildBuilderDelegate(
                // the builder function returns a ListTile with a title that
                // displays the index of the current item.
                (context, index) => ListTile(title: Text('Item #$index')),
                // builds 1000 ListTiles
                childCount: 1000,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
create a scrolling parallax effect
when you scroll a list of cards (containing images,
for example) in an app, you might notice that those
images appear to scroll more slowly than the rest of the
screen. it almost looks as if the cards in the list
are in the foreground, but the images themselves sit
far off in the distant background. this effect is
known as parallax.
in this recipe, you create the parallax effect by building
a list of cards (with rounded corners containing some text).
each card also contains an image.
as the cards slide up the screen,
the images within each card slide down.
the following animation shows the app’s behavior:
<topic_end>
<topic_start>
create a list to hold the parallax items
to display a list of parallax scrolling images,
you must first display a list.
create a new stateless widget called ParallaxRecipe.
within ParallaxRecipe, build a widget tree with a
SingleChildScrollView and a column, which forms
a list.
<code_start>
class ParallaxRecipe extends StatelessWidget {
  const ParallaxRecipe({super.key});
  @override
  widget build(BuildContext context) {
    return const SingleChildScrollView(
      child: column(
        children: [],
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
display items with text and a static image
each list item displays a rounded-rectangle background
image, representing one of seven locations in the world.
stacked on top of that background image is the
name of the location and its country,
positioned in the lower left. between the
background image and the text is a dark gradient,
which improves the legibility
of the text against the background.
implement a stateless widget called LocationListItem
that consists of the previously mentioned visuals.
for now, use a static image widget for the background.
later, you’ll replace that widget with a parallax version.
<code_start>
@immutable
class LocationListItem extends StatelessWidget {
  const LocationListItem({
    super.key,
    required this.imageUrl,
    required this.name,
    required this.country,
  });
  final string imageUrl;
  final string name;
  final string country;
  @override
  widget build(BuildContext context) {
    return padding(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16),
          child: stack(
            children: [
              _buildParallaxBackground(context),
              _buildGradient(),
              _buildTitleAndSubtitle(),
            ],
          ),
        ),
      ),
    );
  }
  widget _buildParallaxBackground(BuildContext context) {
    return positioned.fill(
      child: image.network(
        imageUrl,
        fit: BoxFit.cover,
      ),
    );
  }
  widget _buildGradient() {
    return positioned.fill(
      child: DecoratedBox(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [colors.transparent, Colors.black.withOpacity(0.7)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            stops: const [0.6, 0.95],
          ),
        ),
      ),
    );
  }
  widget _buildTitleAndSubtitle() {
    return positioned(
      left: 20,
      bottom: 20,
      child: column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          text(
            name,
            style: const TextStyle(
              color: colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          text(
            country,
            style: const TextStyle(
              color: colors.white,
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }
}
<code_end>
next, add the list items to your ParallaxRecipe widget.
<code_start>
class ParallaxRecipe extends StatelessWidget {
  const ParallaxRecipe({super.key});
  @override
  widget build(BuildContext context) {
    return SingleChildScrollView(
      child: column(
        children: [
          for (final location in locations)
            LocationListItem(
              imageUrl: location.imageUrl,
              name: location.name,
              country: location.place,
            ),
        ],
      ),
    );
  }
}
<code_end>
you now have a typical, scrollable list of cards
that displays seven unique locations in the world.
in the next step, you add a parallax effect to the
background image.
<topic_end>
<topic_start>
implement the parallax effect
a parallax scrolling effect is achieved by slightly
pushing the background image in the opposite direction
of the rest of the list. as the list items slide up
the screen, each background image slides slightly downward.
conversely, as the list items slide down the screen,
each background image slides slightly upward.
visually, this results in parallax.
the parallax effect depends on the list item’s
current position within its ancestor scrollable.
as the list item’s scroll position changes, the position
of the list item’s background image must also change.
this is an interesting problem to solve. the position
of a list item within the scrollable isn’t
available until flutter’s layout phase is complete.
this means that the position of the background image
must be determined in the paint phase, which comes after
the layout phase. fortunately, flutter provides a widget
called flow, which is specifically designed to give you
control over the transform of a child widget immediately
before the widget is painted. in other words,
you can intercept the painting phase and take control
to reposition your child widgets however you want.
info note
  to learn more, check out this short
  widget of the week video on the flow widget:
info note
  in cases where you need control over what a child paints,
  rather than where a child is painted,
  consider using a CustomPaint widget.
in cases where you need control over the layout,
  painting, and hit testing, consider defining a
  custom RenderBox.
wrap your background image widget with a
flow widget.
<code_start>
widget _buildParallaxBackground(BuildContext context) {
  return flow(
    children: [
      image.network(
        imageUrl,
        fit: BoxFit.cover,
      ),
    ],
  );
}
<code_end>
introduce a new FlowDelegate called ParallaxFlowDelegate.
<code_start>
widget _buildParallaxBackground(BuildContext context) {
  return flow(
    delegate: ParallaxFlowDelegate(),
    children: [
      image.network(
        imageUrl,
        fit: BoxFit.cover,
      ),
    ],
  );
}
<code_end>
<code_start>
class ParallaxFlowDelegate extends FlowDelegate {
  ParallaxFlowDelegate();
  @override
  BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) {
    // TODO: we'll add more to this later.
  }
  @override
  void paintChildren(FlowPaintingContext context) {
    // TODO: we'll add more to this later.
  }
  @override
  bool shouldRepaint(covariant FlowDelegate oldDelegate) {
    // TODO: we'll add more to this later.
    return true;
  }
}
<code_end>
a FlowDelegate controls how its children are sized
and where those children are painted. in this case,
your flow widget has only one child: the background image.
that image must be exactly as wide as the flow widget.
return tight width constraints for your background image child.
<code_start>
@override
BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) {
  return BoxConstraints.tightFor(
    width: constraints.maxWidth,
  );
}
<code_end>
your background images are now sized appropriately,
but you still need to calculate the vertical position
of each background image based on its scroll
position, and then paint it.
there are three critical pieces of information that
you need to compute the desired position of a
background image:
to look up the bounds of the scrollable,
you pass a ScrollableState into your FlowDelegate.
to look up the bounds of your individual list item,
pass your list item’s BuildContext into your FlowDelegate.
to look up the final size of your background image,
assign a GlobalKey to your image widget,
and then you pass that GlobalKey into your
FlowDelegate.
make this information available to ParallaxFlowDelegate.
<code_start>
@immutable
class LocationListItem extends StatelessWidget {
  final GlobalKey _backgroundImageKey = GlobalKey();
  widget _buildParallaxBackground(BuildContext context) {
    return flow(
      delegate: ParallaxFlowDelegate(
        scrollable: scrollable.of(context),
        listItemContext: context,
        backgroundImageKey: _backgroundImageKey,
      ),
      children: [
        image.network(
          imageUrl,
          key: _backgroundImageKey,
          fit: BoxFit.cover,
        ),
      ],
    );
  }
}
<code_end>
<code_start>
class ParallaxFlowDelegate extends FlowDelegate {
  ParallaxFlowDelegate({
    required this.scrollable,
    required this.listItemContext,
    required this.backgroundImageKey,
  });
  final ScrollableState scrollable;
  final BuildContext listItemContext;
  final GlobalKey backgroundImageKey;
}
<code_end>
having all the information needed to implement
parallax scrolling, implement the shouldRepaint() method.
<code_start>
@override
bool shouldRepaint(ParallaxFlowDelegate oldDelegate) {
  return scrollable != oldDelegate.scrollable ||
      listItemContext != oldDelegate.listItemContext ||
      backgroundImageKey != oldDelegate.backgroundImageKey;
}
<code_end>
now, implement the layout calculations for the parallax effect.
first, calculate the pixel position of a list
item within its ancestor scrollable.
<code_start>
@override
void paintChildren(FlowPaintingContext context) {
  // calculate the position of this list item within the viewport.
  final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
  final listItemBox = listItemContext.findRenderObject() as RenderBox;
  final listItemOffset = listItemBox.localToGlobal(
      listItemBox.size.centerLeft(Offset.zero),
      ancestor: scrollableBox);
}
<code_end>
use the pixel position of the list item to calculate its
percentage from the top of the scrollable.
a list item at the top of the scrollable area should
produce 0%, and a list item at the bottom of the
scrollable area should produce 100%.
<code_start>
@override
void paintChildren(FlowPaintingContext context) {
  // calculate the position of this list item within the viewport.
  final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
  final listItemBox = listItemContext.findRenderObject() as RenderBox;
  final listItemOffset = listItemBox.localToGlobal(
      listItemBox.size.centerLeft(Offset.zero),
      ancestor: scrollableBox);
  // determine the percent position of this list item within the
  // scrollable area.
  final viewportDimension = scrollable.position.viewportDimension;
  final scrollFraction =
      (listitemoffset.dy / viewportDimension).clamp(0.0, 1.0);
<code_end>
use the scroll percentage to calculate an alignment.
at 0%, you want alignment(0.0, -1.0),
and at 100%, you want alignment(0.0, 1.0).
these coordinates correspond to top and bottom
alignment, respectively.
<code_start>
@override
void paintChildren(FlowPaintingContext context) {
  // calculate the position of this list item within the viewport.
  final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
  final listItemBox = listItemContext.findRenderObject() as RenderBox;
  final listItemOffset = listItemBox.localToGlobal(
      listItemBox.size.centerLeft(Offset.zero),
      ancestor: scrollableBox);
  // determine the percent position of this list item within the
  // scrollable area.
  final viewportDimension = scrollable.position.viewportDimension;
  final scrollFraction =
      (listitemoffset.dy / viewportDimension).clamp(0.0, 1.0);
  // calculate the vertical alignment of the background
  // based on the scroll percent.
  final verticalAlignment = alignment(0.0, scrollFraction * 2 - 1);
<code_end>
use verticalAlignment, along with the size of the
list item and the size of the background image,
to produce a rect that determines where the
background image should be positioned.
<code_start>
@override
void paintChildren(FlowPaintingContext context) {
  // calculate the position of this list item within the viewport.
  final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
  final listItemBox = listItemContext.findRenderObject() as RenderBox;
  final listItemOffset = listItemBox.localToGlobal(
      listItemBox.size.centerLeft(Offset.zero),
      ancestor: scrollableBox);
  // determine the percent position of this list item within the
  // scrollable area.
  final viewportDimension = scrollable.position.viewportDimension;
  final scrollFraction =
      (listitemoffset.dy / viewportDimension).clamp(0.0, 1.0);
  // calculate the vertical alignment of the background
  // based on the scroll percent.
  final verticalAlignment = alignment(0.0, scrollFraction * 2 - 1);
  // convert the background alignment into a pixel offset for
  // painting purposes.
  final backgroundSize =
      (backgroundimagekey.currentcontext!.findrenderobject() as RenderBox)
          .size;
  final listItemSize = context.size;
  final childRect =
      verticalAlignment.inscribe(backgroundSize, offset.zero & listItemSize);
<code_end>
using childRect, paint the background image with
the desired translation transformation.
it’s this transformation over time that gives you the
parallax effect.
<code_start>
@override
void paintChildren(FlowPaintingContext context) {
  // calculate the position of this list item within the viewport.
  final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
  final listItemBox = listItemContext.findRenderObject() as RenderBox;
  final listItemOffset = listItemBox.localToGlobal(
      listItemBox.size.centerLeft(Offset.zero),
      ancestor: scrollableBox);
  // determine the percent position of this list item within the
  // scrollable area.
  final viewportDimension = scrollable.position.viewportDimension;
  final scrollFraction =
      (listitemoffset.dy / viewportDimension).clamp(0.0, 1.0);
  // calculate the vertical alignment of the background
  // based on the scroll percent.
  final verticalAlignment = alignment(0.0, scrollFraction * 2 - 1);
  // convert the background alignment into a pixel offset for
  // painting purposes.
  final backgroundSize =
      (backgroundimagekey.currentcontext!.findrenderobject() as RenderBox)
          .size;
  final listItemSize = context.size;
  final childRect =
      verticalAlignment.inscribe(backgroundSize, offset.zero & listItemSize);
  // paint the background.
  context.paintChild(
    0,
    transform:
        transform.translate(offset: offset(0.0, childRect.top)).transform,
  );
<code_end>
you need one final detail to achieve the parallax effect.
the ParallaxFlowDelegate repaints when the inputs change,
but the ParallaxFlowDelegate doesn’t repaint every time
the scroll position changes.
pass the ScrollableState’s ScrollPosition to
the FlowDelegate superclass so that the FlowDelegate
repaints every time the ScrollPosition changes.
<code_start>
class ParallaxFlowDelegate extends FlowDelegate {
  ParallaxFlowDelegate({
    required this.scrollable,
    required this.listItemContext,
    required this.backgroundImageKey,
  }) : super(repaint: scrollable.position);
}
<code_end>
congratulations!
you now have a list of cards with parallax,
scrolling background images.
<topic_end>
<topic_start>
interactive example
run the app:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
const color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: const scaffold(
        body: center(
          child: ExampleParallax(),
        ),
      ),
    );
  }
}
class ExampleParallax extends StatelessWidget {
  const ExampleParallax({
    super.key,
  });
  @override
  widget build(BuildContext context) {
    return SingleChildScrollView(
      child: column(
        children: [
          for (final location in locations)
            LocationListItem(
              imageUrl: location.imageUrl,
              name: location.name,
              country: location.place,
            ),
        ],
      ),
    );
  }
}
class LocationListItem extends StatelessWidget {
  LocationListItem({
    super.key,
    required this.imageUrl,
    required this.name,
    required this.country,
  });
  final string imageUrl;
  final string name;
  final string country;
  final GlobalKey _backgroundImageKey = GlobalKey();
  @override
  widget build(BuildContext context) {
    return padding(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16),
          child: stack(
            children: [
              _buildParallaxBackground(context),
              _buildGradient(),
              _buildTitleAndSubtitle(),
            ],
          ),
        ),
      ),
    );
  }
  widget _buildParallaxBackground(BuildContext context) {
    return flow(
      delegate: ParallaxFlowDelegate(
        scrollable: scrollable.of(context),
        listItemContext: context,
        backgroundImageKey: _backgroundImageKey,
      ),
      children: [
        image.network(
          imageUrl,
          key: _backgroundImageKey,
          fit: BoxFit.cover,
        ),
      ],
    );
  }
  widget _buildGradient() {
    return positioned.fill(
      child: DecoratedBox(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [colors.transparent, Colors.black.withOpacity(0.7)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            stops: const [0.6, 0.95],
          ),
        ),
      ),
    );
  }
  widget _buildTitleAndSubtitle() {
    return positioned(
      left: 20,
      bottom: 20,
      child: column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          text(
            name,
            style: const TextStyle(
              color: colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          text(
            country,
            style: const TextStyle(
              color: colors.white,
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }
}
class ParallaxFlowDelegate extends FlowDelegate {
  ParallaxFlowDelegate({
    required this.scrollable,
    required this.listItemContext,
    required this.backgroundImageKey,
  }) : super(repaint: scrollable.position);
  final ScrollableState scrollable;
  final BuildContext listItemContext;
  final GlobalKey backgroundImageKey;
  @override
  BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) {
    return BoxConstraints.tightFor(
      width: constraints.maxWidth,
    );
  }
  @override
  void paintChildren(FlowPaintingContext context) {
    // calculate the position of this list item within the viewport.
    final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
    final listItemBox = listItemContext.findRenderObject() as RenderBox;
    final listItemOffset = listItemBox.localToGlobal(
        listItemBox.size.centerLeft(Offset.zero),
        ancestor: scrollableBox);
    // determine the percent position of this list item within the
    // scrollable area.
    final viewportDimension = scrollable.position.viewportDimension;
    final scrollFraction =
        (listitemoffset.dy / viewportDimension).clamp(0.0, 1.0);
    // calculate the vertical alignment of the background
    // based on the scroll percent.
    final verticalAlignment = alignment(0.0, scrollFraction * 2 - 1);
    // convert the background alignment into a pixel offset for
    // painting purposes.
    final backgroundSize =
        (backgroundimagekey.currentcontext!.findrenderobject() as RenderBox)
            .size;
    final listItemSize = context.size;
    final childRect =
        verticalAlignment.inscribe(backgroundSize, offset.zero & listItemSize);
    // paint the background.
    context.paintChild(
      0,
      transform:
          transform.translate(offset: offset(0.0, childRect.top)).transform,
    );
  }
  @override
  bool shouldRepaint(ParallaxFlowDelegate oldDelegate) {
    return scrollable != oldDelegate.scrollable ||
        listItemContext != oldDelegate.listItemContext ||
        backgroundImageKey != oldDelegate.backgroundImageKey;
  }
}
class parallax extends SingleChildRenderObjectWidget {
  const parallax({
    super.key,
    required widget background,
  }) : super(child: background);
  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderParallax(scrollable: scrollable.of(context));
  }
  @override
  void updateRenderObject(
      BuildContext context, covariant RenderParallax renderObject) {
    renderObject.scrollable = scrollable.of(context);
  }
}
class ParallaxParentData extends ContainerBoxParentData<RenderBox> {}
class RenderParallax extends RenderBox
    with RenderObjectWithChildMixin<RenderBox>, RenderProxyBoxMixin {
  RenderParallax({
    required ScrollableState scrollable,
  }) : _scrollable = scrollable;
  ScrollableState _scrollable;
  ScrollableState get scrollable => _scrollable;
  set scrollable(ScrollableState value) {
    if (value != _scrollable) {
      if (attached) {
        _scrollable.position.removeListener(markNeedsLayout);
      }
      _scrollable = value;
      if (attached) {
        _scrollable.position.addListener(markNeedsLayout);
      }
    }
  }
  @override
  void attach(covariant PipelineOwner owner) {
    super.attach(owner);
    _scrollable.position.addListener(markNeedsLayout);
  }
  @override
  void detach() {
    _scrollable.position.removeListener(markNeedsLayout);
    super.detach();
  }
  @override
  void setupParentData(covariant RenderObject child) {
    if (child.parentdata is! ParallaxParentData) {
      child.parentData = ParallaxParentData();
    }
  }
  @override
  void performLayout() {
    size = constraints.biggest;
    // force the background to take up all available width
    // and then scale its height based on the image's aspect ratio.
    final background = child!;
    final backgroundImageConstraints =
        BoxConstraints.tightFor(width: size.width);
    background.layout(backgroundImageConstraints, parentUsesSize: true);
    // set the background's local offset, which is zero.
    (background.parentdata as ParallaxParentData).offset = offset.zero;
  }
  @override
  void paint(PaintingContext context, offset offset) {
    // get the size of the scrollable area.
    final viewportDimension = scrollable.position.viewportDimension;
    // calculate the global position of this list item.
    final scrollableBox = scrollable.context.findRenderObject() as RenderBox;
    final backgroundOffset =
        localToGlobal(size.centerLeft(Offset.zero), ancestor: scrollableBox);
    // determine the percent position of this list item within the
    // scrollable area.
    final scrollFraction =
        (backgroundoffset.dy / viewportDimension).clamp(0.0, 1.0);
    // calculate the vertical alignment of the background
    // based on the scroll percent.
    final verticalAlignment = alignment(0.0, scrollFraction * 2 - 1);
    // convert the background alignment into a pixel offset for
    // painting purposes.
    final background = child!;
    final backgroundSize = background.size;
    final listItemSize = size;
    final childRect =
        verticalAlignment.inscribe(backgroundSize, offset.zero & listItemSize);
    // paint the background.
    context.paintChild(
        background,
        (background.parentdata as ParallaxParentData).offset +
            offset +
            offset(0.0, childRect.top));
  }
}
class location {
  const location({
    required this.name,
    required this.place,
    required this.imageUrl,
  });
  final string name;
  final string place;
  final string imageUrl;
}
const urlPrefix =
    'https://docs.flutter.dev/cookbook/img-files/effects/parallax';
const locations = [
  location(
    name: 'mount rushmore',
    place: 'u.s.a',
    imageUrl: '$urlprefix/01-mount-rushmore.jpg',
  ),
  location(
    name: 'gardens by the bay',
    place: 'singapore',
    imageUrl: '$urlprefix/02-singapore.jpg',
  ),
  location(
    name: 'machu picchu',
    place: 'peru',
    imageUrl: '$urlprefix/03-machu-picchu.jpg',
  ),
  location(
    name: 'vitznau',
    place: 'switzerland',
    imageUrl: '$urlprefix/04-vitznau.jpg',
  ),
  location(
    name: 'bali',
    place: 'indonesia',
    imageUrl: '$urlprefix/05-bali.jpg',
  ),
  location(
    name: 'mexico city',
    place: 'mexico',
    imageUrl: '$urlprefix/06-mexico-city.jpg',
  ),
  location(
    name: 'cairo',
    place: 'egypt',
    imageUrl: '$urlprefix/07-cairo.jpg',
  ),
];
<code_end>
<topic_end>
<topic_start>
creating responsive and adaptive apps
one of flutter’s primary goals is to create a framework
that allows you to develop apps from a single codebase
that look and feel great on any platform.
this means that your app might appear on screens of
many different sizes, from a watch, to a foldable
phone with two screens, to a high def monitor.
two terms that describe concepts for this
scenario are adaptive and responsive. ideally,
you’d want your app to be both but what,
exactly, does this mean?
these terms are similar, but they are not the same.
<topic_end>
<topic_start>
the difference between an adaptive and a responsive app
adaptive and responsive can be viewed as separate
dimensions of an app: you can have an adaptive app
that is not responsive, or vice versa. and, of course,
an app can be both, or neither.
learn more in the following 5-minute video:
adaptive vs responsive
<topic_end>
<topic_start>
creating a responsive flutter app
flutter allows you to create apps that self-adapt
to the device’s screen size and orientation.
there are two basic approaches to creating flutter
apps with responsive design:
other useful widgets and classes for creating a responsive UI:
<topic_end>
<topic_start>
other resources
for more information, here are a few resources,
including contributions from the flutter community:
<topic_end>
<topic_start>
creating an adaptive flutter app
learn more about creating an adaptive flutter app with
building adaptive apps, written by the gskinner team.
you might also check out the following episodes
of the boring show:
adaptive layouts
adaptive layouts, part 2
for an excellent example of an adaptive app,
check out flutter folio, a scrapbooking app created
in collaboration with gskinner and the flutter team:
the folio source code is also available on GitHub.
learn more on the gskinner blog.
<topic_end>
<topic_start>
other resources
you can learn more about creating platform adaptive apps
in the following resources:
<topic_end>
<topic_start>
creating responsive and adaptive apps
one of flutter’s primary goals is to create a framework
that allows you to develop apps from a single codebase
that look and feel great on any platform.
this means that your app might appear on screens of
many different sizes, from a watch, to a foldable
phone with two screens, to a high def monitor.
two terms that describe concepts for this
scenario are adaptive and responsive. ideally,
you’d want your app to be both but what,
exactly, does this mean?
these terms are similar, but they are not the same.
<topic_end>
<topic_start>
the difference between an adaptive and a responsive app
adaptive and responsive can be viewed as separate
dimensions of an app: you can have an adaptive app
that is not responsive, or vice versa. and, of course,
an app can be both, or neither.
learn more in the following 5-minute video:
adaptive vs responsive
<topic_end>
<topic_start>
creating a responsive flutter app
flutter allows you to create apps that self-adapt
to the device’s screen size and orientation.
there are two basic approaches to creating flutter
apps with responsive design:
other useful widgets and classes for creating a responsive UI:
<topic_end>
<topic_start>
other resources
for more information, here are a few resources,
including contributions from the flutter community:
<topic_end>
<topic_start>
creating an adaptive flutter app
learn more about creating an adaptive flutter app with
building adaptive apps, written by the gskinner team.
you might also check out the following episodes
of the boring show:
adaptive layouts
adaptive layouts, part 2
for an excellent example of an adaptive app,
check out flutter folio, a scrapbooking app created
in collaboration with gskinner and the flutter team:
the folio source code is also available on GitHub.
learn more on the gskinner blog.
<topic_end>
<topic_start>
other resources
you can learn more about creating platform adaptive apps
in the following resources:
<topic_end>
<topic_start>
building adaptive apps
<topic_end>
<topic_start>
overview
flutter provides new opportunities to build apps that can
run on mobile, desktop, and the web from a single codebase.
however, with these opportunities, come new challenges.
you want your app to feel familiar to users,
adapting to each platform by maximizing usability and
ensuring a comfortable and seamless experience.
that is, you need to build apps that are not just
multiplatform, but are fully platform adaptive.
there are many considerations for developing platform-adaptive
apps, but they fall into three major categories:
this page covers all three categories in detail
using code snippets to illustrate the concepts.
if you’d like to see how these concepts come together,
check out the flokk and folio examples that
were built using the concepts described here.
original demo code for adaptive app development techniques from flutter-adaptive-demo.
<topic_end>
<topic_start>
building adaptive layouts
one of the first things you must consider when writing
your app for multiple platforms is how to adapt
it to the various sizes and shapes of the screens that
it will run on.
<topic_end>
<topic_start>
layout widgets
if you’ve been building apps or websites,
you’re probably familiar with creating responsive interfaces.
luckily for flutter developers,
there are a large set of widgets to make this easier.
some of flutter’s most useful layout widgets include:
single child
Align—Aligns a child within itself.
it takes a double value between -1 and 1,
for both the vertical and horizontal alignment.
AspectRatio—Attempts to size the
child to a specific aspect ratio.
ConstrainedBox—Imposes size constraints on its child,
offering control over the minimum or maximum size.
CustomSingleChildLayout—Uses a delegate function
to position a single child. the delegate can determine
the layout constraints and positioning for the child.
expanded and Flexible—Allows a child of a
row or column to shrink or grow to fill any available space.
FractionallySizedBox—Sizes its child to a fraction
of the available space.
LayoutBuilder—Builds a widget that can reflow
itself based on its parents size.
SingleChildScrollView—Adds scrolling to a single child.
often used with a row or column.
multichild
column, row, and Flex—Lays out children
in a single horizontal or vertical run.
both column and row extend the flex widget.
CustomMultiChildLayout—Uses a delegate function to
position multiple children during the layout phase.
Flow—Similar to CustomMultiChildLayout,
but more efficient because it’s performed during the
paint phase rather than the layout phase.
ListView, GridView, and
CustomScrollView—Provides scrollable
lists of children.
Stack—Layers and positions multiple children
relative to the edges of the stack.
functions similarly to position-fixed in CSS.
Table—Uses a classic table layout algorithm for
its children, combining multiple rows and columns.
Wrap—Displays its children in multiple horizontal
or vertical runs.
to see more available widgets and example code, see
layout widgets.
<topic_end>
<topic_start>
visual density
different input devices offer various levels of precision,
which necessitate differently sized hit areas.
flutter’s VisualDensity class makes it easy to adjust the
density of your views across the entire application,
for example, by making a button larger
(and therefore easier to tap) on a touch device.
when you change the VisualDensity for your MaterialApp,
MaterialComponents that support it animate their densities
to match. by default, both horizontal and vertical densities
are set to 0.0, but you can set the densities to any negative
or positive value that you want. by switching between different
densities, you can easily adjust your UI:
to set a custom visual density, inject the density into
your MaterialApp theme:
<code_start>
double densityAmt = touchMode ? 0.0 : -1.0;
VisualDensity density =
    VisualDensity(horizontal: densityAmt, vertical: densityAmt);
return MaterialApp(
  theme: ThemeData(visualDensity: density),
  home: MainAppScaffold(),
  debugShowCheckedModeBanner: false,
);
<code_end>
to use VisualDensity inside your own views,
you can look it up:
<code_start>
VisualDensity density = Theme.of(context).visualDensity;
<code_end>
not only does the container react automatically to changes
in density, it also animates when it changes.
this ties together your custom components,
along with the built-in components,
for a smooth transition effect across the app.
as shown, VisualDensity is unit-less,
so it can mean different things to different views.
in this example, 1 density unit equals 6 pixels,
but this is totally up to your views to decide.
the fact that it is unit-less makes it quite versatile,
and it should work in most contexts.
it’s worth noting that the material components generally
use a value of around 4 logical pixels for each
visual density unit. for more information about the
supported components, see VisualDensity API.
for more information about density principles in general,
see the material design guide.
<topic_end>
<topic_start>
contextual layout
if you need more than density changes and can’t find a
widget that does what you need, you can take a more
procedural approach to adjust parameters, calculate sizes,
swap widgets, or completely restructure your UI to suit
a particular form factor.
<topic_end>
<topic_start>
screen-based breakpoints
the simplest form of procedural layouts uses
screen-based breakpoints. in flutter,
this can be done with the MediaQuery API.
there are no hard and fast rules for the sizes to use
here, but these are general values:
<code_start>
class FormFactor {
  static double desktop = 900;
  static double tablet = 600;
  static double handset = 300;
}
<code_end>
using breakpoints, you can set up a simple system
to determine the device type:
<code_start>
ScreenType getFormFactor(BuildContext context) {
  // use .shortestside to detect device type regardless of orientation
  double deviceWidth = MediaQuery.of(context).size.shortestSide;
  if (devicewidth > FormFactor.desktop) return ScreenType.desktop;
  if (devicewidth > FormFactor.tablet) return ScreenType.tablet;
  if (devicewidth > FormFactor.handset) return ScreenType.handset;
  return ScreenType.watch;
}
<code_end>
as an alternative, you could abstract it more
and define it in terms of small to large:
<code_start>
enum ScreenSize { small, normal, large, extraLarge }
ScreenSize getSize(BuildContext context) {
  double deviceWidth = MediaQuery.of(context).size.shortestSide;
  if (devicewidth > 900) return ScreenSize.extraLarge;
  if (devicewidth > 600) return ScreenSize.large;
  if (devicewidth > 300) return ScreenSize.normal;
  return ScreenSize.small;
}
<code_end>
screen-based breakpoints are best used for making
top-level decisions in your app. changing things like
visual density, paddings, or font-sizes are best when
defined on a global basis.
you can also use screen-based breakpoints to reflow your
top-level widget trees. for example, you could switch
from a vertical to a horizontal layout when the user isn’t on a handset:
<code_start>
bool isHandset = MediaQuery.of(context).size.width < 600;
return flex(
  direction: isHandset ? axis.vertical : axis.horizontal,
  children: const [text('foo'), Text('Bar'), Text('Baz')],
);
<code_end>
in another widget,
you might swap some of the children completely:
<code_start>
widget foo = row(
  children: [
    ...ishandset ? _getHandsetChildren() : _getNormalChildren(),
  ],
);
<code_end>
<topic_end>
<topic_start>
use LayoutBuilder for extra flexibility
even though checking total screen size is great for
full-screen pages or making global layout decisions,
it’s often not ideal for nested subviews.
often, subviews have their own internal breakpoints
and care only about the space that they have available to render.
the simplest way to handle this in flutter is using the
LayoutBuilder class. LayoutBuilder allows a
widget to respond to incoming local size constraints,
which can make the widget more versatile than if it
depended on a global value.
the previous example could be rewritten using LayoutBuilder:
<code_start>
widget foo = LayoutBuilder(builder: (context, constraints) {
  bool useVerticalLayout = constraints.maxWidth < 400;
  return flex(
    direction: useVerticalLayout ? axis.vertical : axis.horizontal,
    children: const [
      Text('Hello'),
      Text('World'),
    ],
  );
});
<code_end>
this widget can now be composed within a side panel,
dialog, or even a full-screen view,
and adapt its layout to whatever space is provided.
<topic_end>
<topic_start>
device segmentation
there are times when you want to make layout decisions
based on the actual platform you’re running on,
regardless of size. for example, when building a
custom title bar, you might need to check the operating
system type and tweak the layout of your title bar,
so it doesn’t get covered by the native window buttons.
to determine which combination of platforms you’re on,
you can use the platform API along with the kIsWeb value:
<code_start>
bool get isMobileDevice => !kisweb && (platform.isios || Platform.isAndroid);
bool get isDesktopDevice =>
    !kisweb && (platform.ismacos || Platform.isWindows || Platform.isLinux);
bool get isMobileDeviceOrWeb => kIsWeb || isMobileDevice;
bool get isDesktopDeviceOrWeb => kIsWeb || isDesktopDevice;
<code_end>
the platform API can’t be accessed from web builds without
throwing an exception, because the dart.io package isn’t
supported on the web target. as a result, the above code checks
for web first, and because of short-circuiting,
dart never calls platform on web targets.
use Platform/kIsWeb when the logic absolutely must
run for a given platform. for example,
talking to a plugin that only works on iOS,
or displaying a widget that only conforms to
play store policy and not the app store’s.
<topic_end>
<topic_start>
single source of truth for styling
you’ll probably find it easier to maintain your views
if you create a single source of truth for styling values
like padding, spacing, corner shape, font sizes, and so on.
this can be done easily with some helper classes:
<code_start>
class insets {
  static const double xsmall = 3;
  static const double small = 4;
  static const double medium = 5;
  static const double large = 10;
  static const double extraLarge = 20;
  // etc
}
class fonts {
  static const string raleway = 'raleway';
  // etc
}
class TextStyles {
  static const TextStyle raleway = TextStyle(
    fontFamily: fonts.raleway,
  );
  static TextStyle buttonText1 =
      const TextStyle(fontWeight: FontWeight.bold, fontSize: 14);
  static TextStyle buttonText2 =
      const TextStyle(fontWeight: FontWeight.normal, fontSize: 11);
  static TextStyle h1 =
      const TextStyle(fontWeight: FontWeight.bold, fontSize: 22);
  static TextStyle h2 =
      const TextStyle(fontWeight: FontWeight.bold, fontSize: 16);
  static TextStyle body1 = raleway.copyWith(color: const Color(0xFF42A5F5));
  // etc
}
<code_end>
these constants can then be used in place of hard-coded numeric values:
<code_start>
return padding(
  padding: const EdgeInsets.all(Insets.small),
  child: Text('Hello!', style: TextStyles.body1),
);
<code_end>
use theme.of(context).platform for theming and
design choices, like what kind of switches to show
and general Cupertino/Material adaptions.
with all views referencing the same shared-design system rules,
they tend to look better and more consistent.
making a change or adjusting a value for a specific platform
can be done in a single place, instead of using an error-prone
search and replace. using shared rules has the added benefit
of helping enforce consistency on the design side.
some common design system categories that can be represented
this way are:
like most rules, there are exceptions:
one-off values that are used nowhere else in the app.
there is little point in cluttering up the styling rules
with these values, but it’s worth considering if they
should be derived from an existing value (for example,
padding + 1.0). you should also watch for reuse or duplication
of the same semantic values. those values should likely be
added to the global styling ruleset.
<topic_end>
<topic_start>
design to the strengths of each form factor
beyond screen size, you should also spend time
considering the unique strengths and weaknesses
of different form factors. it isn’t always ideal
for your multiplatform app to offer identical
functionality everywhere. consider whether it makes
sense to focus on specific capabilities,
or even remove certain features, on some device categories.
for example, mobile devices are portable and have cameras,
but they aren’t well suited for detailed creative work.
with this in mind, you might focus more on capturing content
and tagging it with location data for a mobile UI,
but focus on organizing or manipulating that content
for a tablet or desktop UI.
another example is leveraging the web’s extremely low barrier
for sharing. if you’re deploying a web app,
decide which deep links to support,
and design your navigation routes with those in mind.
the key takeaway here is to think about what each
platform does best and see if there are unique capabilities
you can leverage.
<topic_end>
<topic_start>
use desktop build targets for rapid testing
one of the most effective ways to test adaptive
interfaces is to take advantage of the desktop build targets.
when running on a desktop, you can easily resize the window
while the app is running to preview various screen sizes.
this, combined with hot reload, can greatly accelerate the
development of a responsive UI.
<topic_end>
<topic_start>
solve touch first
building a great touch UI can often be more difficult
than a traditional desktop UI due, in part,
to the lack of input accelerators like right-click,
scroll wheel, or keyboard shortcuts.
one way to approach this challenge is to focus initially
on a great touch-oriented UI. you can still do most of
your testing using the desktop target for its iteration speed.
but, remember to switch frequently to a mobile device to
verify that everything feels right.
after you have the touch interface polished, you can tweak
the visual density for mouse users, and then layer on all
the additional inputs. approach these other inputs as
accelerator—alternatives that make a task faster.
the important thing to consider is what a user expects
when using a particular input device,
and work to reflect that in your app.
<topic_end>
<topic_start>
input
of course, it isn’t enough to just adapt how your app looks,
you also have to support varying user inputs.
the mouse and keyboard introduce input types beyond those
found on a touch device—like scroll wheel, right-click,
hover interactions, tab traversal, and keyboard shortcuts.
<topic_end>
<topic_start>
scroll wheel
scrolling widgets like ScrollView or ListView
support the scroll wheel by default, and because
almost every scrollable custom widget is built
using one of these, it works with them as well.
if you need to implement custom scroll behavior,
you can use the listener widget, which lets you
customize how your UI reacts to the scroll wheel.
<code_start>
return listener(
  onPointerSignal: (event) {
    if (event is PointerScrollEvent) print(event.scrollDelta.dy);
  },
  child: ListView(),
);
<code_end>
<topic_end>
<topic_start>
tab traversal and focus interactions
users with physical keyboards expect that they can use
the tab key to quickly navigate your application,
and users with motor or vision differences often rely
completely on keyboard navigation.
there are two considerations for tab interactions:
how focus moves from widget to widget, known as traversal,
and the visual highlight shown when a widget is focused.
most built-in components, like buttons and text fields,
support traversal and highlights by default.
if you have your own widget that you want included in
traversal, you can use the FocusableActionDetector widget
to create your own controls. it combines the functionality
of actions, shortcuts, MouseRegion, and
focus widgets to create a detector that defines actions
and key bindings, and provides callbacks for handling focus
and hover highlights.
<code_start>
class _BasicActionDetectorState extends State<BasicActionDetector> {
  bool _hasFocus = false;
  @override
  widget build(BuildContext context) {
    return FocusableActionDetector(
      onFocusChange: (value) => setState(() => _hasFocus = value),
      actions: <type, Action<Intent>>{
        ActivateIntent: CallbackAction<Intent>(onInvoke: (intent) {
          print('Enter or space was pressed!');
          return null;
        }),
      },
      child: stack(
        clipBehavior: clip.none,
        children: [
          const FlutterLogo(size: 100),
          // position focus in the negative margin for a cool effect
          if (_hasfocus)
            positioned(
              left: -4,
              top: -4,
              bottom: -4,
              right: -4,
              child: _roundedBorder(),
            )
        ],
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
controlling traversal order
to get more control over the order that
widgets are focused on when the user presses tab,
you can use FocusTraversalGroup to define sections
of the tree that should be treated as a group when tabbing.
for example, you might to tab through all the fields in
a form before tabbing to the submit button:
<code_start>
return column(children: [
  FocusTraversalGroup(
    child: MyFormWithMultipleColumnsAndRows(),
  ),
  SubmitButton(),
]);
<code_end>
flutter has several built-in ways to traverse widgets and groups,
defaulting to the ReadingOrderTraversalPolicy class.
this class usually works well, but it’s possible to modify this
using another predefined TraversalPolicy class or by creating
a custom policy.
<topic_end>
<topic_start>
keyboard accelerators
in addition to tab traversal, desktop and web users are accustomed
to having various keyboard shortcuts bound to specific actions.
whether it’s the delete key for quick deletions or
Control+N for a new document, be sure to consider the different
accelerators your users expect. the keyboard is a powerful
input tool, so try to squeeze as much efficiency from it as you can.
your users will appreciate it!
keyboard accelerators can be accomplished in a few ways in flutter
depending on your goals.
if you have a single widget like a TextField or a button that
already has a focus node, you can wrap it in a KeyboardListener
or a focus widget and listen for keyboard events:
<code_start>
  @override
  widget build(BuildContext context) {
    return focus(
      onKeyEvent: (node, event) {
        if (event is KeyDownEvent) {
          print(event.logicalKey);
        }
        return KeyEventResult.ignored;
      },
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 400),
        child: const TextField(
          decoration: InputDecoration(
            border: OutlineInputBorder(),
          ),
        ),
      ),
    );
  }
}
<code_end>
if you’d like to apply a set of keyboard shortcuts to a
large section of the tree, you can use the shortcuts widget:
<code_start>
// define a class for each type of shortcut action you want
class CreateNewItemIntent extends intent {
  const CreateNewItemIntent();
}
widget build(BuildContext context) {
  return shortcuts(
    // bind intents to key combinations
    shortcuts: const <shortcutactivator, intent>{
      SingleActivator(LogicalKeyboardKey.keyN, control: true):
          CreateNewItemIntent(),
    },
    child: actions(
      // bind intents to an actual method in your code
      actions: <type, Action<Intent>>{
        CreateNewItemIntent: CallbackAction<CreateNewItemIntent>(
          onInvoke: (intent) => _createNewItem(),
        ),
      },
      // your sub-tree must be wrapped in a focusNode, so it can take focus.
      child: focus(
        autofocus: true,
        child: container(),
      ),
    ),
  );
}
<code_end>
the shortcuts widget is useful because it only
allows shortcuts to be fired when this widget tree
or one of its children has focus and is visible.
the final option is a global listener. this listener
can be used for always-on, app-wide shortcuts or for
panels that can accept shortcuts whenever they’re visible
(regardless of their focus state). adding global listeners
is easy with HardwareKeyboard:
<code_start>
@override
void initState() {
  super.initState();
  HardwareKeyboard.instance.addHandler(_handleKey);
}
@override
void dispose() {
  HardwareKeyboard.instance.removeHandler(_handleKey);
  super.dispose();
}
<code_end>
to check key combinations with the global listener,
you can use the HardwareKeyboard.instance.logicalKeysPressed set.
for example, a method like the following can check whether any
of the provided keys are being held down:
<code_start>
static bool isKeyDown(Set<LogicalKeyboardKey> keys) {
  return keys
      .intersection(hardwarekeyboard.instance.logicalkeyspressed)
      .isnotempty;
}
<code_end>
putting these two things together,
you can fire an action when Shift+N is pressed:
<code_start>
bool _handleKey(KeyEvent event) {
  bool isShiftDown = isKeyDown({
    LogicalKeyboardKey.shiftLeft,
    LogicalKeyboardKey.shiftRight,
  });
  if (isshiftdown && event.logicalKey == LogicalKeyboardKey.keyN) {
    _createNewItem();
    return true;
  }
  return false;
}
<code_end>
one note of caution when using the static listener,
is that you often need to disable it when the user
is typing in a field or when the widget it’s associated with
is hidden from view.
unlike with shortcuts or KeyboardListener,
this is your responsibility to manage. this can be especially
important when you’re binding a Delete/Backspace accelerator for
delete, but then have child TextFields that the user
might be typing in.
<topic_end>
<topic_start>
mouse enter, exit, and hover
on desktop, it’s common to change the mouse cursor
to indicate the functionality about the content the
mouse is hovering over. for example, you usually see
a hand cursor when you hover over a button,
or an i cursor when you hover over text.
the material component set has built-in support
for your standard button and text cursors.
to change the cursor from within your own widgets,
use MouseRegion:
<code_start>
// show hand cursor
return MouseRegion(
  cursor: SystemMouseCursors.click,
  // request focus when clicked
  child: GestureDetector(
    onTap: () {
      Focus.of(context).requestFocus();
      _submit();
    },
    child: Logo(showBorder: hasFocus),
  ),
);
<code_end>
MouseRegion is also useful for creating custom
rollover and hover effects:
<code_start>
return MouseRegion(
  onEnter: (_) => setState(() => _isMouseOver = true),
  onExit: (_) => setState(() => _isMouseOver = false),
  onHover: (e) => print(e.localPosition),
  child: container(
    height: 500,
    color: _isMouseOver ? colors.blue : colors.black,
  ),
);
<code_end>
<topic_end>
<topic_start>
idioms and norms
the final area to consider for adaptive apps is platform standards.
each platform has its own idioms and norms;
these nominal or de facto standards inform user expectations
of how an application should behave. thanks, in part to the web,
users are accustomed to more customized experiences,
but reflecting these platform standards can still provide
significant benefits:
reduce cognitive load—By matching the user’s
existing mental model, accomplishing tasks becomes intuitive,
which requires less thinking,
boosts productivity, and reduces frustrations.
build trust—Users can become wary or suspicious
when applications don’t adhere to their expectations.
conversely, a UI that feels familiar can build user trust
and can help improve the perception of quality.
this often has the added benefit of better app store
ratings—something we can all appreciate!
<topic_end>
<topic_start>
consider expected behavior on each platform
the first step is to spend some time considering what
the expected appearance, presentation, or behavior is on this platform.
try to forget any limitations of your current implementation,
and just envision the ideal user experience.
work backwards from there.
another way to think about this is to ask,
“how would a user of this platform expect to achieve this goal?”
then, try to envision how that would work in your app
without any compromises.
this can be difficult if you aren’t a regular user of the platform.
you might be unaware of the specific idioms and can easily miss
them completely. for example, a lifetime android user is
likely unaware of platform conventions on iOS,
and the same holds true for macOS, linux, and windows.
these differences might be subtle to you,
but be painfully obvious to an experienced user.
<topic_end>
<topic_start>
find a platform advocate
if possible, assign someone as an advocate for each platform.
ideally, your advocate uses the platform as their primary device,
and can offer the perspective of a highly opinionated user.
to reduce the number of people, combine roles.
have one advocate for windows and android,
one for linux and the web, and one for mac and iOS.
the goal is to have constant, informed feedback so the app
feels great on each platform. advocates should be encouraged
to be quite picky, calling out anything they feel differs from
typical applications on their device. a simple example is how
the default button in a dialog is typically on the left on mac
and linux, but is on the right on windows.
details like that are easy to miss if you aren’t using a platform
on a regular basis.
important: advocates don’t need to be developers or
  even full-time team members. they can be designers,
  stakeholders, or external testers that are provided
  with regular builds.
<topic_end>
<topic_start>
stay unique
conforming to expected behaviors doesn’t mean that your app
needs to use default components or styling.
many of the most popular multiplatform apps have very distinct
and opinionated UIs including custom buttons, context menus,
and title bars.
the more you can consolidate styling and behavior across platforms,
the easier development and testing will be.
the trick is to balance creating a unique experience with a
strong identity, while respecting the norms of each platform.
<topic_end>
<topic_start>
common idioms and norms to consider
take a quick look at a few specific norms and idioms
you might want to consider, and how you could approach
them in flutter.
<topic_end>
<topic_start>
scrollbar appearance and behavior
desktop and mobile users expect scrollbars,
but they expect them to behave differently on different platforms.
mobile users expect smaller scrollbars that only appear
while scrolling, whereas desktop users generally expect
omnipresent, larger scrollbars that they can click or drag.
flutter comes with a built-in scrollbar widget that already
has support for adaptive colors and sizes according to the
current platform. the one tweak you might want to make is to
toggle alwaysShown when on a desktop platform:
<code_start>
return scrollbar(
  thumbVisibility: DeviceType.isDesktop,
  controller: _scrollController,
  child: GridView.count(
    controller: _scrollController,
    padding: const EdgeInsets.all(Insets.extraLarge),
    childAspectRatio: 1,
    crossAxisCount: colCount,
    children: listChildren,
  ),
);
<code_end>
this subtle attention to detail can make your app feel more
comfortable on a given platform.
<topic_end>
<topic_start>
multi-select
dealing with multi-select within a list is another area
with subtle differences across platforms:
<code_start>
static bool get isSpanSelectModifierDown =>
    isKeyDown({LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight});
<code_end>
to perform a platform-aware check for control or command,
you can write something like this:
<code_start>
static bool get isMultiSelectModifierDown {
  bool isDown = false;
  if (platform.ismacos) {
    isDown = isKeyDown(
      {logicalkeyboardkey.metaleft, LogicalKeyboardKey.metaRight},
    );
  } else {
    isDown = isKeyDown(
      {logicalkeyboardkey.controlleft, LogicalKeyboardKey.controlRight},
    );
  }
  return isDown;
}
<code_end>
a final consideration for keyboard users is the select all action.
if you have a large list of items of selectable items,
many of your keyboard users will expect that they can use
Control+A to select all the items.
<topic_end>
<topic_start>
touch devices
on touch devices, multi-selection is typically simplified,
with the expected behavior being similar to having the
isMultiSelectModifier down on the desktop.
you can select or deselect items using a single tap,
and will usually have a button to select all or
clear the current selection.
how you handle multi-selection on different devices depends
on your specific use cases, but the important thing is to
make sure that you’re offering each platform the best
interaction model possible.
<topic_end>
<topic_start>
selectable text
a common expectation on the web (and to a lesser extent desktop)
is that most visible text can be selected with the mouse cursor.
when text is not selectable,
users on the web tend to have an adverse reaction.
luckily, this is easy to support with the SelectableText widget:
<code_start>
return const SelectableText('Select me!');
<code_end>
to support rich text, then use TextSpan:
<code_start>
return const SelectableText.rich(
  TextSpan(
    children: [
      TextSpan(text: 'hello'),
      TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
    ],
  ),
);
<code_end>
<topic_end>
<topic_start>
title bars
on modern desktop applications, it’s common to customize
the title bar of your app window, adding a logo for
stronger branding or contextual controls to help save
vertical space in your main UI.
this isn’t supported directly in flutter, but you can use the
bits_dojo package to disable the native title bars,
and replace them with your own.
this package lets you add whatever widgets you want to the
TitleBar because it uses pure flutter widgets under the hood.
this makes it easy to adapt the title bar as you navigate
to different sections of the app.
<topic_end>
<topic_start>
context menus and tooltips
on desktop, there are several interactions that
manifest as a widget shown in an overlay,
but with differences in how they’re triggered, dismissed,
and positioned:
context menu—Typically triggered by a right-click,
a context menu is positioned close to the mouse,
and is dismissed by clicking anywhere,
selecting an option from the menu, or clicking outside it.
Tooltip—Typically triggered by hovering for
200-400ms over an interactive element,
a tooltip is usually anchored to a widget
(as opposed to the mouse position) and is dismissed
when the mouse cursor leaves that widget.
popup panel (also known as flyout)—Similar to a tooltip,
a popup panel is usually anchored to a widget.
the main difference is that panels are most often
shown on a tap event, and they usually don’t hide
themselves when the cursor leaves.
instead, panels are typically dismissed by clicking
outside the panel or by pressing a close or submit button.
to show basic tooltips in flutter,
use the built-in tooltip widget:
<code_start>
return const tooltip(
  message: 'i am a tooltip',
  child: Text('Hover over the text to show a tooltip.'),
);
<code_end>
flutter also provides built-in context menus when editing
or selecting text.
to show more advanced tooltips, popup panels,
or create custom context menus,
you either use one of the available packages,
or build it yourself using a stack or overlay.
some available packages include:
while these controls can be valuable for touch users as accelerators,
they are essential for mouse users. these users expect
to right-click things, edit content in place,
and hover for more information. failing to meet those expectations
can lead to disappointed users, or at least,
a feeling that something isn’t quite right.
<topic_end>
<topic_start>
horizontal button order
on windows, when presenting a row of buttons,
the confirmation button is placed at the start of
the row (left side). on all other platforms,
it’s the opposite. the confirmation button is
placed at the end of the row (right side).
this can be easily handled in flutter using the
TextDirection property on row:
<code_start>
TextDirection btnDirection =
    DeviceType.isWindows ? TextDirection.rtl : TextDirection.ltr;
return row(
  children: [
    const spacer(),
    row(
      textDirection: btnDirection,
      children: [
        DialogButton(
          label: 'cancel',
          onPressed: () => navigator.pop(context, false),
        ),
        DialogButton(
          label: 'ok',
          onPressed: () => navigator.pop(context, true),
        ),
      ],
    ),
  ],
);
<code_end>
<topic_end>
<topic_start>
menu bar
another common pattern on desktop apps is the menu bar.
on windows and linux, this menu lives as part of the chrome title bar,
whereas on macOS, it’s located along the top of the primary screen.
currently, you can specify custom menu bar entries using
a prototype plugin, but it’s expected that this functionality will
eventually be integrated into the main SDK.
it’s worth mentioning that on windows and linux,
you can’t combine a custom title bar with a menu bar.
when you create a custom title bar,
you’re replacing the native one completely,
which means you also lose the integrated native menu bar.
if you need both a custom title bar and a menu bar,
you can achieve that by implementing it in flutter,
similar to a custom context menu.
<topic_end>
<topic_start>
drag and drop
one of the core interactions for both touch-based and
pointer-based inputs is drag and drop. although this
interaction is expected for both types of input,
there are important differences to think about when
it comes to scrolling lists of draggable items.
generally speaking, touch users expect to see drag handles
to differentiate draggable areas from scrollable ones,
or alternatively, to initiate a drag by using a long
press gesture. this is because scrolling and dragging
are both sharing a single finger for input.
mouse users have more input options. they can use a wheel
or scrollbar to scroll, which generally eliminates the need
for dedicated drag handles. if you look at the macOS
finder or windows explorer, you’ll see that they work
this way: you just select an item and start dragging.
in flutter, you can implement drag and drop in many
ways. discussing specific implementations is outside
the scope of this article, but some high level options
are:
use the draggable and DragTarget APIs
directly for a custom look and feel.
hook into onPan gesture events,
and move an object yourself within a parent stack.
use one of the pre-made list packages on pub.dev.
<topic_end>
<topic_start>
educate yourself on basic usability principles
of course, this page doesn’t constitute an exhaustive list
of the things you might consider. the more operating systems,
form factors, and input devices you support,
the more difficult it becomes to spec out every permutation in design.
taking time to learn basic usability principles as a
developer empowers you to make better decisions,
reduces back-and-forth iterations with design during production,
and results in improved productivity with better outcomes.
here are some resources to get you started:
<topic_end>
<topic_start>
update the UI based on orientation
in some situations,
you want to update the display of an app when the user
rotates the screen from portrait mode to landscape mode. for example,
the app might show one item after the next in portrait mode,
yet put those same items side-by-side in landscape mode.
in flutter, you can build different layouts depending
on a given orientation.
in this example, build a list that displays two columns in
portrait mode and three columns in landscape mode using the
following steps:
<topic_end>
<topic_start>
1. build a GridView with two columns
first, create a list of items to work with.
rather than using a normal list,
create a list that displays items in a grid.
for now, create a grid with two columns.
<code_start>
return GridView.count(
  // a list with 2 columns
  crossAxisCount: 2,
  // ...
);
<code_end>
to learn more about working with GridViews,
see the creating a grid list recipe.
<topic_end>
<topic_start>
2. use an OrientationBuilder to change the number of columns
to determine the app’s current orientation, use the
OrientationBuilder widget.
the OrientationBuilder calculates the current orientation by
comparing the width and height available to the parent widget,
and rebuilds when the size of the parent changes.
using the orientation, build a list that displays two columns in portrait
mode, or three columns in landscape mode.
<code_start>
body: OrientationBuilder(
  builder: (context, orientation) {
    return GridView.count(
      // create a grid with 2 columns in portrait mode,
      // or 3 columns in landscape mode.
      crossAxisCount: orientation == orientation.portrait ? 2 : 3,
    );
  },
),
<code_end>
info note
  if you’re interested in the orientation of the screen,
  rather than the amount of space available to the parent,
  use MediaQuery.of(context).orientation instead of an
  OrientationBuilder widget.
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const appTitle = 'orientation demo';
    return const MaterialApp(
      title: appTitle,
      home: OrientationList(
        title: appTitle,
      ),
    );
  }
}
class OrientationList extends StatelessWidget {
  final string title;
  const OrientationList({super.key, required this.title});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: text(title)),
      body: OrientationBuilder(
        builder: (context, orientation) {
          return GridView.count(
            // create a grid with 2 columns in portrait mode, or 3 columns in
            // landscape mode.
            crossAxisCount: orientation == orientation.portrait ? 2 : 3,
            // generate 100 widgets that display their index in the list.
            children: list.generate(100, (index) {
              return center(
                child: text(
                  'item $index',
                  style: Theme.of(context).textTheme.displayLarge,
                ),
              );
            }),
          );
        },
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
locking device orientation
in the previous section, you learned 
how to adapt the app UI to device orientation changes.
flutter also allows you to specify the orientations your app supports 
using the values of DeviceOrientation. you can either:
in the application main() method,
call SystemChrome.setPreferredOrientations()
with the list of preferred orientations that your app supports.
to lock the device to a single orientation, 
you can pass a list with a single item.
for a list of all the possible values, check out DeviceOrientation.
<code_start>
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
  runApp(const MyApp());
}
<code_end>
<topic_end>
<topic_start>
use themes to share colors and font styles
info note
  this recipe uses flutter’s support for material 3 and
  the google_fonts package. as of the flutter 3.16 release,
  material 3 is flutter’s default theme.
to share colors and font styles throughout an app, use themes.
you can define app-wide themes.
you can extend a theme to change a theme style for one component.
each theme defines the colors, type style, and other parameters
applicable for the type of material component.
flutter applies styling in the following order:
after you define a theme, use it within your own widgets.
flutter’s material widgets use your theme to set the background
colors and font styles for app bars, buttons, checkboxes, and more.
<topic_end>
<topic_start>
create an app theme
to share a theme across your entire app, set the theme property
to your MaterialApp constructor.
this property takes a ThemeData instance.
as of the flutter 3.16 release, material 3 is flutter’s
default theme.
if you don’t specify a theme in the constructor,
flutter creates a default theme for you.
<code_start>
MaterialApp(
  title: appName,
  theme: ThemeData(
    useMaterial3: true,
    // define the default brightness and colors.
    colorScheme: ColorScheme.fromSeed(
      seedColor: colors.purple,
      // ···
      brightness: brightness.dark,
    ),
    // define the default `texttheme`. use this to specify the default
    // text styling for headlines, titles, bodies of text, and more.
    textTheme: TextTheme(
      displayLarge: const TextStyle(
        fontSize: 72,
        fontWeight: FontWeight.bold,
      ),
      // ···
      titleLarge: GoogleFonts.oswald(
        fontSize: 30,
        fontStyle: FontStyle.italic,
      ),
      bodyMedium: GoogleFonts.merriweather(),
      displaySmall: GoogleFonts.pacifico(),
    ),
  ),
  home: const MyHomePage(
    title: appName,
  ),
);
<code_end>
most instances of ThemeData set values for the following two properties. these properties affect the entire app.
to learn what colors, fonts, and other properties, you can define,
check out the ThemeData documentation.
<topic_end>
<topic_start>
apply a theme
to apply your new theme, use the theme.of(context) method
when specifying a widget’s styling properties.
these can include, but are not limited to, style and color.
the theme.of(context) method looks up the widget tree and retrieves
the nearest theme in the tree.
if you have a standalone theme, that’s applied.
if not, flutter applies the app’s theme.
in the following example, the container constructor uses this technique to set its color.
<code_start>
container(
  padding: const EdgeInsets.symmetric(
    horizontal: 12,
    vertical: 12,
  ),
  color: Theme.of(context).colorScheme.primary,
  child: text(
    'text with a background color',
    // ···
    style: Theme.of(context).textTheme.bodyMedium!.copyWith(
          color: Theme.of(context).colorScheme.onPrimary,
        ),
  ),
),
<code_end>
<topic_end>
<topic_start>
override a theme
to override the overall theme in part of an app,
wrap that section of the app in a theme widget.
you can override a theme in two ways:
<topic_end>
<topic_start>
set a unique ThemeData instance
if you want a component of your app to ignore the overall theme,
create a ThemeData instance.
pass that instance to the theme widget.
<code_start>
theme(
  // create a unique theme with `themedata`.
  data: ThemeData(
    colorScheme: ColorScheme.fromSeed(
      seedColor: colors.pink,
    ),
  ),
  child: FloatingActionButton(
    onPressed: () {},
    child: const Icon(Icons.add),
  ),
);
<code_end>
<topic_end>
<topic_start>
extend the parent theme
instead of overriding everything, consider extending the parent theme.
to extend a theme, use the copyWith() method.
<code_start>
theme(
  // find and extend the parent theme using `copywith`.
  // to learn more, check out the section on `theme.of`.
  data: Theme.of(context).copyWith(
    colorScheme: ColorScheme.fromSeed(
      seedColor: colors.pink,
    ),
  ),
  child: const FloatingActionButton(
    onPressed: null,
    child: Icon(Icons.add),
  ),
);
<code_end>
<topic_end>
<topic_start>
watch a video on theme
to learn more, watch this short widget of the week video on the theme widget:
<topic_end>
<topic_start>
try an interactive example
<code_start>
import 'package:flutter/material.dart';
// include the google fonts package to provide more text format options
// https://pub.dev/packages/google_fonts
import 'package:google_fonts/google_fonts.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const appName = 'custom themes';
    return MaterialApp(
      title: appName,
      theme: ThemeData(
        useMaterial3: true,
        // define the default brightness and colors.
        colorScheme: ColorScheme.fromSeed(
          seedColor: colors.purple,
          // TRY THIS: change to "brightness.light"
          //           and see that all colors change
          //           to better contrast a light background.
          brightness: brightness.dark,
        ),
        // define the default `texttheme`. use this to specify the default
        // text styling for headlines, titles, bodies of text, and more.
        textTheme: TextTheme(
          displayLarge: const TextStyle(
            fontSize: 72,
            fontWeight: FontWeight.bold,
          ),
          // TRY THIS: change one of the GoogleFonts
          //           to "lato", "poppins", or "lora".
          //           the title uses "titlelarge"
          //           and the middle text uses "bodymedium".
          titleLarge: GoogleFonts.oswald(
            fontSize: 30,
            fontStyle: FontStyle.italic,
          ),
          bodyMedium: GoogleFonts.merriweather(),
          displaySmall: GoogleFonts.pacifico(),
        ),
      ),
      home: const MyHomePage(
        title: appName,
      ),
    );
  }
}
class MyHomePage extends StatelessWidget {
  final string title;
  const MyHomePage({super.key, required this.title});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(title,
            style: Theme.of(context).textTheme.titleLarge!.copyWith(
                  color: Theme.of(context).colorScheme.onSecondary,
                )),
        backgroundColor: Theme.of(context).colorScheme.secondary,
      ),
      body: center(
        child: container(
          padding: const EdgeInsets.symmetric(
            horizontal: 12,
            vertical: 12,
          ),
          color: Theme.of(context).colorScheme.primary,
          child: text(
            'text with a background color',
            // TRY THIS: change the text value
            //           or change the Theme.of(context).textTheme
            //           to "displaylarge" or "displaysmall".
            style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                  color: Theme.of(context).colorScheme.onPrimary,
                ),
          ),
        ),
      ),
      floatingActionButton: theme(
        data: Theme.of(context).copyWith(
          // TRY THIS: change the seedColor to "colors.red" or
          //           "colors.blue".
          colorScheme: ColorScheme.fromSeed(
            seedColor: colors.pink,
            brightness: brightness.dark,
          ),
        ),
        child: FloatingActionButton(
          onPressed: () {},
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
material design for flutter
material design is an open-source design system built
and supported by google designers and developers.
the latest version, material 3, enables personal,
adaptive, and expressive experiences—from dynamic color
and enhanced accessibility, to foundations for
large screen layouts, and design tokens.
warning warning
  as of the flutter 3.16 release, material 3 is
  enabled by default. for now, you can opt out
  of material 3 by setting the useMaterial3 property
  to false. but be aware that the useMaterial3
  property and support for material 2
  will eventually be deprecated according to
  flutter’s deprecation policy.
for most flutter widgets, upgrading to material 3
is seamless. but some widgets couldn’t be
updated—entirely new implementations were needed,
such as NavigationBar.
you must make these changes to your code manually.
until your app is entirely updated,
the UI might look or act a bit strange.
you can find the entirely new material components by
visiting the affected widgets page.
explore the updated components, typography, color system,
and elevation support with the
interactive material 3 demo:
<topic_end>
<topic_start>
more information
to learn more about material design and flutter,
check out:
<topic_end>
<topic_start>
migrate to material 3
<topic_end>
<topic_start>
summary
the material library has been updated to match the material 3 design spec.
changes include new components and component themes, updated component visuals,
and much more. many of these updates are seamless. you’ll see the new version
of an affected widget when recompiling your app against the 3.16 (or later)
release. but some manual work is also required to complete the migration.
<topic_end>
<topic_start>
migration guide
prior to the 3.16 release, you could opt in to the material 3 changes by
setting the useMaterial3 flag to true. as of the flutter 3.16 release
(november 2023), useMaterial3 is true by default.
by the way, you can revert to material 2 behavior in your app by setting the
useMaterial3 to false. however, this is just a temporary solution. the
useMaterial3 flag and the material 2 implementation will eventually be
removed as part of flutter’s deprecation policy.
<topic_end>
<topic_start>
colors
the default values for ThemeData.colorScheme are updated to match
the material 3 design spec.
the ColorScheme.fromSeed constructor generates a ColorScheme
derived from the given seedColor. the colors generated by this
constructor are designed to work well together and meet contrast
requirements for accessibility in the material 3 design system.
when updating to the 3.16 release, your UI might look a little strange
without the correct ColorScheme. to fix this, migrate to the
ColorScheme generated from the ColorScheme.fromSeed constructor.
code before migration:
code after migration:
to generate a content-based dynamic color scheme, use the
ColorScheme.fromImageProvider static method. for an example of generating a
color scheme, check out the ColorScheme from a network image sample.
changes to flutter material 3 include a new background color.
ColorScheme.surfaceTint indicates an elevated widget.
some widgets use different colors.
to return your app’s UI to its previous behavior (which we don’t recommend):
code before migration:
code after migration:
the ColorScheme.surfaceTint value indicates a component’s elevation in
material 3. some widgets might use both surfaceTint and shadowColor to
indicate elevation (for example, card and ElevatedButton) and others might
only use surfaceTint to indicate elevation (such as AppBar).
to return to the widget’s previous behavior, set, set colors.transparent
to ColorScheme.surfaceTint in the theme. to differentiate a widget’s shadow
from the content (when it has no shadow), set the ColorScheme.shadow color to
the shadowColor property in the widget theme without a default shadow color.
code before migration:
code after migration:
the ElevatedButton now styles itself with a new combination of colors.
previously, when the useMaterial3 flag was set to false, ElevatedButton
styled itself with ColorScheme.primary for the background and
ColorScheme.onPrimary for the foreground. to achieve the same visuals, switch
to the new FilledButton widget without the elevation changes or drop shadow.
code before migration:
code after migration:
<topic_end>
<topic_start>
typography
the default values for ThemeData.textTheme are updated to match the
material 3 defaults. changes include updated font size, font weight, letter
spacing, and line height. for more details, check out the TextTheme
documentation.
as shown in the following example, prior to the 3.16 release, when a text
widget with a long string using TextTheme.bodyLarge in a constrained layout
wrapped the text into two lines. however, the 3.16 release wraps the text into
three lines. if you must achieve the previous behavior, adjust the text style
and, if necessary, the letter spacing.
code before migration:
code after migration:
<topic_end>
<topic_start>
components
some components couldn’t merely be updated to match the material 3 design spec
but needed a whole new implementation. such components require manual migration
since the flutter SDK doesn’t know what, exactly, you want.
replace the material 2 style BottomNavigationBar widget with the new
NavigationBar widget. it’s slightly taller, contains pill-shaped
navigation indicators, and uses new color mappings.
code before migration:
code after migration:
check out the complete sample on
migrating from BottomNavigationBar to NavigationBar.
replace the drawer widget with NavigationDrawer, which provides
pill-shaped navigation indicators, rounded corners, and new color mappings.
code before migration:
code after migration:
check out the complete sample on migrating from drawer to NavigationDrawer.
material 3 introduces medium and large app bars that display a larger headline
before scrolling. instead of a drop shadow, ColorScheme.surfaceTint color
is used create a separation from the content when scrolling.
the following code demonstrates how to implement the medium app bar:
there are now two types of TabBar widgets: primary and secondary.
secondary tabs are used within a content area to further separate
related content and establish hierarchy. check out the TabBar.secondary
example.
the new TabBar.tabAlignment property specifies the horizontal alignment
of the tabs.
the following sample shows how to modify tab alignment in a scrollable TabBar:
SegmentedButton, an updated version of ToggleButtons,
uses fully rounded corners, differs in layout height and
size, and uses a dart set to determine selected items.
code before migration:
code after migration:
check out the complete sample on
migrating from ToggleButtons to SegmentedButton.
<topic_end>
<topic_start>
new components
<topic_end>
<topic_start>
timeline
in stable release: 3.16
<topic_end>
<topic_start>
references
documentation:
API documentation:
relevant issues:
relevant PRs:
<topic_end>
<topic_start>
text
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
flutter's fonts and typography
typography covers the style and appearance of
type or fonts: it specifies how heavy the font is,
the slant of the font, the spacing between
the letters, and other visual aspects of the text.
all fonts are not created the same. fonts are a huge
topic and beyond the scope of this site, however,
this page discusses flutter’s support for variable
and static fonts.
<topic_end>
<topic_start>
variable fonts
variable fonts (also called OpenType fonts),
allow you to control pre-defined aspects of text styling.
variable fonts support specific axes, such as width,
weight, slant (to name a few).
the user can select any value along the continuous axis
when specifying the type.
however, the font must first define what axes are available,
and that isn’t always easy to figure out. if you are using
a google font, you can learn what axes are available using
the type tester feature, described in the next section.
<topic_end>
<topic_start>
using the google fonts type tester
the google fonts site offers both variable and static fonts.
use the type tester to learn more about its variable fonts.
in real time, move the slider on any of the axes to
see how it affects the font. when programming a variable font,
use the FontVariation class to modify the font’s design axes.
the FontVariation class conforms to the
OpenType font variables spec.
<topic_end>
<topic_start>
static fonts
google fonts also contains static fonts. as with variable fonts,
you need to know how the font is designed to know what options
are available to you.
once again, the google fonts site can help.
<topic_end>
<topic_start>
using the google fonts site
use the font’s details page to learn more about its static fonts.
use the following API to programmatically alter a static font
(but remember that this only works if the font was designed
to support the feature):
a FontFeature corresponds to an OpenType feature tag
and can be thought of as a boolean flag to enable or disable
a feature of a given font.
the following example is for CSS, but illustrates the concept:
<topic_end>
<topic_start>
other resources
the following video shows you some of the capabilities
of flutter’s typography and combines it with the material
and cupertino look and feel (depending on the platform
the app runs on), animation, and custom fragment shaders:
prototyping beautiful designs with flutter
to read one engineer’s experience
customizing variable fonts and animating them as they
morph (and was the basis for the above video),
check out playful typography with flutter,
a free article on medium. the associated example also
uses a custom shader.
<topic_end>
<topic_start>
use a custom font
<topic_end>
<topic_start>
what you’ll learn
although android and iOS offer high quality system fonts,
designers want support for custom fonts.
you might have a custom-built font from a designer,
or perhaps you downloaded a font from google fonts.
a typeface is the collection of glyphs or shapes that comprise
a given style of lettering.
a font is one representation of that typeface at a given weight or variation.
roboto is a typeface and roboto bold is a font.
flutter lets you apply a custom font across an entire app or to individual widgets.
this recipe creates an app that uses custom fonts with the following steps.
you don’t need to follow each step as you go. 
the guide offers completed example files at the end.
info note
this guide makes the following presumptions:
<topic_end>
<topic_start>
choose a font
your choice of font should be more than a preference.
consider which file formats work with flutter and
how the font could affect design options and app performance.
<topic_end>
<topic_start>
pick a supported font format
flutter supports the following font formats:
flutter does not support fonts in the web open font format,
.woff and .woff2, on desktop platforms.
<topic_end>
<topic_start>
choose fonts for their specific benefits
few sources agree on what a font file type is or which uses less space.
the key difference between font file types involves how the format 
encodes the glyphs in the file.
most TrueType and OpenType font files have similar capabilities as they
borrowed from each other as the formats and fonts improved over time.
which font you should use depends on the following considerations.
research what options a given font offers,
like more than one weight or style per font file,
variable font capability,
the availability of multiple font files for a multiple font weights,
or more than one width per font.
choose the typeface or font family that meets the design needs of your app.
to learn how to get direct access to over 1,000 open-sourced font families,
  check out the google_fonts package.
to learn about another approach to using custom fonts that allows you to
  re-use one font over multiple projects,
  check out export fonts from a package.
<topic_end>
<topic_start>
import the font files
to work with a font, import its font files into your flutter project.
to import font files, perform the following steps.
if necessary, to match the remaining steps in this guide,
change the name of your flutter app to custom_fonts.
navigate to the root of your flutter project.
create a fonts directory at the root of your flutter project.
move or copy the font files in a fonts or assets
folder at the root of your flutter project.
the resulting folder structure should resemble the following:
<topic_end>
<topic_start>
declare the font in the pubspec.yaml file
after you’ve downloaded a font,
include a font definition in the pubspec.yaml file.
this font definition also specifies which font file should be used to
render a given weight or style in your app.
<topic_end>
<topic_start>
define fonts in the pubspec.yaml file
to add font files to your flutter app, complete the following steps.
open the pubspec.yaml file at the root of your flutter project.
paste the following YAML block after the flutter declaration.
this pubspec.yaml file defines the italic style for the
raleway font family as the Raleway-Italic.ttf font file.
when you set style: TextStyle(fontStyle: FontStyle.italic),
flutter swaps Raleway-Regular with Raleway-Italic.
the family value sets the name of the typeface.
you use this name in the fontFamily property of a TextStyle object.
the value of an asset is a relative path from the pubspec.yaml file
to the font file.
these files contain the outlines for the glyphs in the font.
when building the app,
flutter includes these files in the app’s asset bundle.
<topic_end>
<topic_start>
include font files for each font
different typefaces implement font files in different ways.
if you need a typeface with a variety of font weights and styles,
choose and import font files that represent that variety.
when you import a font file that doesn’t include either multiple fonts
within it or variable font capabilities,
don’t use the style or weight property to adjust how they display.
if you do use those properties on a regular font file,
flutter attempts to simulate the look.
the visual result will look quite different from using the correct font file.
<topic_end>
<topic_start>
set styles and weights with font files
when you declare which font files represent styles or weights of a font,
you can apply the style or weight properties.
<topic_end>
<topic_start>
set font weight
the weight property specifies the weight of the outlines in
the file as an integer multiple of 100, between 100 and 900.
these values correspond to the FontWeight and can be used in the
fontWeight property of a TextStyle object.
in the pubspec.yaml shown in this guide,
you defined RobotoMono-Bold as the 700 weight of the font family.
to use the RobotoMono-Bold font that you added to your app, 
set fontWeight to FontWeight.w700 in your TextStyle widget.
if hadn’t added RobotoMono-Bold to your app,
flutter attempts to make the font look bold.
the text then might appear to be somewhat darker.
you can’t use the weight property to override the weight of the font.
you can’t set RobotoMono-Bold to any other weight than 700.
if you set TextStyle(fontFamily: 'robotomono', fontWeight: FontWeight.w900),
the displayed font would still render as however bold RobotoMono-Bold looks.
<topic_end>
<topic_start>
set font style
the style property specifies whether the glyphs in the font file display as
either italic or normal.
these values correspond to the FontStyle.
you can use these styles in the fontStyle property
of a TextStyle object.
in the pubspec.yaml shown in this guide,
you defined Raleway-Italic as being in the italic style. 
to use the Raleway-Italic font that you added to your app, 
set style: TextStyle(fontStyle: FontStyle.italic).
flutter swaps Raleway-Regular with Raleway-Italic when rendering.
if hadn’t added Raleway-Italic to your app,
flutter attempts to make the font look italic.
the text then might appear to be leaning to the right.
you can’t use the style property to override the glyphs of a font.
if you set TextStyle(fontFamily: 'raleway', fontStyle: FontStyle.normal),
the displayed font would still render as italic.
the regular style of an italic font is italic.
<topic_end>
<topic_start>
set a font as the default
to apply a font to text, you can set the font as the app’s default font
in its theme.
to set a default font, set the fontFamily property in the app’s theme.
match the fontFamily value to the family name declared in the
pubspec.yaml file.
the result would resemble the following code.
<code_start>
return MaterialApp(
  title: 'custom fonts',
  // set raleway as the default app font.
  theme: ThemeData(fontFamily: 'raleway'),
  home: const MyHomePage(),
);
<code_end>
to learn more about themes,
check out the using themes to share colors and font styles recipe.
<topic_end>
<topic_start>
set the font in a specific widget
to apply the font to a specific widget like a text widget,
provide a TextStyle to the widget.
for this guide, 
try to apply the RobotoMono font to a single text widget.
match the fontFamily value to the family name declared in the
pubspec.yaml file.
the result would resemble the following code.
<code_start>
child: text(
  'roboto mono sample',
  style: TextStyle(fontFamily: 'robotomono'),
),
<code_end>
error important
  if a TextStyle object specifies a weight or style without a
  corresponding font file, the engine uses a generic file for the font
  and attempts to extrapolate outlines for the requested weight and style.
avoid relying on this capability. import the proper font file instead.
<topic_end>
<topic_start>
try the complete example
<topic_end>
<topic_start>
download fonts
download the raleway and RobotoMono font files from google fonts.
<topic_end>
<topic_start>
update the pubspec.yaml file
open the pubspec.yaml file at the root of your flutter project.
replace its contents with the following YAML.
<topic_end>
<topic_start>
use this main.dart file
open the main.dart file in the lib/ directory of your flutter project.
replace its contents with the following dart code.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'custom fonts',
      // set raleway as the default app font.
      theme: ThemeData(fontFamily: 'raleway'),
      home: const MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      // the AppBar uses the app-default raleway font.
      appBar: AppBar(title: const Text('Custom fonts')),
      body: const center(
        // this text widget uses the RobotoMono font.
        child: text(
          'roboto mono sample',
          style: TextStyle(fontFamily: 'robotomono'),
        ),
      ),
    );
  }
}
<code_end>
the resulting flutter app should display the following screen.
<topic_end>
<topic_start>
export fonts from a package
rather than declaring a font as part of an app,
you can declare a font as part of a separate package.
this is a convenient way to share the same font across
several different projects,
or for coders publishing their packages to pub.dev.
this recipe uses the following steps:
info note
  check out the google_fonts package for direct access
  to almost 1000 open-sourced font families.
<topic_end>
<topic_start>
1. add a font to a package
to export a font from a package, you need to import the font files into the
lib folder of the package project. you can place font files directly in the
lib folder or in a subdirectory, such as lib/fonts.
in this example, assume you’ve got a flutter library called
awesome_package with fonts living in a lib/fonts folder.
<topic_end>
<topic_start>
2. add the package and fonts to the app
now you can use the fonts in the package by
updating the pubspec.yaml in the app’s root directory.
<topic_end>
<topic_start>
add the package to the app
to add the awesome_package package as a dependency,
run flutter pub add:
<topic_end>
<topic_start>
declare the font assets
now that you’ve imported the package, tell flutter where to
find the fonts from the awesome_package.
to declare package fonts, prefix the path to the font with
packages/awesome_package.
this tells flutter to look in the lib folder
of the package for the font.
<topic_end>
<topic_start>
3. use the font
use a TextStyle to change the appearance of text.
to use package fonts, declare which font you’d like to use and
which package the font belongs to.
<code_start>
child: text(
  'using the raleway font from the awesome_package',
  style: TextStyle(
    fontFamily: 'raleway',
  ),
),
<code_end>
<topic_end>
<topic_start>
complete example
<topic_end>
<topic_start>
fonts
the raleway and RobotoMono fonts were downloaded from
google fonts.
<topic_end>
<topic_start>
pubspec.yaml
<topic_end>
<topic_start>
main.dart
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'package fonts',
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      // the AppBar uses the app-default font.
      appBar: AppBar(title: const Text('Package fonts')),
      body: const center(
        // this text widget uses the raleway font.
        child: text(
          'using the raleway font from the awesome_package',
          style: TextStyle(
            fontFamily: 'raleway',
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
custom drawing and graphics
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
writing and using fragment shaders
info note
  both the skia and impeller backends support writing a
  custom shader. except where noted, the same
  instructions apply to both.
custom shaders can be used to provide rich graphical effects
beyond those provided by the flutter SDK.
a shader is a program authored in a small,
dart-like language, known as GLSL,
and executed on the user’s GPU.
custom shaders are added to a flutter project
by listing them in the pubspec.yaml file,
and obtained using the FragmentProgram API.
<topic_end>
<topic_start>
adding shaders to an application
shaders, in the form of GLSL files with the .frag extension,
must be declared in the shaders section of your project’s pubspec.yaml file.
the flutter command-line tool compiles the shader
to its appropriate backend format,
and generates its necessary runtime metadata.
the compiled shader is then included in the application just like an asset.
when running in debug mode,
changes to a shader program trigger recompilation
and update the shader during hot reload or hot restart.
shaders from packages are added to a project
with packages/$pkgname prefixed to the shader program’s name
(where $pkgname is the name of the package).
<topic_end>
<topic_start>
loading shaders at runtime
to load a shader into a FragmentProgram object at runtime,
use the FragmentProgram.fromAsset constructor.
the asset’s name is the same as the path to the shader
given in the pubspec.yaml file.
the FragmentProgram object can be used to create
one or more FragmentShader instances.
a FragmentShader object represents a fragment program
along with a particular set of uniforms (configuration parameters).
the available uniforms depends on how the shader was defined.
<topic_end>
<topic_start>
canvas API
fragment shaders can be used with most canvas APIs
by setting paint.shader.
for example, when using Canvas.drawRect
the shader is evaluated for all fragments within the rectangle.
for an API like Canvas.drawPath with a stroked path,
the shader is evaluated for all fragments within the stroked line.
some APIs, such as Canvas.drawImage, ignore the value of the shader.
<topic_end>
<topic_start>
authoring shaders
fragment shaders are authored as GLSL source files.
by convention, these files have the .frag extension.
(flutter doesn’t support vertex shaders,
which would have the .vert extension.)
any GLSL version from 460 down to 100 is supported,
though some available features are restricted.
the rest of the examples in this document use version 460 core.
shaders are subject to the following limitations
when used with flutter:
<topic_end>
<topic_start>
uniforms
a fragment program can be configured by defining
uniform values in the GLSL shader source
and then setting these values in dart for
each fragment shader instance.
floating point uniforms with the GLSL types
float, vec2, vec3, and vec4
are set using the FragmentShader.setFloat method.
GLSL sampler values, which use the sampler2D type,
are set using the FragmentShader.setImageSampler method.
the correct index for each uniform value is determined by the order
that the uniform values are defined in the fragment program.
for data types composed of multiple floats, such as a vec4,
you must call FragmentShader.setFloat once for each value.
for example, given the following uniforms declarations in a GLSL fragment program:
the corresponding dart code to initialize these uniform values is as follows:
observe that the indices used with FragmentShader.setFloat
do not count the sampler2D uniform.
this uniform is set separately with FragmentShader.setImageSampler,
with the index starting over at 0.
any float uniforms that are left uninitialized will default to 0.0.
<topic_end>
<topic_start>
current position
the shader has access to a varying value that contains the local coordinates for
the particular fragment being evaluated. use this feature to compute
effects that depend on the current position, which can be accessed by
importing the flutter/runtime_effect.glsl library and calling the
FlutterFragCoord function. for example:
the value returned from FlutterFragCoord is distinct from gl_FragCoord.
gl_FragCoord provides the screen space coordinates and should generally be
avoided to ensure that shaders are consistent across backends.
when targeting a skia backend,
the calls to gl_FragCoord are rewritten to access local
coordinates but this rewriting isn’t possible with impeller.
<topic_end>
<topic_start>
colors
there isn’t a built-in data type for colors.
instead they are commonly represented as a vec4
with each component corresponding to one of the RGBA
color channels.
the single output fragColor expects that the color value
is normalized to be in the range of 0.0 to 1.0
and that it has premultiplied alpha.
this is different than typical flutter colors which use
a 0-255 value encoding and have unpremultipled alpha.
<topic_end>
<topic_start>
samplers
a sampler provides access to a dart:ui image object.
this image can be acquired either from a decoded image
or from part of the application using
Scene.toImageSync or Picture.toImageSync.
by default, the image uses
TileMode.clamp to determine how values outside
of the range of [0, 1] behave.
customization of the tile mode is not
supported and needs to be emulated in the shader.
<topic_end>
<topic_start>
performance considerations
when targeting the skia backend,
loading the shader might be expensive since it
must be compiled to the appropriate
platform-specific shader at runtime.
if you intend to use one or more shaders during an animation,
consider precaching the fragment program objects before
starting the animation.
you can reuse a FragmentShader object across frames;
this is more efficient than creating a new
FragmentShader for each frame.
for a more detailed guide on writing performant shaders,
check out writing efficient shaders on GitHub.
<topic_end>
<topic_start>
other resources
for more information, here are a few resources.
<topic_end>
<topic_start>
add interactivity to your flutter app
<topic_end>
<topic_start>
what you'll learn
how do you modify your app to make it react to user input?
in this tutorial, you’ll add interactivity to an app that
contains only non-interactive widgets.
specifically, you’ll modify an icon to make it tappable
by creating a custom stateful widget that manages two
stateless widgets.
the building layouts tutorial showed you how to create
the layout for the following screenshot.
when the app first launches, the star is solid red,
indicating that this lake has previously been favorited.
the number next to the star indicates that 41
people have favorited this lake. after completing this tutorial,
tapping the star removes its favorited status,
replacing the solid star with an outline and
decreasing the count. tapping again favorites the lake,
drawing a solid star and increasing the count.
to accomplish this, you’ll create a single custom widget
that includes both the star and the count,
which are themselves widgets. tapping the star changes state
for both widgets, so the same widget should manage both.
you can get right to touching the code in
step 2: subclass StatefulWidget.
if you want to try different ways of managing state,
skip to managing state.
<topic_end>
<topic_start>
stateful and stateless widgets
a widget is either stateful or stateless. if a widget can
change—when a user interacts with it,
for example—it’s stateful.
a stateless widget never changes.
icon, IconButton, and text are
examples of stateless widgets. stateless widgets
subclass StatelessWidget.
a stateful widget is dynamic: for example,
it can change its appearance in response to events
triggered by user interactions or when it receives data.
checkbox, radio, slider,
InkWell, form, and TextField
are examples of stateful widgets. stateful widgets
subclass StatefulWidget.
a widget’s state is stored in a state object,
separating the widget’s state from its appearance.
the state consists of values that can change, like a
slider’s current value or whether a checkbox is checked.
when the widget’s state changes,
the state object calls setState(),
telling the framework to redraw the widget.
<topic_end>
<topic_start>
creating a stateful widget
<topic_end>
<topic_start>
what's the point?
in this section, you’ll create a custom stateful widget.
you’ll replace two stateless widgets—the solid red
star and the numeric count next to it—with a single
custom stateful widget that manages a row with two
children widgets: an IconButton and text.
implementing a custom stateful widget requires creating two classes:
this section shows you how to build a stateful widget,
called FavoriteWidget, for the lakes app.
after setting up, your first step is choosing how state is
managed for FavoriteWidget.
<topic_end>
<topic_start>
step 0: get ready
if you’ve already built the app in the
building layouts tutorial,
skip to the next section.
once you have a connected and enabled device,
or you’ve launched the iOS simulator
(part of the flutter install) or the
android emulator (part of the android studio
install), you are good to go!
<topic_end>
<topic_start>
step 1: decide which object manages the widget’s state
a widget’s state can be managed in several ways,
but in our example the widget itself,
FavoriteWidget, will manage its own state.
in this example, toggling the star is an isolated
action that doesn’t affect the parent widget or the rest of
the UI, so the widget can handle its state internally.
learn more about the separation of widget and state,
and how state might be managed, in managing state.
<topic_end>
<topic_start>
step 2: subclass StatefulWidget
the FavoriteWidget class manages its own state,
so it overrides createState() to create a state
object. the framework calls createState()
when it wants to build the widget.
in this example, createState() returns an
instance of _FavoriteWidgetState,
which you’ll implement in the next step.
<code_start>
class FavoriteWidget extends StatefulWidget {
  const FavoriteWidget({super.key});
  @override
  State<FavoriteWidget> createState() => _FavoriteWidgetState();
}
<code_end>
info note
  members or classes that start with an underscore
  (_) are private. for more information,
  see libraries and imports, a section in the
  dart language documentation.
<topic_end>
<topic_start>
step 3: subclass state
the _FavoriteWidgetState class stores the mutable data
that can change over the lifetime of the widget.
when the app first launches, the UI displays a solid
red star, indicating that the lake has “favorite” status,
along with 41 likes. these values are stored in the
_isFavorited and _favoriteCount fields:
<code_start>
class _FavoriteWidgetState extends State<FavoriteWidget> {
  bool _isFavorited = true;
  int _favoriteCount = 41;
  // ···
}
<code_end>
the class also defines a build() method,
which creates a row containing a red IconButton,
and text.  you use IconButton (instead of icon)
because it has an onPressed property that defines
the callback function (_togglefavorite) for handling a tap.
you’ll define the callback function next.
<code_start>
class _FavoriteWidgetState extends State<FavoriteWidget> {
  // ···
  @override
  widget build(BuildContext context) {
    return row(
      mainAxisSize: MainAxisSize.min,
      children: [
        container(
          padding: const EdgeInsets.all(0),
          child: IconButton(
            padding: const EdgeInsets.all(0),
            alignment: Alignment.centerRight,
            icon: (_isfavorited
                ? const Icon(Icons.star)
                : const Icon(Icons.star_border)),
            color: colors.red[500],
            onPressed: _toggleFavorite,
          ),
        ),
        SizedBox(
          width: 18,
          child: SizedBox(
            child: Text('$_favoriteCount'),
          ),
        ),
      ],
    );
  }
}
<code_end>
lightbulb tip
  placing the text in a SizedBox and setting its
  width prevents a discernible “jump” when the text changes
  between the values of 40 and 41 — a jump would
  otherwise occur because those values have different widths.
the _toggleFavorite() method, which is called when the
IconButton is pressed, calls setState().
calling setState() is critical, because this
tells the framework that the widget’s state has
changed and that the widget should be redrawn.
the function argument to setState() toggles the
UI between these two states:
<code_start>
void _toggleFavorite() {
  setState(() {
    if (_isfavorited) {
      _favoriteCount -= 1;
      _isFavorited = false;
    } else {
      _favoriteCount += 1;
      _isFavorited = true;
    }
  });
}
<code_end>
<topic_end>
<topic_start>
step 4: plug the stateful widget into the widget tree
add your custom stateful widget to the widget tree in
the app’s build() method. first, locate the code that
creates the icon and text, and delete it.
in the same location, create the stateful widget:
that’s it! when you hot reload the app,
the star icon should now respond to taps.
<topic_end>
<topic_start>
problems?
if you can’t get your code to run, look in your
IDE for possible errors.  debugging flutter apps might help.
if you still can’t find the problem,
check your code against the interactive lakes example on GitHub.
if you still have questions, refer to any one of the developer
community channels.
the rest of this page covers several ways a widget’s state can
be managed, and lists other available interactive widgets.
<topic_end>
<topic_start>
managing state
<topic_end>
<topic_start>
what's the point?
who manages the stateful widget’s state? the widget itself?
the parent widget?  both? another object?
the answer is… it depends. there are several valid ways
to make your widget interactive. you, as the widget designer,
make the decision based on how you expect your widget to be used.
here are the most common ways to manage state:
how do you decide which approach to use?
the following principles should help you decide:
if the state in question is user data,
for example the checked or unchecked
mode of a checkbox, or the position of a slider,
then the state is best managed by the parent widget.
if the state in question is aesthetic,
for example an animation, then the
state is best managed by the widget itself.
if in doubt, start by managing state in the parent widget.
we’ll give examples of the different ways of managing state
by creating three simple examples: TapboxA, TapboxB,
and TapboxC. the examples all work similarly—each
creates a container that, when tapped, toggles between a
green or grey box. the _active boolean determines the
color: green for active or grey for inactive.
these examples use GestureDetector to capture activity
on the container.
<topic_end>
<topic_start>
the widget manages its own state
sometimes it makes the most sense for the widget
to manage its state internally. for example,
ListView automatically scrolls when its
content exceeds the render box. most developers
using ListView don’t want to manage ListView’s
scrolling behavior, so ListView itself manages its scroll offset.
the _TapboxAState class:
<code_start>
import 'package:flutter/material.dart';
// TapboxA manages its own state.
//------------------------- TapboxA ----------------------------------
class TapboxA extends StatefulWidget {
  const TapboxA({super.key});
  @override
  State<TapboxA> createState() => _TapboxAState();
}
class _TapboxAState extends State<TapboxA> {
  bool _active = false;
  void _handleTap() {
    setState(() {
      _active = !_active;
    });
  }
  @override
  widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
          color: _active ? Colors.lightGreen[700] : colors.grey[600],
        ),
        child: center(
          child: text(
            _active ? 'active' : 'inactive',
            style: const TextStyle(fontSize: 32, color: colors.white),
          ),
        ),
      ),
    );
  }
}
//------------------------- MyApp ----------------------------------
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'flutter demo',
      home: scaffold(
        appBar: AppBar(
          title: const Text('Flutter demo'),
        ),
        body: const center(
          child: TapboxA(),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
the parent widget manages the widget’s state
often it makes the most sense for the parent widget
to manage the state and tell its child widget when to update.
for example, IconButton allows you to treat
an icon as a tappable button. IconButton is a
stateless widget because we decided that the parent
widget needs to know whether the button has been tapped,
so it can take appropriate action.
in the following example, TapboxB exports its state
to its parent through a callback. because TapboxB
doesn’t manage any state, it subclasses StatelessWidget.
the ParentWidgetState class:
the TapboxB class:
<code_start>
import 'package:flutter/material.dart';
// ParentWidget manages the state for TapboxB.
//------------------------ ParentWidget --------------------------------
class ParentWidget extends StatefulWidget {
  const ParentWidget({super.key});
  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
  bool _active = false;
  void _handleTapboxChanged(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }
  @override
  widget build(BuildContext context) {
    return SizedBox(
      child: TapboxB(
        active: _active,
        onChanged: _handleTapboxChanged,
      ),
    );
  }
}
//------------------------- TapboxB ----------------------------------
class TapboxB extends StatelessWidget {
  const TapboxB({
    super.key,
    this.active = false,
    required this.onChanged,
  });
  final bool active;
  final ValueChanged<bool> onChanged;
  void _handleTap() {
    onChanged(!active);
  }
  @override
  widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
          color: active ? Colors.lightGreen[700] : colors.grey[600],
        ),
        child: center(
          child: text(
            active ? 'active' : 'inactive',
            style: const TextStyle(fontSize: 32, color: colors.white),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
a mix-and-match approach
for some widgets, a mix-and-match approach makes
the most sense. in this scenario, the stateful widget
manages some of the state, and the parent widget
manages other aspects of the state.
in the TapboxC example, on tap down,
a dark green border appears around the box. on tap up,
the border disappears and the box’s color changes. TapboxC
exports its _active state to its parent but manages its
_highlight state internally. this example has two state
objects, _ParentWidgetState and _TapboxCState.
the _ParentWidgetState object:
the _TapboxCState object:
<code_start>
import 'package:flutter/material.dart';
//---------------------------- ParentWidget ----------------------------
class ParentWidget extends StatefulWidget {
  const ParentWidget({super.key});
  @override
  State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
  bool _active = false;
  void _handleTapboxChanged(bool newValue) {
    setState(() {
      _active = newValue;
    });
  }
  @override
  widget build(BuildContext context) {
    return SizedBox(
      child: TapboxC(
        active: _active,
        onChanged: _handleTapboxChanged,
      ),
    );
  }
}
//----------------------------- TapboxC ------------------------------
class TapboxC extends StatefulWidget {
  const TapboxC({
    super.key,
    this.active = false,
    required this.onChanged,
  });
  final bool active;
  final ValueChanged<bool> onChanged;
  @override
  State<TapboxC> createState() => _TapboxCState();
}
class _TapboxCState extends State<TapboxC> {
  bool _highlight = false;
  void _handleTapDown(TapDownDetails details) {
    setState(() {
      _highlight = true;
    });
  }
  void _handleTapUp(TapUpDetails details) {
    setState(() {
      _highlight = false;
    });
  }
  void _handleTapCancel() {
    setState(() {
      _highlight = false;
    });
  }
  void _handleTap() {
    widget.onChanged(!widget.active);
  }
  @override
  widget build(BuildContext context) {
    // this example adds a green border on tap down.
    // on tap up, the square changes to the opposite state.
    return GestureDetector(
      onTapDown: _handleTapDown, // handle the tap events in the order that
      onTapUp: _handleTapUp, // they occur: down, up, tap, cancel
      onTap: _handleTap,
      onTapCancel: _handleTapCancel,
      child: container(
        width: 200,
        height: 200,
        decoration: BoxDecoration(
          color: widget.active ? Colors.lightGreen[700] : colors.grey[600],
          border: _highlight
              ? border.all(
                  color: colors.teal[700]!,
                  width: 10,
                )
              : null,
        ),
        child: center(
          child: text(widget.active ? 'active' : 'inactive',
              style: const TextStyle(fontSize: 32, color: colors.white)),
        ),
      ),
    );
  }
}
<code_end>
an alternate implementation might have exported the highlight
state to the parent while keeping the active state internal,
but if you asked someone to use that tap box,
they’d probably complain that it doesn’t make much sense.
the developer cares whether the box is active.
the developer probably doesn’t care how the highlighting
is managed, and prefers that the tap box handles those
details.
<topic_end>
<topic_start>
other interactive widgets
flutter offers a variety of buttons and similar interactive widgets.
most of these widgets implement the material design guidelines,
which define a set of components with an opinionated UI.
if you prefer, you can use GestureDetector to build
interactivity into any custom widget.
you can find examples of GestureDetector in
managing state. learn more about the GestureDetector
in handle taps, a recipe in the flutter cookbook.
lightbulb tip
  flutter also provides a set of iOS-style widgets called
  cupertino.
when you need interactivity, it’s easiest to use one of
the prefabricated widgets. here’s a partial list:
<topic_end>
<topic_start>
standard widgets
<topic_end>
<topic_start>
material components
<topic_end>
<topic_start>
resources
the following resources might help when adding interactivity
to your app.
gestures, a section in the flutter cookbook.
<topic_end>
<topic_start>
taps, drags, and other gestures
this document explains how to listen for, and respond to,
gestures in flutter.
examples of gestures include taps, drags, and scaling.
the gesture system in flutter has two separate layers.
the first layer has raw pointer events that describe
the location and movement of pointers (for example,
touches, mice, and styli) across the screen.
the second layer has gestures that describe semantic
actions that consist of one or more pointer movements.
<topic_end>
<topic_start>
pointers
pointers represent raw data about the user’s interaction
with the device’s screen.
there are four types of pointer events:
on pointer down, the framework does a hit test on your app
to determine which widget exists at the location where the
pointer contacted the screen. the pointer down event
(and subsequent events for that pointer) are then dispatched
to the innermost widget found by the hit test.
from there, the events bubble up the tree and are dispatched
to all the widgets on the path from the innermost
widget to the root of the tree. there is no mechanism for
canceling or stopping pointer events from being dispatched further.
to listen to pointer events directly from the widgets layer, use a
listener widget. however, generally,
consider using gestures (as discussed below) instead.
<topic_end>
<topic_start>
gestures
gestures represent semantic actions (for example, tap, drag,
and scale) that are recognized from multiple individual pointer
events, potentially even multiple individual pointers.
gestures can dispatch multiple events, corresponding to the
lifecycle of the gesture (for example, drag start,
drag update, and drag end):
tap
double tap
long press
vertical drag
horizontal drag
pan
<topic_end>
<topic_start>
adding gesture detection to widgets
to listen to gestures from the widgets layer,
use a GestureDetector.
info note
  to learn more, watch this short
  widget of the week video on the GestureDetector widget:
if you’re using material components,
many of those widgets already respond to taps or gestures.
for example, IconButton and TextButton
respond to presses (taps), and ListView
responds to swipes to trigger scrolling.
if you aren’t using those widgets, but you want the
“ink splash” effect on a tap, you can use InkWell.
<topic_end>
<topic_start>
gesture disambiguation
at a given location on screen,
there might be multiple gesture detectors.
for example:
all of these gesture detectors listen to the stream
of pointer events as they flow past and attempt to recognize
specific gestures. the GestureDetector widget decides
which gestures to attempt to recognize based on which of its
callbacks are non-null.
when there is more than one gesture recognizer for a given
pointer on the screen, the framework disambiguates which
gesture the user intends by having each recognizer join
the gesture arena. the gesture arena determines which
gesture wins using the following rules:
at any time, a recognizer can eliminate itself and leave the
arena. if there’s only one recognizer left in the arena,
that recognizer wins.
at any time, a recognizer can declare itself the winner,
causing all of the remaining recognizers to lose.
for example, when disambiguating horizontal and vertical dragging,
both recognizers enter the arena when they receive the pointer
down event. the recognizers observe the pointer move events.
if the user moves the pointer more than a certain number of
logical pixels horizontally, the horizontal recognizer declares
the win and the gesture is interpreted as a horizontal drag.
similarly, if the user moves more than a certain number of logical
pixels vertically, the vertical recognizer declares itself the winner.
the gesture arena is beneficial when there is only a horizontal
(or vertical) drag recognizer. in that case, there is only one
recognizer in the arena and the horizontal drag is recognized
immediately, which means the first pixel of horizontal movement
can be treated as a drag and the user won’t need to wait for
further gesture disambiguation.
<topic_end>
<topic_start>
handle taps
you not only want to display information to users,
you want users to interact with your app.
use the GestureDetector widget to respond
to fundamental actions, such as tapping and dragging.
info note
  to learn more, watch this short widget of the week video on the GestureDetector widget:
this recipe shows how to make a custom button that shows
a snackbar when tapped with the following steps:
<code_start>
// the GestureDetector wraps the button.
GestureDetector(
  // when the child is tapped, show a snackbar.
  onTap: () {
    const snackBar = SnackBar(content: Text('Tap'));
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  },
  // the custom button
  child: container(
    padding: const EdgeInsets.all(12),
    decoration: BoxDecoration(
      color: Colors.lightBlue,
      borderRadius: BorderRadius.circular(8),
    ),
    child: const Text('My button'),
  ),
)
<code_end>
<topic_end>
<topic_start>
notes
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'gesture demo';
    return const MaterialApp(
      title: title,
      home: MyHomePage(title: title),
    );
  }
}
class MyHomePage extends StatelessWidget {
  final string title;
  const MyHomePage({super.key, required this.title});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(title),
      ),
      body: const center(
        child: MyButton(),
      ),
    );
  }
}
class MyButton extends StatelessWidget {
  const MyButton({super.key});
  @override
  widget build(BuildContext context) {
    // the GestureDetector wraps the button.
    return GestureDetector(
      // when the child is tapped, show a snackbar.
      onTap: () {
        const snackBar = SnackBar(content: Text('Tap'));
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      },
      // the custom button
      child: container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.lightBlue,
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Text('My button'),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
drag outside an app
you might want to implement
drag and drop somewhere in your app.
you have a couple potential approaches
that you can take. one directly uses
flutter widgets and the other uses a package
(super_drag_and_drop), available on pub.dev.
<topic_end>
<topic_start>
create draggable widgets within your app
if you want to implement drag and drop within
your application, you can use the draggable
widget. for insight into this approach, see
the drag a UI element within an app recipe.
an advantage of using draggable and DragTarget is
that you can supply dart code to decide whether to accept a drop.
for more information, check out the
draggable widget of the week video.
<topic_end>
<topic_start>
implement drag and drop between apps
if you want to implement drag and drop within
your application and also between your
application and another (possibly non-Flutter) app,
check out the super_drag_and_drop package.
to avoid implementing two styles of drag and drop,
one for drags outside of the app and another for
dragging inside the app,
you can supply local data to the package to
perform drags within your app.
another difference between this approach and
using draggable directly,
is that you must tell the package up front
what data your app accepts because the platform
APIs need a synchronous response, which doesn’t
allow an asynchronous response from the framework.
an advantage of using this approach is that it
works across desktop, mobile, and web.
<topic_end>
<topic_start>
drag a UI element
drag and drop is a common mobile app interaction.
as the user long presses (sometimes called touch & hold)
on a widget, another widget appears beneath the
user’s finger, and the user drags the widget to a
final location and releases it.
in this recipe, you’ll build a drag-and-drop interaction
where the user long presses on a choice of food,
and then drags that food to the picture of the customer who
is paying for it.
the following animation shows the app’s behavior:
this recipe begins with a prebuilt list of menu items and
a row of customers.
the first step is to recognize a long press
and display a draggable photo of a menu item.
<topic_end>
<topic_start>
press and drag
flutter provides a widget called LongPressDraggable
that provides the exact behavior that you need to begin
a drag-and-drop interaction. a LongPressDraggable
widget recognizes when a long press occurs and then 
displays a new widget near the user’s finger.
as the user drags, the widget follows the user’s finger.
LongPressDraggable gives you full control over the 
widget that the user drags.
each menu list item is displayed with a custom
MenuListItem widget.
<code_start>
MenuListItem(
  name: item.name,
  price: item.formattedTotalItemPrice,
  photoProvider: item.imageProvider,
)
<code_end>
wrap the MenuListItem widget with a LongPressDraggable widget.
<code_start>
LongPressDraggable<Item>(
  data: item,
  dragAnchorStrategy: pointerDragAnchorStrategy,
  feedback: DraggingListItem(
    dragKey: _draggableKey,
    photoProvider: item.imageProvider,
  ),
  child: MenuListItem(
    name: item.name,
    price: item.formattedTotalItemPrice,
    photoProvider: item.imageProvider,
  ),
);
<code_end>
in this case, when the user long presses on the
MenuListItem widget, the LongPressDraggable
widget displays a DraggingListItem.
this DraggingListItem displays a photo of the
selected food item, centered beneath 
the user’s finger.
the dragAnchorStrategy property is set to
pointerDragAnchorStrategy.
this property value instructs LongPressDraggable
to base the DraggableListItem’s position on the 
user’s finger. as the user moves a finger,
the DraggableListItem moves with it.
dragging and dropping is of little use if no information
is transmitted when the item is dropped.
for this reason, LongPressDraggable takes a data parameter. 
in this case, the type of data is item,
which holds information about the 
food menu item that the user pressed on.
the data associated with a LongPressDraggable
is sent to a special widget called DragTarget,
where the user releases the drag gesture.
you’ll implement the drop behavior next.
<topic_end>
<topic_start>
drop the draggable
the user can drop a LongPressDraggable wherever they choose,
but dropping the draggable has no effect unless it’s dropped
on top of a DragTarget. when the user drops a draggable on
top of a DragTarget widget, the DragTarget widget 
can either accept or reject the data from the draggable.
in this recipe, the user should drop a menu item on a
CustomerCart widget to add the menu item to the user’s cart.
<code_start>
CustomerCart(
  hasItems: customer.items.isNotEmpty,
  highlighted: candidateItems.isNotEmpty,
  customer: customer,
);
<code_end>
wrap the CustomerCart widget with a DragTarget widget.
<code_start>
DragTarget<Item>(
  builder: (context, candidateItems, rejectedItems) {
    return CustomerCart(
      hasItems: customer.items.isNotEmpty,
      highlighted: candidateItems.isNotEmpty,
      customer: customer,
    );
  },
  onAcceptWithDetails: (details) {
    _itemDroppedOnCustomerCart(
      item: details.data,
      customer: customer,
    );
  },
)
<code_end>
the DragTarget displays your existing widget and
also coordinates with LongPressDraggable to recognize
when the user drags a draggable on top of the DragTarget.
the DragTarget also recognizes when the user drops
a draggable on top of the DragTarget widget.
when the user drags a draggable on the DragTarget widget,
candidateItems contains the data items that the user is dragging.
this draggable allows you to change what your widget looks
like when the user is dragging over it. in this case,
the customer widget turns red whenever any items are dragged above the 
DragTarget widget. the red visual appearance is configured with the 
highlighted property within the CustomerCart widget.
when the user drops a draggable on the DragTarget widget,
the onAcceptWithDetails callback is invoked. this is when you get
to decide whether or not to accept the data that was dropped.
in this case, the item is always accepted and processed. 
you might choose to inspect the incoming item to make a
different decision.
notice that the type of item dropped on DragTarget
must match the type of the item dragged from LongPressDraggable.
if the types are not compatible, then 
the onAcceptWithDetails method isn’t invoked.
with a DragTarget widget configured to accept your
desired data, you can now transmit data from one part
of your UI to another by dragging and dropping.
in the next step,
you update the customer’s cart with the dropped menu item.
<topic_end>
<topic_start>
add a menu item to a cart
each customer is represented by a customer object,
which maintains a cart of items and a price total.
<code_start>
class customer {
  customer({
    required this.name,
    required this.imageProvider,
    List<Item>? items,
  }) : items = items ?? [];
  final string name;
  final ImageProvider imageProvider;
  final List<Item> items;
  string get formattedTotalItemPrice {
    final totalPriceCents =
        items.fold<int>(0, (prev, item) => prev + item.totalPriceCents);
    return '\$${(totalpricecents / 100.0).tostringasfixed(2)}';
  }
}
<code_end>
the CustomerCart widget displays the customer’s photo,
name, total, and item count based on a customer instance.
to update a customer’s cart when a menu item is dropped,
add the dropped item to the associated customer object.
<code_start>
void _itemDroppedOnCustomerCart({
  required item item,
  required customer customer,
}) {
  setState(() {
    customer.items.add(item);
  });
}
<code_end>
the _itemDroppedOnCustomerCart method is invoked in
onAcceptWithDetails() when the user drops a menu item on a
CustomerCart widget. by adding the dropped item to the 
customer object, and invoking setState() to cause a
layout update, the UI refreshes with the new customer’s
price total and item count.
congratulations! you have a drag-and-drop interaction
that adds food items to a customer’s shopping cart.
<topic_end>
<topic_start>
interactive example
run the app:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: ExampleDragAndDrop(),
      debugShowCheckedModeBanner: false,
    ),
  );
}
const List<Item> _items = [
  item(
    name: 'spinach pizza',
    totalPriceCents: 1299,
    uid: '1',
    imageProvider: NetworkImage('https://flutter'
        '.dev/docs/cookbook/img-files/effects/split-check/food1.jpg'),
  ),
  item(
    name: 'veggie delight',
    totalPriceCents: 799,
    uid: '2',
    imageProvider: NetworkImage('https://flutter'
        '.dev/docs/cookbook/img-files/effects/split-check/food2.jpg'),
  ),
  item(
    name: 'chicken parmesan',
    totalPriceCents: 1499,
    uid: '3',
    imageProvider: NetworkImage('https://flutter'
        '.dev/docs/cookbook/img-files/effects/split-check/food3.jpg'),
  ),
];
@immutable
class ExampleDragAndDrop extends StatefulWidget {
  const ExampleDragAndDrop({super.key});
  @override
  State<ExampleDragAndDrop> createState() => _ExampleDragAndDropState();
}
class _ExampleDragAndDropState extends State<ExampleDragAndDrop>
    with TickerProviderStateMixin {
  final List<Customer> _people = [
    customer(
      name: 'makayla',
      imageProvider: const NetworkImage('https://flutter'
          '.dev/docs/cookbook/img-files/effects/split-check/avatar1.jpg'),
    ),
    customer(
      name: 'nathan',
      imageProvider: const NetworkImage('https://flutter'
          '.dev/docs/cookbook/img-files/effects/split-check/avatar2.jpg'),
    ),
    customer(
      name: 'emilio',
      imageProvider: const NetworkImage('https://flutter'
          '.dev/docs/cookbook/img-files/effects/split-check/avatar3.jpg'),
    ),
  ];
  final GlobalKey _draggableKey = GlobalKey();
  void _itemDroppedOnCustomerCart({
    required item item,
    required customer customer,
  }) {
    setState(() {
      customer.items.add(item);
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      backgroundColor: const Color(0xFFF7F7F7),
      appBar: _buildAppBar(),
      body: _buildContent(),
    );
  }
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      iconTheme: const IconThemeData(color: Color(0xFFF64209)),
      title: text(
        'order food',
        style: Theme.of(context).textTheme.headlineMedium?.copyWith(
              fontSize: 36,
              color: const Color(0xFFF64209),
              fontWeight: FontWeight.bold,
            ),
      ),
      backgroundColor: const Color(0xFFF7F7F7),
      elevation: 0,
    );
  }
  widget _buildContent() {
    return stack(
      children: [
        SafeArea(
          child: column(
            children: [
              expanded(
                child: _buildMenuList(),
              ),
              _buildPeopleRow(),
            ],
          ),
        ),
      ],
    );
  }
  widget _buildMenuList() {
    return ListView.separated(
      padding: const EdgeInsets.all(16),
      itemCount: _items.length,
      separatorBuilder: (context, index) {
        return const SizedBox(
          height: 12,
        );
      },
      itemBuilder: (context, index) {
        final item = _items[index];
        return _buildMenuItem(
          item: item,
        );
      },
    );
  }
  widget _buildMenuItem({
    required item item,
  }) {
    return LongPressDraggable<Item>(
      data: item,
      dragAnchorStrategy: pointerDragAnchorStrategy,
      feedback: DraggingListItem(
        dragKey: _draggableKey,
        photoProvider: item.imageProvider,
      ),
      child: MenuListItem(
        name: item.name,
        price: item.formattedTotalItemPrice,
        photoProvider: item.imageProvider,
      ),
    );
  }
  widget _buildPeopleRow() {
    return container(
      padding: const EdgeInsets.symmetric(
        horizontal: 8,
        vertical: 20,
      ),
      child: row(
        children: _people.map(_buildPersonWithDropZone).toList(),
      ),
    );
  }
  widget _buildPersonWithDropZone(Customer customer) {
    return expanded(
      child: padding(
        padding: const EdgeInsets.symmetric(
          horizontal: 6,
        ),
        child: DragTarget<Item>(
          builder: (context, candidateItems, rejectedItems) {
            return CustomerCart(
              hasItems: customer.items.isNotEmpty,
              highlighted: candidateItems.isNotEmpty,
              customer: customer,
            );
          },
          onAcceptWithDetails: (details) {
            _itemDroppedOnCustomerCart(
              item: details.data,
              customer: customer,
            );
          },
        ),
      ),
    );
  }
}
class CustomerCart extends StatelessWidget {
  const CustomerCart({
    super.key,
    required this.customer,
    this.highlighted = false,
    this.hasItems = false,
  });
  final customer customer;
  final bool highlighted;
  final bool hasItems;
  @override
  widget build(BuildContext context) {
    final textColor = highlighted ? colors.white : colors.black;
    return transform.scale(
      scale: highlighted ? 1.075 : 1.0,
      child: material(
        elevation: highlighted ? 8 : 4,
        borderRadius: BorderRadius.circular(22),
        color: highlighted ? const Color(0xFFF64209) : colors.white,
        child: padding(
          padding: const EdgeInsets.symmetric(
            horizontal: 12,
            vertical: 24,
          ),
          child: column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ClipOval(
                child: SizedBox(
                  width: 46,
                  height: 46,
                  child: image(
                    image: customer.imageProvider,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              const SizedBox(height: 8),
              text(
                customer.name,
                style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      color: textColor,
                      fontWeight:
                          hasItems ? FontWeight.normal : FontWeight.bold,
                    ),
              ),
              visibility(
                visible: hasItems,
                maintainState: true,
                maintainAnimation: true,
                maintainSize: true,
                child: column(
                  children: [
                    const SizedBox(height: 4),
                    text(
                      customer.formattedTotalItemPrice,
                      style: Theme.of(context).textTheme.bodySmall!.copyWith(
                            color: textColor,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    const SizedBox(height: 4),
                    text(
                      '${customer.items.length} item${customer.items.length != 1 ? 's' : ''}',
                      style: Theme.of(context).textTheme.titleMedium!.copyWith(
                            color: textColor,
                            fontSize: 12,
                          ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
class MenuListItem extends StatelessWidget {
  const MenuListItem({
    super.key,
    this.name = '',
    this.price = '',
    required this.photoProvider,
    this.isDepressed = false,
  });
  final string name;
  final string price;
  final ImageProvider photoProvider;
  final bool isDepressed;
  @override
  widget build(BuildContext context) {
    return material(
      elevation: 12,
      borderRadius: BorderRadius.circular(20),
      child: padding(
        padding: const EdgeInsets.all(12),
        child: row(
          mainAxisSize: MainAxisSize.max,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: SizedBox(
                width: 120,
                height: 120,
                child: center(
                  child: AnimatedContainer(
                    duration: const duration(milliseconds: 100),
                    curve: Curves.easeInOut,
                    height: isDepressed ? 115 : 120,
                    width: isDepressed ? 115 : 120,
                    child: image(
                      image: photoProvider,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(width: 30),
            expanded(
              child: column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  text(
                    name,
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontSize: 18,
                        ),
                  ),
                  const SizedBox(height: 10),
                  text(
                    price,
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                        ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
class DraggingListItem extends StatelessWidget {
  const DraggingListItem({
    super.key,
    required this.dragKey,
    required this.photoProvider,
  });
  final GlobalKey dragKey;
  final ImageProvider photoProvider;
  @override
  widget build(BuildContext context) {
    return FractionalTranslation(
      translation: const offset(-0.5, -0.5),
      child: ClipRRect(
        key: dragKey,
        borderRadius: BorderRadius.circular(12),
        child: SizedBox(
          height: 150,
          width: 150,
          child: opacity(
            opacity: 0.85,
            child: image(
              image: photoProvider,
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }
}
@immutable
class item {
  const item({
    required this.totalPriceCents,
    required this.name,
    required this.uid,
    required this.imageProvider,
  });
  final int totalPriceCents;
  final string name;
  final string uid;
  final ImageProvider imageProvider;
  string get formattedTotalItemPrice =>
      '\$${(totalpricecents / 100.0).tostringasfixed(2)}';
}
class customer {
  customer({
    required this.name,
    required this.imageProvider,
    List<Item>? items,
  }) : items = items ?? [];
  final string name;
  final ImageProvider imageProvider;
  final List<Item> items;
  string get formattedTotalItemPrice {
    final totalPriceCents =
        items.fold<int>(0, (prev, item) => prev + item.totalPriceCents);
    return '\$${(totalpricecents / 100.0).tostringasfixed(2)}';
  }
}
<code_end>
<topic_end>
<topic_start>
add material touch ripples
widgets that follow the material design guidelines display
a ripple animation when tapped.
flutter provides the InkWell
widget to perform this effect.
create a ripple effect using the following steps:
<code_start>
// the InkWell wraps the custom flat button widget.
InkWell(
  // when the user taps the button, show a snackbar.
  onTap: () {
    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
      content: Text('Tap'),
    ));
  },
  child: const padding(
    padding: EdgeInsets.all(12),
    child: Text('Flat button'),
  ),
)
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'inkwell demo';
    return const MaterialApp(
      title: title,
      home: MyHomePage(title: title),
    );
  }
}
class MyHomePage extends StatelessWidget {
  final string title;
  const MyHomePage({super.key, required this.title});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(title),
      ),
      body: const center(
        child: MyButton(),
      ),
    );
  }
}
class MyButton extends StatelessWidget {
  const MyButton({super.key});
  @override
  widget build(BuildContext context) {
    // the InkWell wraps the custom flat button widget.
    return InkWell(
      // when the user taps the button, show a snackbar.
      onTap: () {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text('Tap'),
        ));
      },
      child: const padding(
        padding: EdgeInsets.all(12),
        child: Text('Flat button'),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
implement swipe to dismiss
the “swipe to dismiss” pattern is common in many mobile apps.
for example, when writing an email app,
you might want to allow a user to swipe away
email messages to delete them from a list.
flutter makes this task easy by providing the
dismissible widget.
learn how to implement swipe to dismiss with the following steps:
<topic_end>
<topic_start>
1. create a list of items
first, create a list of items. for detailed
instructions on how to create a list,
follow the working with long lists recipe.
<topic_end>
<topic_start>
create a data source
in this example,
you want 20 sample items to work with.
to keep it simple, generate a list of strings.
<code_start>
final items = List<String>.generate(20, (i) => 'item ${i + 1}');
<code_end>
<topic_end>
<topic_start>
convert the data source into a list
display each item in the list on screen. users won’t
be able to swipe these items away just yet.
<code_start>
ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: text(items[index]),
    );
  },
)
<code_end>
<topic_end>
<topic_start>
2. wrap each item in a dismissible widget
in this step,
give users the ability to swipe an item off the list by using the
dismissible widget.
after the user has swiped away the item,
remove the item from the list and display a snackbar.
in a real app, you might need to perform more complex logic,
such as removing the item from a web service or database.
update the itemBuilder() function to return a dismissible widget:
<code_start>
itemBuilder: (context, index) {
  final item = items[index];
  return dismissible(
    // each dismissible must contain a key. keys allow flutter to
    // uniquely identify widgets.
    key: key(item),
    // provide a function that tells the app
    // what to do after an item has been swiped away.
    onDismissed: (direction) {
      // remove the item from the data source.
      setState(() {
        items.removeAt(index);
      });
      // then show a snackbar.
      ScaffoldMessenger.of(context)
          .showsnackbar(snackbar(content: text('$item dismissed')));
    },
    child: ListTile(
      title: text(item),
    ),
  );
},
<code_end>
<topic_end>
<topic_start>
3. provide “leave behind” indicators
as it stands,
the app allows users to swipe items off the list, but it doesn’t
give a visual indication of what happens when they do.
to provide a cue that items are removed,
display a “leave behind” indicator as they
swipe the item off the screen. in this case,
the indicator is a red background.
to add the indicator,
provide a background parameter to the dismissible.
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
// MyApp is a StatefulWidget. this allows updating the state of the
// widget when an item is removed.
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  MyAppState createState() {
    return MyAppState();
  }
}
class MyAppState extends State<MyApp> {
  final items = List<String>.generate(20, (i) => 'item ${i + 1}');
  @override
  widget build(BuildContext context) {
    const title = 'dismissing items';
    return MaterialApp(
      title: title,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];
            return dismissible(
              // each dismissible must contain a key. keys allow flutter to
              // uniquely identify widgets.
              key: key(item),
              // provide a function that tells the app
              // what to do after an item has been swiped away.
              onDismissed: (direction) {
                // remove the item from the data source.
                setState(() {
                  items.removeAt(index);
                });
                // then show a snackbar.
                ScaffoldMessenger.of(context)
                    .showsnackbar(snackbar(content: text('$item dismissed')));
              },
              // show a red background as the item is swiped away.
              background: container(color: colors.red),
              child: ListTile(
                title: text(item),
              ),
            );
          },
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
input & forms
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
create and style a text field
text fields allow users to type text into an app.
they are used to build forms,
send messages, create search experiences, and more.
in this recipe, explore how to create and style text fields.
flutter provides two text fields:
TextField and TextFormField.
<topic_end>
<topic_start>
TextField
TextField is the most commonly used text input widget.
by default, a TextField is decorated with an underline.
you can add a label, icon, inline hint text, and error text by supplying an
InputDecoration as the decoration
property of the TextField.
to remove the decoration entirely (including the
underline and the space reserved for the label),
set the decoration to null.
<code_start>
TextField(
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    hintText: 'enter a search term',
  ),
),
<code_end>
to retrieve the value when it changes,
see the handle changes to a text field recipe.
<topic_end>
<topic_start>
TextFormField
TextFormField wraps a TextField and integrates it
with the enclosing form.
this provides additional functionality,
such as validation and integration with other
FormField widgets.
<code_start>
TextFormField(
  decoration: const InputDecoration(
    border: UnderlineInputBorder(),
    labelText: 'enter your username',
  ),
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const appTitle = 'form styling demo';
    return MaterialApp(
      title: appTitle,
      home: scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: const MyCustomForm(),
      ),
    );
  }
}
class MyCustomForm extends StatelessWidget {
  const MyCustomForm({super.key});
  @override
  widget build(BuildContext context) {
    return column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <widget>[
        const padding(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
          child: TextField(
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              hintText: 'enter a search term',
            ),
          ),
        ),
        padding(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
          child: TextFormField(
            decoration: const InputDecoration(
              border: UnderlineInputBorder(),
              labelText: 'enter your username',
            ),
          ),
        ),
      ],
    );
  }
}
<code_end>
for more information on input validation, see the
building a form with validation recipe.
<topic_end>
<topic_start>
retrieve the value of a text field
in this recipe,
learn how to retrieve the text a user has entered into a text field
using the following steps:
<topic_end>
<topic_start>
1. create a TextEditingController
to retrieve the text a user has entered into a text field,
create a TextEditingController
and supply it to a TextField or TextFormField.
important: call dispose of the TextEditingController when
  you’ve finished using it. this ensures that you discard any resources
  used by the object.
<code_start>
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds the data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();
  @override
  void dispose() {
    // clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    // fill this out in the next step.
  }
}
<code_end>
<topic_end>
<topic_start>
2. supply the TextEditingController to a TextField
now that you have a TextEditingController, wire it up
to a text field using the controller property:
<code_start>
return TextField(
  controller: myController,
);
<code_end>
<topic_end>
<topic_start>
3. display the current value of the text field
after supplying the TextEditingController to the text field,
begin reading values. use the text()
method provided by the TextEditingController to retrieve the
string that the user has entered into the text field.
the following code displays an alert dialog with the current
value of the text field when the user taps a floating action button.
<code_start>
FloatingActionButton(
  // when the user presses the button, show an alert dialog containing
  // the text that the user has entered into the text field.
  onPressed: () {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          // retrieve the text that the user has entered by using the
          // TextEditingController.
          content: Text(myController.text),
        );
      },
    );
  },
  tooltip: 'show me the value!',
  child: const Icon(Icons.text_fields),
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'retrieve text input',
      home: MyCustomForm(),
    );
  }
}
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds the data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();
  @override
  void dispose() {
    // clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Retrieve text input'),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: TextField(
          controller: myController,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // when the user presses the button, show an alert dialog containing
        // the text that the user has entered into the text field.
        onPressed: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // retrieve the text the that user has entered by using the
                // TextEditingController.
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'show me the value!',
        child: const Icon(Icons.text_fields),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
handle changes to a text field
in some cases, it’s useful to run a callback function every time the text
in a text field changes. for example, you might want to build a search
screen with autocomplete functionality where you want to update the
results as the user types.
how do you run a callback function every time the text changes?
with flutter, you have two options:
<topic_end>
<topic_start>
1. supply an onChanged() callback to a TextField or a TextFormField
the simplest approach is to supply an onChanged() callback to a
TextField or a TextFormField.
whenever the text changes, the callback is invoked.
in this example, print the current value and length of the text field 
to the console every time the text changes.
it’s important to use characters when dealing with user input,
as text may contain complex characters.
this ensures that every character is counted correctly
as they appear to the user.
<code_start>
TextField(
  onChanged: (text) {
    print('First text field: $text (${text.characters.length})');
  },
),
<code_end>
<topic_end>
<topic_start>
2. use a TextEditingController
a more powerful, but more elaborate approach, is to supply a
TextEditingController as the controller
property of the TextField or a TextFormField.
to be notified when the text changes, listen to the controller
using the addListener() method using the following steps:
<topic_end>
<topic_start>
create a TextEditingController
create a TextEditingController:
<code_start>
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // create a text controller. later, use it to retrieve the
  // current value of the TextField.
  final myController = TextEditingController();
  @override
  void dispose() {
    // clean up the controller when the widget is removed from the
    // widget tree.
    myController.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    // fill this out in the next step.
  }
}
<code_end>
info note
  remember to dispose of the TextEditingController when it’s no
  longer needed. this ensures that you discard any resources used
  by the object.
<topic_end>
<topic_start>
connect the TextEditingController to a text field
supply the TextEditingController to either a TextField
or a TextFormField. once you wire these two classes together,
you can begin listening for changes to the text field.
<code_start>
TextField(
  controller: myController,
),
<code_end>
<topic_end>
<topic_start>
create a function to print the latest value
you need a function to run every time the text changes.
create a method in the _MyCustomFormState class that prints
out the current value of the text field.
<code_start>
void _printLatestValue() {
  final text = myController.text;
  print('Second text field: $text (${text.characters.length})');
}
<code_end>
<topic_end>
<topic_start>
listen to the controller for changes
finally, listen to the TextEditingController and call the
_printLatestValue() method when the text changes. use the
addListener() method for this purpose.
begin listening for changes when the
_MyCustomFormState class is initialized,
and stop listening when the _MyCustomFormState is disposed.
<code_start>
@override
void initState() {
  super.initState();
  // start listening to changes.
  myController.addListener(_printLatestValue);
}
<code_end>
<code_start>
@override
void dispose() {
  // clean up the controller when the widget is removed from the widget tree.
  // this also removes the _printLatestValue listener.
  myController.dispose();
  super.dispose();
}
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'retrieve text input',
      home: MyCustomForm(),
    );
  }
}
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // create a text controller and use it to retrieve the current value
  // of the TextField.
  final myController = TextEditingController();
  @override
  void initState() {
    super.initState();
    // start listening to changes.
    myController.addListener(_printLatestValue);
  }
  @override
  void dispose() {
    // clean up the controller when the widget is removed from the widget tree.
    // this also removes the _printLatestValue listener.
    myController.dispose();
    super.dispose();
  }
  void _printLatestValue() {
    final text = myController.text;
    print('Second text field: $text (${text.characters.length})');
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Retrieve text input'),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: column(
          children: [
            TextField(
              onChanged: (text) {
                print('First text field: $text (${text.characters.length})');
              },
            ),
            TextField(
              controller: myController,
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
focus and text fields
when a text field is selected and accepting input,
it is said to have “focus.”
generally, users shift focus to a text field by tapping,
and developers shift focus to a text field programmatically by
using the tools described in this recipe.
managing focus is a fundamental tool for creating forms with an intuitive
flow. for example, say you have a search screen with a text field.
when the user navigates to the search screen,
you can set the focus to the text field for the search term.
this allows the user to start typing as soon as the screen
is visible, without needing to manually tap the text field.
in this recipe, learn how to give the focus
to a text field as soon as it’s visible,
as well as how to give focus to a text field
when a button is tapped.
<topic_end>
<topic_start>
focus a text field as soon as it’s visible
to give focus to a text field as soon as it’s visible,
use the autofocus property.
for more information on handling input and creating text fields,
see the forms section of the cookbook.
<topic_end>
<topic_start>
focus a text field when a button is tapped
rather than immediately shifting focus to a specific text field,
you might need to give focus to a text field at a later point in time.
in the real world, you might also need to give focus to a specific
text field in response to an API call or a validation error.
in this example, give focus to a text field after the user
presses a button using the following steps:
<topic_end>
<topic_start>
1. create a FocusNode
first, create a FocusNode.
use the FocusNode to identify a specific TextField in flutter’s
“focus tree.” this allows you to give focus to the TextField
in the next steps.
since focus nodes are long-lived objects, manage the lifecycle
using a state object. use the following instructions to create
a FocusNode instance inside the initState() method of a
state class, and clean it up in the dispose() method:
<code_start>
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // define the focus node. to manage the lifecycle, create the FocusNode in
  // the initState method, and clean it up in the dispose method.
  late FocusNode myFocusNode;
  @override
  void initState() {
    super.initState();
    myFocusNode = FocusNode();
  }
  @override
  void dispose() {
    // clean up the focus node when the form is disposed.
    myFocusNode.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    // fill this out in the next step.
  }
}
<code_end>
<topic_end>
<topic_start>
2. pass the FocusNode to a TextField
now that you have a FocusNode,
pass it to a specific TextField in the build() method.
<code_start>
@override
widget build(BuildContext context) {
  return TextField(
    focusNode: myFocusNode,
  );
}
<code_end>
<topic_end>
<topic_start>
3. give focus to the TextField when a button is tapped
finally, focus the text field when the user taps a floating
action button. use the requestFocus() method to perform
this task.
<code_start>
FloatingActionButton(
  // when the button is pressed,
  // give focus to the text field using myFocusNode.
  onPressed: () => myFocusNode.requestFocus(),
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'text field focus',
      home: MyCustomForm(),
    );
  }
}
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  State<MyCustomForm> createState() => _MyCustomFormState();
}
// define a corresponding state class.
// this class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
  // define the focus node. to manage the lifecycle, create the FocusNode in
  // the initState method, and clean it up in the dispose method.
  late FocusNode myFocusNode;
  @override
  void initState() {
    super.initState();
    myFocusNode = FocusNode();
  }
  @override
  void dispose() {
    // clean up the focus node when the form is disposed.
    myFocusNode.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Text field focus'),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: column(
          children: [
            // the first text field is focused on as soon as the app starts.
            const TextField(
              autofocus: true,
            ),
            // the second text field is focused on when a user taps the
            // FloatingActionButton.
            TextField(
              focusNode: myFocusNode,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // when the button is pressed,
        // give focus to the text field using myFocusNode.
        onPressed: () => myFocusNode.requestFocus(),
        tooltip: 'focus second text field',
        child: const Icon(Icons.edit),
      ), // this trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
<code_end>
<topic_end>
<topic_start>
build a form with validation
apps often require users to enter information into a text field.
for example, you might require users to log in with an email address
and password combination.
to make apps secure and easy to use, check whether the
information the user has provided is valid. if the user has correctly filled
out the form, process the information. if the user submits incorrect
information, display a friendly error message letting them know what went
wrong.
in this example, learn how to add validation to a form that has
a single text field using the following steps:
<topic_end>
<topic_start>
1. create a form with a GlobalKey
create a form.
the form widget acts as a container for grouping and
validating multiple form fields.
when creating the form, provide a GlobalKey.
this assigns a unique identifier to your form.
it also allows you to validate the form later.
create the form as a StatefulWidget.
this allows you to create a unique GlobalKey<FormState>() once.
you can then store it as a variable and access it at different points.
if you made this a StatelessWidget, you’d need to store this key somewhere.
as it is resource expensive, you wouldn’t want to generate a new
GlobalKey each time you run the build method.
<code_start>
import 'package:flutter/material.dart';
// define a custom form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}
// define a corresponding state class.
// this class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // create a global key that uniquely identifies the form widget
  // and allows validation of the form.
  //
  // note: this is a `globalkey<formstate>`,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  @override
  widget build(BuildContext context) {
    // build a form widget using the _formKey created above.
    return form(
      key: _formKey,
      child: const column(
        children: <widget>[
          // add TextFormFields and ElevatedButton here.
        ],
      ),
    );
  }
}
<code_end>
lightbulb tip
  using a GlobalKey is the recommended way to access a form.
  however, if you have a more complex widget tree,
  you can use the form.of() method to
  access the form within nested widgets.
<topic_end>
<topic_start>
2. add a TextFormField with validation logic
although the form is in place,
it doesn’t have a way for users to enter text.
that’s the job of a TextFormField.
the TextFormField widget renders a material design text field
and can display validation errors when they occur.
validate the input by providing a validator() function to the
TextFormField. if the user’s input isn’t valid,
the validator function returns a string containing
an error message.
if there are no errors, the validator must return null.
for this example, create a validator that ensures the
TextFormField isn’t empty. if it is empty,
return a friendly error message.
<code_start>
TextFormField(
  // the validator receives the text that the user has entered.
  validator: (value) {
    if (value == null || value.isEmpty) {
      return 'please enter some text';
    }
    return null;
  },
),
<code_end>
<topic_end>
<topic_start>
3. create a button to validate and submit the form
now that you have a form with a text field,
provide a button that the user can tap to submit the information.
when the user attempts to submit the form, check if the form is valid.
if it is, display a success message.
if it isn’t (the text field has no content) display the error message.
<code_start>
ElevatedButton(
  onPressed: () {
    // validate returns true if the form is valid, or false otherwise.
    if (_formkey.currentstate!.validate()) {
      // if the form is valid, display a snackbar. in the real world,
      // you'd often call a server or save the information in a database.
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Processing data')),
      );
    }
  },
  child: const Text('Submit'),
),
<code_end>
<topic_end>
<topic_start>
how does this work?
to validate the form, use the _formKey created in
step 1. you can use the _formKey.currentState()
method to access the FormState,
which is automatically created by flutter when building a form.
the FormState class contains the validate() method.
when the validate() method is called, it runs the validator()
function for each text field in the form.
if everything looks good, the validate() method returns true.
if any text field contains errors, the validate() method
rebuilds the form to display any error messages and returns false.
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const appTitle = 'form validation demo';
    return MaterialApp(
      title: appTitle,
      home: scaffold(
        appBar: AppBar(
          title: const Text(appTitle),
        ),
        body: const MyCustomForm(),
      ),
    );
  }
}
// create a form widget.
class MyCustomForm extends StatefulWidget {
  const MyCustomForm({super.key});
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}
// create a corresponding state class.
// this class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // create a global key that uniquely identifies the form widget
  // and allows validation of the form.
  //
  // note: this is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  @override
  widget build(BuildContext context) {
    // build a form widget using the _formKey created above.
    return form(
      key: _formKey,
      child: column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextFormField(
            // the validator receives the text that the user has entered.
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'please enter some text';
              }
              return null;
            },
          ),
          padding(
            padding: const EdgeInsets.symmetric(vertical: 16),
            child: ElevatedButton(
              onPressed: () {
                // validate returns true if the form is valid, or false otherwise.
                if (_formkey.currentstate!.validate()) {
                  // if the form is valid, display a snackbar. in the real world,
                  // you'd often call a server or save the information in a database.
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Processing data')),
                  );
                }
              },
              child: const Text('Submit'),
            ),
          ),
        ],
      ),
    );
  }
}
<code_end>
to learn how to retrieve these values, check out the
retrieve the value of a text field recipe.
<topic_end>
<topic_start>
display a snackbar
it can be useful to briefly inform your users when certain actions
take place. for example, when a user swipes away a message in a list,
you might want to inform them that the message has been deleted.
you might even want to give them an option to undo the action.
in material design, this is the job of a SnackBar.
this recipe implements a snackbar using the following steps:
<topic_end>
<topic_start>
1. create a scaffold
when creating apps that follow the material design guidelines,
give your apps a consistent visual structure.
in this example, display the SnackBar at the bottom of the screen,
without overlapping other important
widgets, such as the FloatingActionButton.
the scaffold widget, from the material library,
creates this visual structure and ensures that important
widgets don’t overlap.
<code_start>
return MaterialApp(
  title: 'snackbar demo',
  home: scaffold(
    appBar: AppBar(
      title: const Text('SnackBar demo'),
    ),
    body: const SnackBarPage(),
  ),
);
<code_end>
<topic_end>
<topic_start>
2. display a SnackBar
with the scaffold in place, display a SnackBar.
first, create a SnackBar, then display it using ScaffoldMessenger.
<code_start>
const snackBar = SnackBar(
  content: Text('Yay! a SnackBar!'),
);
// find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
<code_end>
info note
  to learn more, watch this short widget of the week video on the ScaffoldMessenger widget:
<topic_end>
<topic_start>
3. provide an optional action
you might want to provide an action to the user when
the SnackBar is displayed.
for example, if the user accidentally deletes a message,
they might use an optional action in the SnackBar to recover
the message.
here’s an example of providing
an additional action to the SnackBar widget:
<code_start>
final snackBar = SnackBar(
  content: const Text('Yay! a SnackBar!'),
  action: SnackBarAction(
    label: 'undo',
    onPressed: () {
      // some code to undo the change.
    },
  ),
);
<code_end>
<topic_end>
<topic_start>
interactive example
info note
  in this example, the SnackBar displays when a user taps a button.
  for more information on working with user input,
  see the gestures section of the cookbook.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const SnackBarDemo());
class SnackBarDemo extends StatelessWidget {
  const SnackBarDemo({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'snackbar demo',
      home: scaffold(
        appBar: AppBar(
          title: const Text('SnackBar demo'),
        ),
        body: const SnackBarPage(),
      ),
    );
  }
}
class SnackBarPage extends StatelessWidget {
  const SnackBarPage({super.key});
  @override
  widget build(BuildContext context) {
    return center(
      child: ElevatedButton(
        onPressed: () {
          final snackBar = SnackBar(
            content: const Text('Yay! a SnackBar!'),
            action: SnackBarAction(
              label: 'undo',
              onPressed: () {
                // some code to undo the change.
              },
            ),
          );
          // find the ScaffoldMessenger in the widget tree
          // and use it to show a SnackBar.
          ScaffoldMessenger.of(context).showSnackBar(snackBar);
        },
        child: const Text('Show SnackBar'),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
using actions and shortcuts
this page describes how to bind physical keyboard events to actions in the user
interface. for instance, to define keyboard shortcuts in your application, this
page is for you.
<topic_end>
<topic_start>
overview
for a GUI application to do anything, it has to have actions: users want to tell
the application to do something. actions are often simple functions that
directly perform the action (such as set a value or save a file). in a larger
application, however, things are more complex: the code for invoking the action,
and the code for the action itself might need to be in different places.
shortcuts (key bindings) might need definition at a level that knows nothing
about the actions they invoke.
that’s where flutter’s actions and shortcuts system comes in. it allows
developers to define actions that fulfill intents bound to them. in this
context, an intent is a generic action that the user wishes to perform, and an
intent class instance represents these user intents in flutter. an
intent can be general purpose, fulfilled by different actions in different
contexts. an action can be a simple callback (as in the case of
the CallbackAction) or something more complex that integrates with entire
undo/redo architectures (for example) or other logic.
shortcuts are key bindings that activate by pressing a key or combination
of keys. the key combinations reside in a table with their bound intent. when
the shortcuts widget invokes them, it sends their matching intent to the
actions subsystem for fulfillment.
to illustrate the concepts in actions and shortcuts, this article creates a
simple app that allows a user to select and copy text in a text field using both
buttons and shortcuts.
<topic_end>
<topic_start>
why separate actions from intents?
you might wonder: why not just map a key combination directly to an action?  why
have intents at all? this is because it is useful to have a separation of
concerns between where the key mapping definitions are (often at a high level),
and where the action definitions are (often at a low level), and because it is
important to be able to have a single key combination map to an intended
operation in an app, and have it adapt automatically to whichever action
fulfills that intended operation for the focused context.
for instance, flutter has an ActivateIntent widget that maps each type of
control to its corresponding version of an ActivateAction (and that executes
the code that activates the control). this code often needs fairly private
access to do its work. if the extra layer of indirection that intents provide
didn’t exist, it would be necessary to elevate the definition of the actions to
where the defining instance of the shortcuts widget could see them, causing
the shortcuts to have more knowledge than necessary about which action to
invoke, and to have access to or provide state that it wouldn’t necessarily have
or need otherwise. this allows your code to separate the two concerns to be more
independent.
intents configure an action so that the same action can serve multiple uses. an
example of this is DirectionalFocusIntent, which takes a direction to move
the focus in, allowing the DirectionalFocusAction to know which direction to
move the focus. just be careful: don’t pass state in the intent that applies
to all  invocations of an action: that kind of state should be passed to the
constructor of the action itself, to keep the intent from needing to know
too much.
<topic_end>
<topic_start>
why not use callbacks?
you also might wonder: why not just use a callback instead of an action
object? the main reason is that it’s useful for actions to decide whether they
are enabled by implementing isEnabled. also, it is often helpful if the key
bindings, and the implementation of those bindings, are in different places.
if all you need are callbacks without the flexibility of actions and
shortcuts, you can use the CallbackShortcuts widget:
<code_start>
@override
widget build(BuildContext context) {
  return CallbackShortcuts(
    bindings: <shortcutactivator, VoidCallback>{
      const SingleActivator(LogicalKeyboardKey.arrowUp): () {
        setState(() => count = count + 1);
      },
      const SingleActivator(LogicalKeyboardKey.arrowDown): () {
        setState(() => count = count - 1);
      },
    },
    child: focus(
      autofocus: true,
      child: column(
        children: <widget>[
          const Text('Press the up arrow key to add to the counter'),
          const Text('Press the down arrow key to subtract from the counter'),
          text('count: $count'),
        ],
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
shortcuts
as you’ll see below, actions are useful on their own, but the most common use
case involves binding them to a keyboard shortcut. this is what the shortcuts
widget is for.
it is inserted into the widget hierarchy to define key combinations that
represent the user’s intent when that key combination is pressed. to convert
that intended purpose for the key combination into a concrete action, the
actions widget used to map the intent to an action. for instance, you can
define a SelectAllIntent, and bind it to your own SelectAllAction or to your
CanvasSelectAllAction, and from that one key binding, the system invokes
either one, depending on which part of your application has focus. let’s see how
the key binding part works:
<code_start>
@override
widget build(BuildContext context) {
  return shortcuts(
    shortcuts: <logicalkeyset, intent>{
      LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyA):
          const SelectAllIntent(),
    },
    child: actions(
      dispatcher: LoggingActionDispatcher(),
      actions: <type, Action<Intent>>{
        SelectAllIntent: SelectAllAction(model),
      },
      child: builder(
        builder: (context) => TextButton(
          onPressed: Actions.handler<SelectAllIntent>(
            context,
            const SelectAllIntent(),
          ),
          child: const Text('SELECT ALL'),
        ),
      ),
    ),
  );
}
<code_end>
the map given to a shortcuts widget maps a LogicalKeySet (or a
ShortcutActivator, see note below) to an intent instance. the logical key
set defines a set of one or more keys, and the intent indicates the intended
purpose of the keypress. the shortcuts widget looks up key presses in the map,
to find an intent instance, which it gives to the action’s invoke() method.
info note
ShortcutActivator is a replacement for LogicalKeySet.
  it allows for more flexible and correct activation of shortcuts.
  LogicalKeySet is a ShortcutActivator, of course, but
  there is also SingleActivator, which takes a single key and the
  optional modifiers to be pressed before the key.
  then there is CharacterActivator, which activates a shortcut based on the
  character produced by a key sequence, instead of the logical keys themselves.
  ShortcutActivator is also meant to be subclassed to allow for
  custom ways of activating shortcuts from key events.
<topic_end>
<topic_start>
the ShortcutManager
the shortcut manager, a longer-lived object than the shortcuts widget, passes
on key events when it receives them. it contains the logic for deciding how to
handle the keys, the logic for walking up the tree to find other shortcut
mappings, and maintains a map of key combinations to intents.
while the default behavior of the ShortcutManager is usually desirable, the
shortcuts widget takes a ShortcutManager that you can subclass to customize
its functionality.
for example, if you wanted to log each key that a shortcuts widget handled,
you could make a LoggingShortcutManager:
<code_start>
class LoggingShortcutManager extends ShortcutManager {
  @override
  KeyEventResult handleKeypress(BuildContext context, KeyEvent event) {
    final KeyEventResult result = super.handleKeypress(context, event);
    if (result == KeyEventResult.handled) {
      print('Handled shortcut $event in $context');
    }
    return result;
  }
}
<code_end>
now, every time the shortcuts widget handles a shortcut, it prints out the key
event and relevant context.
<topic_end>
<topic_start>
actions
actions allow for the definition of operations that the application can
perform by invoking them with an intent. actions can be enabled or disabled,
and receive the intent instance that invoked them as an argument to allow
configuration by the intent.
<topic_end>
<topic_start>
defining actions
actions, in their simplest form, are just subclasses of Action<Intent> with an
invoke() method. here’s a simple action that simply invokes a function on the
provided model:
<code_start>
class SelectAllAction extends Action<SelectAllIntent> {
  SelectAllAction(this.model);
  final model model;
  @override
  void invoke(covariant SelectAllIntent intent) => model.selectAll();
}
<code_end>
or, if it’s too much of a bother to create a new class, use a CallbackAction:
<code_start>
CallbackAction(onInvoke: (intent) => model.selectAll());
<code_end>
once you have an action, you add it to your application using the actions
widget, which takes a map of intent types to actions:
<code_start>
@override
widget build(BuildContext context) {
  return actions(
    actions: <type, Action<Intent>>{
      SelectAllIntent: SelectAllAction(model),
    },
    child: child,
  );
}
<code_end>
the shortcuts widget uses the focus widget’s context and actions.invoke to
find which action to invoke. if the shortcuts widget doesn’t find a matching
intent type in the first actions widget encountered, it considers the next
ancestor actions widget, and so on, until it reaches the root of the widget
tree, or finds a matching intent type and invokes the corresponding action.
<topic_end>
<topic_start>
invoking actions
the actions system has several ways to invoke actions.  by far the most common
way is through the use of a shortcuts widget covered in the previous section,
but there are other ways to interrogate the actions subsystem and invoke an
action. it’s possible to invoke actions that are not bound to keys.
for instance, to find an action associated with an intent, you can use:
<code_start>
Action<SelectAllIntent>? selectAll =
    Actions.maybeFind<SelectAllIntent>(context);
<code_end>
this returns an action associated with the SelectAllIntent type if one is
available in the given context.  if one isn’t available, it returns null. if
an associated action should always be available, then use find instead of
maybeFind, which throws an exception when it doesn’t find a matching intent
type.
to invoke the action (if it exists), call:
<code_start>
object? result;
if (selectall != null) {
  result =
      Actions.of(context).invokeAction(selectAll, const SelectAllIntent());
}
<code_end>
combine that into one call with the following:
<code_start>
object? result =
    Actions.maybeInvoke<SelectAllIntent>(context, const SelectAllIntent());
<code_end>
sometimes you want to invoke an action as a
result of pressing a button or another control.
you can do this with the actions.handler function.
if the intent has a mapping to an enabled action,
the actions.handler function creates a handler closure.
however, if it doesn’t have a mapping, it returns null.
this allows the button to be disabled if
there is no enabled action that matches in the context.
<code_start>
@override
widget build(BuildContext context) {
  return actions(
    actions: <type, Action<Intent>>{
      SelectAllIntent: SelectAllAction(model),
    },
    child: builder(
      builder: (context) => TextButton(
        onPressed: Actions.handler<SelectAllIntent>(
          context,
          SelectAllIntent(controller: controller),
        ),
        child: const Text('SELECT ALL'),
      ),
    ),
  );
}
<code_end>
the actions widget only invokes actions when isEnabled(Intent intent)
returns true, allowing the action to decide if the dispatcher should consider it
for invocation.  if the action isn’t enabled, then the actions widget gives
another enabled action higher in the widget hierarchy (if it exists) a chance to
execute.
the previous example uses a builder because actions.handler and
actions.invoke (for example) only finds actions in the provided context, and
if the example passes the context given to the build function, the framework
starts looking above the current widget.  using a builder allows the
framework to find the actions defined in the same build function.
you can invoke an action without needing a BuildContext, but since the
actions widget requires a context to find an enabled action to invoke, you
need to provide one, either by creating your own action instance, or by
finding one in an appropriate context with actions.find.
to invoke the action, pass the action to the invoke method on an
ActionDispatcher, either one you created yourself, or one retrieved from an
existing actions widget using the actions.of(context) method. check whether
the action is enabled before calling invoke. of course, you can also just call
invoke on the action itself, passing an intent, but then you opt out of any
services that an action dispatcher might provide (like logging, undo/redo, and
so on).
<topic_end>
<topic_start>
action dispatchers
most of the time, you just want to invoke an action, have it do its thing, and
forget about it. sometimes, however, you might want to log the executed actions.
this is where replacing the default ActionDispatcher with a custom dispatcher
comes in.  you pass your ActionDispatcher to the actions widget, and it
invokes actions from any actions widgets below that one that doesn’t set a
dispatcher of its own.
the first thing actions does when invoking an action is look up the
ActionDispatcher and pass the action to it for invocation. if there is none,
it creates a default ActionDispatcher that simply invokes the action.
if you want a log of all the actions invoked, however, you can create your own
LoggingActionDispatcher to do the job:
<code_start>
class LoggingActionDispatcher extends ActionDispatcher {
  @override
  object? invokeAction(
    covariant Action<Intent> action,
    covariant intent intent, [
    BuildContext? context,
  ]) {
    print('Action invoked: $action($intent) from $context');
    super.invokeAction(action, intent, context);
    return null;
  }
  @override
  (bool, object?) invokeActionIfEnabled(
    covariant Action<Intent> action,
    covariant intent intent, [
    BuildContext? context,
  ]) {
    print('Action invoked: $action($intent) from $context');
    return super.invokeActionIfEnabled(action, intent, context);
  }
}
<code_end>
then you pass that to your top-level actions widget:
<code_start>
@override
widget build(BuildContext context) {
  return actions(
    dispatcher: LoggingActionDispatcher(),
    actions: <type, Action<Intent>>{
      SelectAllIntent: SelectAllAction(model),
    },
    child: builder(
      builder: (context) => TextButton(
        onPressed: Actions.handler<SelectAllIntent>(
          context,
          const SelectAllIntent(),
        ),
        child: const Text('SELECT ALL'),
      ),
    ),
  );
}
<code_end>
this logs every action as it executes, like so:
<topic_end>
<topic_start>
putting it together
the combination of actions and shortcuts is powerful: you can define generic
intents that map to specific actions at the widget level. here’s a simple app
that illustrates the concepts described above. the app creates a text field that
also has “select all” and “copy to clipboard” buttons next to it. the buttons
invoke actions to accomplish their work. all the invoked actions and
shortcuts are logged.
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// a text field that also has buttons to select all the text and copy the
/// selected text to the clipboard.
class CopyableTextField extends StatefulWidget {
  const CopyableTextField({super.key, required this.title});
  final string title;
  @override
  State<CopyableTextField> createState() => _CopyableTextFieldState();
}
class _CopyableTextFieldState extends State<CopyableTextField> {
  late final TextEditingController controller = TextEditingController();
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return actions(
      dispatcher: LoggingActionDispatcher(),
      actions: <type, Action<Intent>>{
        ClearIntent: ClearAction(controller),
        CopyIntent: CopyAction(controller),
        SelectAllIntent: SelectAllAction(controller),
      },
      child: builder(builder: (context) {
        return scaffold(
          body: center(
            child: row(
              children: <widget>[
                const spacer(),
                expanded(
                  child: TextField(controller: controller),
                ),
                IconButton(
                  icon: const Icon(Icons.copy),
                  onPressed:
                      Actions.handler<CopyIntent>(context, const CopyIntent()),
                ),
                IconButton(
                  icon: const Icon(Icons.select_all),
                  onPressed: Actions.handler<SelectAllIntent>(
                      context, const SelectAllIntent()),
                ),
                const spacer(),
              ],
            ),
          ),
        );
      }),
    );
  }
}
/// a ShortcutManager that logs all keys that it handles.
class LoggingShortcutManager extends ShortcutManager {
  @override
  KeyEventResult handleKeypress(BuildContext context, KeyEvent event) {
    final KeyEventResult result = super.handleKeypress(context, event);
    if (result == KeyEventResult.handled) {
      print('Handled shortcut $event in $context');
    }
    return result;
  }
}
/// an ActionDispatcher that logs all the actions that it invokes.
class LoggingActionDispatcher extends ActionDispatcher {
  @override
  object? invokeAction(
    covariant Action<Intent> action,
    covariant intent intent, [
    BuildContext? context,
  ]) {
    print('Action invoked: $action($intent) from $context');
    super.invokeAction(action, intent, context);
    return null;
  }
}
/// an intent that is bound to ClearAction in order to clear its
/// TextEditingController.
class ClearIntent extends intent {
  const ClearIntent();
}
/// an action that is bound to ClearIntent that clears its
/// TextEditingController.
class ClearAction extends Action<ClearIntent> {
  ClearAction(this.controller);
  final TextEditingController controller;
  @override
  object? invoke(covariant ClearIntent intent) {
    controller.clear();
    return null;
  }
}
/// an intent that is bound to CopyAction to copy from its
/// TextEditingController.
class CopyIntent extends intent {
  const CopyIntent();
}
/// an action that is bound to CopyIntent that copies the text in its
/// TextEditingController to the clipboard.
class CopyAction extends Action<CopyIntent> {
  CopyAction(this.controller);
  final TextEditingController controller;
  @override
  object? invoke(covariant CopyIntent intent) {
    final string selectedString = controller.text.substring(
      controller.selection.baseOffset,
      controller.selection.extentOffset,
    );
    Clipboard.setData(ClipboardData(text: selectedString));
    return null;
  }
}
/// an intent that is bound to SelectAllAction to select all the text in its
/// controller.
class SelectAllIntent extends intent {
  const SelectAllIntent();
}
/// an action that is bound to SelectAllAction that selects all text in its
/// TextEditingController.
class SelectAllAction extends Action<SelectAllIntent> {
  SelectAllAction(this.controller);
  final TextEditingController controller;
  @override
  object? invoke(covariant SelectAllIntent intent) {
    controller.selection = controller.selection.copyWith(
      baseOffset: 0,
      extentOffset: controller.text.length,
      affinity: controller.selection.affinity,
    );
    return null;
  }
}
/// the top level application class.
///
/// shortcuts defined here are in effect for the whole app,
/// although different widgets may fulfill them differently.
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  static const string title = 'shortcuts and actions demo';
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: title,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: shortcuts(
        shortcuts: <logicalkeyset, intent>{
          LogicalKeySet(LogicalKeyboardKey.escape): const ClearIntent(),
          LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyC):
              const CopyIntent(),
          LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyA):
              const SelectAllIntent(),
        },
        child: const CopyableTextField(title: title),
      ),
    );
  }
}
void main() => runApp(const MyApp());
<code_end>
<topic_end>
<topic_start>
understanding flutter's keyboard focus system
this article explains how to control where keyboard input is directed. if you
are implementing an application that uses a physical keyboard, such as most
desktop and web applications, this page is for you. if your app won’t be used
with a physical keyboard, you can skip this.
<topic_end>
<topic_start>
overview
flutter comes with a focus system that directs the keyboard input to a
particular part of an application. in order to do this, users “focus” the input
onto that part of an application by tapping or clicking the desired UI element.
once that happens, text entered with the keyboard flows to that part of the
application until the focus moves to another part of the application.  focus can
also be moved by pressing a particular keyboard shortcut, which is typically
bound to tab, so it is sometimes called “tab traversal”.
this page explores the APIs used to perform these operations on a flutter
application, and how the focus system works. we have noticed that there is some
confusion among developers about how to define and use FocusNode objects.
if that describes your experience, skip ahead to the best practices for
creating FocusNode objects.
<topic_end>
<topic_start>
focus use cases
some examples of situations where you might need to know how to use the focus
system:
<topic_end>
<topic_start>
glossary
below are terms, as flutter uses them, for elements of the focus system. the
various classes that implement some of these concepts are introduced below.
<topic_end>
<topic_start>
FocusNode and FocusScopeNode
the FocusNode and FocusScopeNode objects implement the
mechanics of the focus system. they are long-lived objects (longer than widgets,
similar to render objects) that hold the focus state and attributes so that they
are persistent between builds of the widget tree. together, they form
the focus tree data structure.
they were originally intended to be developer-facing objects used to control
some aspects of the focus system, but over time they have evolved to mostly
implement details of the focus system. in order to prevent breaking existing
applications, they still contain public interfaces for their attributes. but, in
general, the thing for which they are most useful is to act as a relatively
opaque handle, passed to a descendant widget in order to call requestFocus()
on an ancestor widget, which requests that a descendant widget obtain focus.
setting of the other attributes is best managed by a focus or
FocusScope widget, unless you are not using them, or implementing your own
version of them.
<topic_end>
<topic_start>
best practices for creating FocusNode objects
some dos and don’ts around using these objects include:
<topic_end>
<topic_start>
unfocusing
there is an API for telling a node to “give up the focus”, named
FocusNode.unfocus(). while it does remove focus from the node, it is important
to realize that there really is no such thing as “unfocusing” all nodes. if a
node is unfocused, then it must pass the focus somewhere else, since there is
always a primary focus. the node that receives the focus when a node calls
unfocus() is either the nearest FocusScopeNode, or a previously focused node
in that scope, depending upon the disposition argument given to unfocus().
if you would like more control over where the focus goes when you remove it from
a node, explicitly focus another node instead of calling unfocus(), or use the
focus traversal mechanism to find another node with the focusInDirection,
nextFocus, or previousFocus methods on FocusNode.
when calling unfocus(), the disposition argument allows two modes for
unfocusing: UnfocusDisposition.scope and
UnfocusDisposition.previouslyFocusedChild. the default is scope, which gives
the focus to the nearest parent focus scope. this means that if the focus is
thereafter moved to the next node with FocusNode.nextFocus, it starts with the
“first” focusable item in the scope.
the previouslyFocusedChild disposition will search the scope to find the
previously focused child and request focus on it. if there is no previously
focused child, it is equivalent to scope.
beware: if there is no other scope, then focus moves to the root scope node of
  the focus system, FocusManager.rootScope. this is generally not desirable, as
  the root scope doesn’t have a context for the framework to determine which
  node should be focused next. if you find that your application suddenly loses
  the ability to navigate by using focus traversal, this is probably what has
  happened.  to fix it, add a FocusScope as an ancestor to the focus node that
  is requesting the unfocus. the WidgetsApp (from which MaterialApp and
  CupertinoApp are derived) has its own FocusScope, so this should not be an
  issue if you are using those.
<topic_end>
<topic_start>
focus widget
the focus widget owns and manages a focus node, and is the workhorse of the
focus system.  it manages the attaching and detaching of the focus node it owns
from the focus tree, manages the attributes and callbacks of the focus node, and
has static functions to enable discovery of focus nodes attached to the widget
tree.
in its simplest form, wrapping the focus widget around a widget subtree allows
that widget subtree to obtain focus as part of the focus traversal process, or
whenever requestFocus is called on the FocusNode passed to it. when combined
with a gesture detector that calls requestFocus, it can receive focus when
tapped or clicked.
you might pass a FocusNode object to the focus widget to manage, but if you
don’t, it creates its own. the main reason to create your own
FocusNode is to be able to call requestFocus()
on the node to control the focus from a parent widget. most of the other
functionality of a FocusNode is best accessed by changing the attributes of
the focus widget itself.
the focus widget is used in most of flutter’s own controls to implement their
focus functionality.
here is an example showing how to use the focus widget to make a custom
control focusable. it creates a container with text that reacts to receiving the
focus.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  static const string _title = 'focus sample';
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: scaffold(
        appBar: AppBar(title: const text(_title)),
        body: const column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <widget>[mycustomwidget(), MyCustomWidget()],
        ),
      ),
    );
  }
}
class MyCustomWidget extends StatefulWidget {
  const MyCustomWidget({super.key});
  @override
  State<MyCustomWidget> createState() => _MyCustomWidgetState();
}
class _MyCustomWidgetState extends State<MyCustomWidget> {
  color _color = colors.white;
  string _label = 'unfocused';
  @override
  widget build(BuildContext context) {
    return focus(
      onFocusChange: (focused) {
        setState(() {
          _color = focused ? colors.black26 : colors.white;
          _label = focused ? 'focused' : 'unfocused';
        });
      },
      child: center(
        child: container(
          width: 300,
          height: 50,
          alignment: alignment.center,
          color: _color,
          child: text(_label),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
key events
if you wish to listen for key events in a subtree,
set the onKeyEvent attribute of the focus widget to
be a handler that either just listens to the key, or
handles the key and stops its propagation to other widgets.
key events start at the focus node with primary focus.
if that node doesn’t return KeyEventResult.handled from
its onKeyEvent handler, then its parent focus node is given the event.
if the parent doesn’t handle it, it goes to its parent,
and so on, until it reaches the root of the focus tree.
if the event reaches the root of the focus tree without being handled, then
it is returned to the platform to give to
the next native control in the application
(in case the flutter UI is part of a larger native application UI).
events that are handled are not propagated to other flutter widgets,
and they are also not propagated to native widgets.
here’s an example of a focus widget that absorbs every key that
its subtree doesn’t handle, without being able to be the primary focus:
<code_start>
@override
widget build(BuildContext context) {
  return focus(
    onKeyEvent: (node, event) => KeyEventResult.handled,
    canRequestFocus: false,
    child: child,
  );
}
<code_end>
focus key events are processed before text entry events, so handling a key event
when the focus widget surrounds a text field prevents that key from being
entered into the text field.
here’s an example of a widget that won’t allow the letter “a” to be typed into
the text field:
<code_start>
@override
widget build(BuildContext context) {
  return focus(
    onKeyEvent: (node, event) {
      return (event.logicalkey == LogicalKeyboardKey.keyA)
          ? KeyEventResult.handled
          : KeyEventResult.ignored;
    },
    child: const TextField(),
  );
}
<code_end>
if the intent is input validation, this example’s functionality would probably
be better implemented using a TextInputFormatter, but the technique can still
be useful: the shortcuts widget uses this method to handle shortcuts before
they become text input, for instance.
<topic_end>
<topic_start>
controlling what gets focus
one of the main aspects of focus is controlling what can receive focus and how.
the attributes canRequestFocus, skipTraversal, and descendantsAreFocusable
control how this node and its descendants participate in the focus process.
if the skipTraversal attribute true, then this focus node doesn’t participate
in focus traversal. it is still focusable if requestFocus is called on its
focus node, but is otherwise skipped when the focus traversal system is looking
for the next thing to focus on.
the canRequestFocus attribute, unsurprisingly, controls whether or not the
focus node that this focus widget manages can be used to request focus. if
this attribute is false, then calling requestFocus on the node has no effect.
it also implies that this node is skipped for focus traversal, since it can’t
request focus.
the descendantsAreFocusable attribute controls whether the descendants of this
node can receive focus, but still allows this node to receive focus.  this
attribute can be used to turn off focusability for an entire widget subtree.
this is how the ExcludeFocus widget works: it’s just a focus widget with
this attribute set.
<topic_end>
<topic_start>
autofocus
setting the autofocus attribute of a focus widget tells the widget to
request the focus the first time the focus scope it belongs to is focused.  if
more than one widget has autofocus set, then it is arbitrary which one
receives the focus, so try to only set it on one widget per focus scope.
the autofocus attribute only takes effect if there isn’t already a focus in
the scope that the node belongs to.
setting the autofocus attribute on two nodes that belong to different focus
scopes is well defined: each one becomes the focused widget when their
corresponding scopes are focused.
<topic_end>
<topic_start>
change notifications
the Focus.onFocusChanged callback can be used to get notifications that the
focus state for a particular node has changed. it notifies if the node is added
to or removed from the focus chain, which means it gets notifications even if it
isn’t the primary focus. if you only want to know if you have received the
primary focus, check and see if hasPrimaryFocus is true on the focus node.
<topic_end>
<topic_start>
obtaining the FocusNode
sometimes, it is useful to obtain the focus node of a focus widget to
interrogate its attributes.
to access the focus node from an ancestor of the focus widget, create and pass
in a FocusNode as the focus widget’s focusNode attribute. because it needs
to be disposed of, the focus node you pass needs to be owned by a stateful
widget, so don’t just create one each time it is built.
if you need access to the focus node from the descendant of a focus widget,
you can call focus.of(context) to obtain the focus node of the nearest focus
widget to the given context. if you need to obtain the FocusNode of a focus
widget within the same build function, use a builder to make sure you have
the correct context. this is shown in the following example:
<code_start>
@override
widget build(BuildContext context) {
  return focus(
    child: builder(
      builder: (context) {
        final bool hasPrimary = Focus.of(context).hasPrimaryFocus;
        print('Building with primary focus: $hasprimary');
        return const SizedBox(width: 100, height: 100);
      },
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
timing
one of the details of the focus system is that when focus is requested, it only
takes effect after the current build phase completes.  this means that focus
changes are always delayed by one frame, because changing focus can
cause arbitrary parts of the widget tree to rebuild, including ancestors of the
widget currently requesting focus. because descendants cannot dirty their
ancestors, it has to happen between frames, so that any needed changes can
happen on the next frame.
<topic_end>
<topic_start>
FocusScope widget
the FocusScope widget is a special version of the focus widget that manages
a FocusScopeNode instead of a FocusNode.  the FocusScopeNode is a special
node in the focus tree that serves as a grouping mechanism for the focus nodes
in a subtree. focus traversal stays within a focus scope unless a node outside
of the scope is explicitly focused.
the focus scope also keeps track of the current focus and history of the nodes
focused within its subtree.  that way, if a node releases focus or is removed
when it had focus, the focus can be returned to the node that had focus
previously.
focus scopes also serve as a place to return focus to if none of the descendants
have focus.  this allows the focus traversal code to have a starting context for
finding the next (or first) focusable control to move to.
if you focus a focus scope node, it first attempts to focus the current, or most
recently focused node in its subtree, or the node in its subtree that requested
autofocus (if any).  if there is no such node, it receives the focus itself.
<topic_end>
<topic_start>
FocusableActionDetector widget
the FocusableActionDetector is a widget that combines the functionality of
actions, shortcuts, MouseRegion and a focus widget to create
a detector that defines actions and key bindings, and provides callbacks for
handling focus and hover highlights. it is what flutter controls use to
implement all of these aspects of the controls. it is just implemented using the
constituent widgets, so if you don’t need all of its functionality, you can just
use the ones you need, but it is a convenient way to build these behaviors into
your custom controls.
info note
  to learn more, watch this short widget of the week video on the FocusableActionDetector widget:
<topic_end>
<topic_start>
controlling focus traversal
once an application has the ability to focus, the next thing many apps want to
do is to allow the user to control the focus using the keyboard or another input
device. the most common example of this is “tab traversal” where the user
presses tab to go to the “next” control. controlling what “next”
means is the subject of this section. this kind of traversal is provided by
flutter by default.
in a simple grid layout, it’s fairly easy to decide which control is next. if
you’re not at the end of the row, then it’s the one to the right (or left for
right-to-left locales). if you are at the end of a row, it’s the first control
in the next row. unfortunately, applications are rarely laid out in grids, so
more guidance is often needed.
the default algorithm in flutter (readingordertraversalpolicy) for focus
traversal is pretty good: it gives the right answer for most applications.
however, there are always pathological cases, or cases where the context or
design requires a different order than the one the default ordering algorithm
arrives at. for those cases, there are other mechanisms for achieving the
desired order.
<topic_end>
<topic_start>
FocusTraversalGroup widget
the FocusTraversalGroup widget should be placed in the tree around widget
subtrees that should be fully traversed before moving on to another widget or
group of widgets. just grouping widgets into related groups is often enough to
resolve many tab traversal ordering problems. if not, the group can also be
given a FocusTraversalPolicy to determine the ordering within the group.
the default ReadingOrderTraversalPolicy is usually sufficient, but in
cases where more control over ordering is needed, an
OrderedTraversalPolicy can be used. the order argument of the
FocusTraversalOrder widget wrapped around the focusable components
determines the order. the order can be any subclass of FocusOrder, but
NumericFocusOrder and LexicalFocusOrder are provided.
if none of the provided focus traversal policies are sufficient for your
application, you could also write your own policy and use it to determine any
custom ordering you want.
here’s an example of how to use the FocusTraversalOrder widget to traverse a
row of buttons in the order TWO, ONE, THREE using NumericFocusOrder.
<code_start>
class OrderedButtonRow extends StatelessWidget {
  const OrderedButtonRow({super.key});
  @override
  widget build(BuildContext context) {
    return FocusTraversalGroup(
      policy: OrderedTraversalPolicy(),
      child: row(
        children: <widget>[
          const spacer(),
          FocusTraversalOrder(
            order: const NumericFocusOrder(2),
            child: TextButton(
              child: const Text('ONE'),
              onPressed: () {},
            ),
          ),
          const spacer(),
          FocusTraversalOrder(
            order: const NumericFocusOrder(1),
            child: TextButton(
              child: const Text('TWO'),
              onPressed: () {},
            ),
          ),
          const spacer(),
          FocusTraversalOrder(
            order: const NumericFocusOrder(3),
            child: TextButton(
              child: const Text('THREE'),
              onPressed: () {},
            ),
          ),
          const spacer(),
        ],
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
FocusTraversalPolicy
the FocusTraversalPolicy is the object that determines which widget is next,
given a request and the current focus node. the requests (member functions) are
things like findFirstFocus, findLastFocus, next, previous, and
inDirection.
FocusTraversalPolicy is the abstract base class for concrete policies, like
ReadingOrderTraversalPolicy,  OrderedTraversalPolicy and the
DirectionalFocusTraversalPolicyMixin classes.
in order to use a FocusTraversalPolicy, you give one to a
FocusTraversalGroup, which determines the widget subtree in which the policy
will be effective. the member functions of the class are rarely called directly:
they are meant to be used by the focus system.
<topic_end>
<topic_start>
the focus manager
the FocusManager maintains the current primary focus for the system. it
only has a few pieces of API that are useful to users of the focus system. one
is the FocusManager.instance.primaryFocus property, which contains the
currently focused focus node and is also accessible from the global
primaryFocus field.
other useful properties are FocusManager.instance.highlightMode and
FocusManager.instance.highlightStrategy. these are used by widgets that need
to switch between a “touch” mode and a “traditional” (mouse and keyboard) mode
for their focus highlights. when a user is using touch to navigate, the focus
highlight is usually hidden, and when they switch to a mouse or keyboard, the
focus highlight needs to be shown again so they know what is focused. the
hightlightStrategy tells the focus manager how to interpret changes in the
usage mode of the device: it can either automatically switch between the two
based on the most recent input events, or it can be locked in touch or
traditional modes. the provided widgets in flutter already know how to use this
information, so you only need it if you’re writing your own controls from
scratch. you can use addHighlightModeListener callback to listen for changes
in the highlight mode.
<topic_end>
<topic_start>
adding assets and images
flutter apps can include both code and assets
(sometimes called resources). an asset is a file
that is bundled and deployed with your app,
and is accessible at runtime. common types of assets include
static data (for example, JSON files),
configuration files, icons, and images
(jpeg, WebP, GIF, animated WebP/GIF, PNG, BMP, and WBMP).
<topic_end>
<topic_start>
specifying assets
flutter uses the pubspec.yaml file,
located at the root of your project,
to identify assets required by an app.
here is an example:
to include all assets under a directory,
specify the directory name with the / character at the end:
info note
 only files located directly in the directory are included.
 resolution-aware asset image variants are the only exception.
 to add files located in subdirectories, create an entry per directory.
<topic_end>
<topic_start>
asset bundling
the assets subsection of the flutter section
specifies files that should be included with the app.
each asset is identified by an explicit path
(relative to the pubspec.yaml file) where the asset
file is located. the order in which the assets are
declared doesn’t matter. the actual directory name used
(assets in first example or directory in the above
example) doesn’t matter.
during a build, flutter places assets into a special
archive called the asset bundle that apps read
from at runtime.
<topic_end>
<topic_start>
loading assets
your app can access its assets through an
AssetBundle object.
the two main methods on an asset bundle allow you to load a
string/text asset (loadstring()) or an image/binary asset (load())
out of the bundle, given a logical key. the logical key maps to the path
to the asset specified in the pubspec.yaml file at build time.
<topic_end>
<topic_start>
loading text assets
each flutter app has a rootBundle
object for easy access to the main asset bundle.
it is possible to load assets directly using the
rootBundle global static from
package:flutter/services.dart.
however, it’s recommended to obtain the AssetBundle
for the current BuildContext using
DefaultAssetBundle, rather than the default
asset bundle that was built with the app; this
approach enables a parent widget to substitute a
different AssetBundle at run time,
which can be useful for localization or testing
scenarios.
typically, you’ll use DefaultAssetBundle.of()
to indirectly load an asset, for example a JSON file,
from the app’s runtime rootBundle.
outside of a widget context, or when a handle
to an AssetBundle is not available,
you can use rootBundle to directly load such assets.
for example:
<code_start>
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}
<code_end>
<topic_end>
<topic_start>
loading images
to load an image, use the AssetImage
class in a widget’s build() method.
for example, your app can load the background
image from the asset declarations in the previous example:
<code_start>
return const image(image: AssetImage('assets/background.png'));
<code_end>
<topic_end>
<topic_start>
resolution-aware image assets
flutter can load resolution-appropriate images for
the current device pixel ratio.
AssetImage will map a logical requested
asset onto one that most closely matches the current
device pixel ratio.
for this mapping to work, assets should be arranged
according to a particular directory structure:
where m and n are numeric identifiers that correspond
to the nominal resolution of the images contained within.
in other words, they specify the device pixel ratio that
the images are intended for.
in this example, image.png is considered the main asset,
while mx/image.png and nx/image.png are considered to be
variants.
the main asset is assumed to correspond to a resolution of 1.0.
for example, consider the following asset layout for an
image named my_icon.png:
on devices with a device pixel ratio of 1.8, the asset
.../2.0x/my_icon.png is chosen.
for a device pixel ratio of 2.7, the asset
.../3.0x/my_icon.png is chosen.
if the width and height of the rendered image are not specified
on the image widget, the nominal resolution is used to scale
the asset so that it occupies the same amount of screen space
as the main asset would have, just with a higher resolution.
that is, if .../my_icon.png is 72px by 72px, then
.../3.0x/my_icon.png should be 216px by 216px;
but they both render into 72px by 72px (in logical pixels),
if width and height are not specified.
info note
device pixel ratio depends on MediaQueryData.size, which requires having either
  MaterialApp or CupertinoApp as an ancestor of your AssetImage.
<topic_end>
<topic_start>
bundling of resolution-aware image assets
you only need to specify the main asset or its parent directory
in the assets section of pubspec.yaml.
flutter bundles the variants for you.
each entry should correspond to a real file, with the exception of
the main asset entry. if the main asset entry doesn’t correspond
to a real file, then the asset with the lowest resolution
is used as the fallback for devices with device pixel
ratios below that resolution. the entry should still
be included in the pubspec.yaml manifest, however.
anything using the default asset bundle inherits resolution
awareness when loading images. (if you work with some of the lower
level classes, like ImageStream or ImageCache,
you’ll also notice parameters related to scale.)
<topic_end>
<topic_start>
asset images in package dependencies
to load an image from a package dependency,
the package argument must be provided to AssetImage.
for instance, suppose your application depends on a package
called my_icons, which has the following directory structure:
to load the image, use:
<code_start>
return const AssetImage('icons/heart.png', package: 'my_icons');
<code_end>
assets used by the package itself should also be fetched
using the package argument as above.
<topic_end>
<topic_start>
bundling of package assets
if the desired asset is specified in the pubspec.yaml
file of the package, it’s bundled automatically with the
application. in particular, assets used by the package
itself must be specified in its pubspec.yaml.
a package can also choose to have assets in its lib/
folder that are not specified in its pubspec.yaml file.
in this case, for those images to be bundled,
the application has to specify which ones to include in its
pubspec.yaml. for instance, a package named fancy_backgrounds
could have the following files:
to include, say, the first image, the pubspec.yaml of the
application should specify it in the assets section:
the lib/ is implied,
so it should not be included in the asset path.
if you are developing a package, to load an asset within the package, specify it in the pubspec.yaml of the package:
to load the image within your package, use:
<topic_end>
<topic_start>
sharing assets with the underlying platform
flutter assets are readily available to platform code
using the AssetManager on android and NSBundle on iOS.
<topic_end>
<topic_start>
loading flutter assets in android
on android the assets are available through the
AssetManager API.  the lookup key used in,
for instance openFd, is obtained from
lookupKeyForAsset on PluginRegistry.Registrar or
getLookupKeyForAsset on FlutterView.
PluginRegistry.Registrar is available when developing a plugin
while FlutterView would be the choice when developing an
app including a platform view.
as an example, suppose you have specified the following
in your pubspec.yaml
this reflects the following structure in your flutter app.
to access icons/heart.png from your java plugin code,
do the following:
<topic_end>
<topic_start>
loading flutter assets in iOS
on iOS the assets are available through the mainBundle.
the lookup key used in, for instance pathForResource:ofType:,
is obtained from lookupKeyForAsset or lookupKeyForAsset:fromPackage:
on FlutterPluginRegistrar, or lookupKeyForAsset: or
lookupKeyForAsset:fromPackage: on FlutterViewController.
FlutterPluginRegistrar is available when developing
a plugin while FlutterViewController would be the choice
when developing an app including a platform view.
as an example, suppose you have the flutter setting from above.
to access icons/heart.png from your Objective-C plugin code you
would do the following:
to access icons/heart.png from your swift app you
would do the following:
for a more complete example, see the implementation of the
flutter video_player plugin on pub.dev.
the ios_platform_images plugin on pub.dev wraps
up this logic in a convenient category. you fetch
an image as follows:
Objective-C:
swift:
<topic_end>
<topic_start>
loading iOS images in flutter
when implementing flutter by
adding it to an existing iOS app,
you might have images hosted in iOS that you
want to use in flutter. to accomplish
that, use the ios_platform_images plugin
available on pub.dev.
<topic_end>
<topic_start>
platform assets
there are other occasions to work with assets in the
platform projects directly. below are two common cases
where assets are used before the flutter framework is
loaded and running.
<topic_end>
<topic_start>
updating the app icon
updating a flutter application’s launch icon works
the same way as updating launch icons in native
android or iOS applications.
<topic_end>
<topic_start>
android
in your flutter project’s root directory, navigate to
.../android/app/src/main/res. the various bitmap resource
folders such as mipmap-hdpi already contain placeholder
images named ic_launcher.png. replace them with your
desired assets respecting the recommended icon size per
screen density as indicated by the android developer guide.
info note
  if you rename the .png files, you must also update the
  corresponding name in your AndroidManifest.xml’s
  <application> tag’s android:icon attribute.
<topic_end>
<topic_start>
iOS
in your flutter project’s root directory,
navigate to .../ios/runner. the
Assets.xcassets/AppIcon.appiconset directory already contains
placeholder images. replace them with the appropriately
sized images as indicated by their filename as dictated by the
apple human interface guidelines.
keep the original file names.
<topic_end>
<topic_start>
updating the launch screen
flutter also uses native platform mechanisms to draw
transitional launch screens to your flutter app while the
flutter framework loads. this launch screen persists until
flutter renders the first frame of your application.
info note
  this implies that if you don’t call runApp() in the
  main() function of your app (or more specifically,
  if you don’t call FlutterView.render() in response to
  PlatformDispatcher.onDrawFrame),
  the launch screen persists forever.
<topic_end>
<topic_start>
android
to add a launch screen (also known as “splash screen”) to your
flutter application, navigate to .../android/app/src/main.
in res/drawable/launch_background.xml,
use this layer list drawable XML to customize
the look of your launch screen. the existing template provides
an example of adding an image to the middle of a white splash
screen in commented code. you can uncomment it or use other
drawables to achieve the intended effect.
for more details, see
adding a splash screen to your android app.
<topic_end>
<topic_start>
iOS
to add an image to the center of your “splash screen”,
navigate to .../ios/runner.
in Assets.xcassets/LaunchImage.imageset,
drop in images named LaunchImage.png,
LaunchImage@2x.png, LaunchImage@3x.png.
if you use different filenames,
update the contents.json file in the same directory.
you can also fully customize your launch screen storyboard
in xcode by opening .../ios/runner.xcworkspace.
navigate to Runner/Runner in the project navigator and
drop in images by opening assets.xcassets or do any
customization using the interface builder in
LaunchScreen.storyboard.
for more details, see
adding a splash screen to your iOS app.
<topic_end>
<topic_start>
display images from the internet
displaying images is fundamental for most mobile apps.
flutter provides the image widget to
display different types of images.
to work with images from a URL, use the
image.network() constructor.
<code_start>
image.network('https://picsum.photos/250?image=9'),
<code_end>
<topic_end>
<topic_start>
bonus: animated gifs
one useful thing about the image widget:
it supports animated gifs.
<code_start>
image.network(
    'https://docs.flutter.dev/assets/images/dash/dash-fainting.gif');
<code_end>
<topic_end>
<topic_start>
image fade in with placeholders
the default image.network constructor doesn’t handle more advanced
functionality, such as fading images in after loading.
to accomplish this task,
check out fade in images with a placeholder.
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    var title = 'web images';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: text(title),
        ),
        body: image.network('https://picsum.photos/250?image=9'),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
fade in images with a placeholder
when displaying images using the default image widget,
you might notice they simply pop onto the screen as they’re loaded.
this might feel visually jarring to your users.
instead, wouldn’t it be nice to display a placeholder at first,
and images would fade in as they’re loaded? use the
FadeInImage widget for exactly this purpose.
FadeInImage works with images of any type: in-memory, local assets,
or images from the internet.
<topic_end>
<topic_start>
In-Memory
in this example, use the transparent_image
package for a simple transparent placeholder.
<code_start>
FadeInImage.memoryNetwork(
  placeholder: kTransparentImage,
  image: 'https://picsum.photos/250?image=9',
),
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'fade in images';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: stack(
          children: <widget>[
            const center(child: CircularProgressIndicator()),
            center(
              child: FadeInImage.memoryNetwork(
                placeholder: kTransparentImage,
                image: 'https://picsum.photos/250?image=9',
              ),
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
from asset bundle
you can also consider using local assets for placeholders.
first, add the asset to the project’s pubspec.yaml file
(for more details, see adding assets and images):
then, use the FadeInImage.assetNetwork() constructor:
<code_start>
FadeInImage.assetNetwork(
  placeholder: 'assets/loading.gif',
  image: 'https://picsum.photos/250?image=9',
),
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'fade in images';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: center(
          child: FadeInImage.assetNetwork(
            placeholder: 'assets/loading.gif',
            image: 'https://picsum.photos/250?image=9',
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
play and pause a video
playing videos is a common task in app development,
and flutter apps are no exception. to play videos,
the flutter team provides the video_player plugin.
you can use the video_player plugin to play videos
stored on the file system, as an asset, or from the internet.
warning warning
  at this time,
  the video_player plugin doesn’t work with any desktop platform.
  to learn more, check out the video_player package.
on iOS, the video_player plugin makes use of
AVPlayer to handle playback. on android,
it uses ExoPlayer.
this recipe demonstrates how to use the video_player package to stream a
video from the internet with basic play and pause controls using
the following steps:
<topic_end>
<topic_start>
1. add the video_player dependency
this recipe depends on one flutter plugin: video_player. 
first, add this dependency to your project.
to add the video_player package as a dependency, run flutter pub add:
<topic_end>
<topic_start>
2. add permissions to your app
next, update your android and ios configurations to ensure
that your app has the correct permissions to stream videos
from the internet.
<topic_end>
<topic_start>
android
add the following permission to the AndroidManifest.xml file just after the
<application> definition. the AndroidManifest.xml file is found at
<project root>/android/app/src/main/AndroidManifest.xml.
<topic_end>
<topic_start>
iOS
for iOS, add the following to the info.plist file found at
<project root>/ios/Runner/Info.plist.
warning warning
  the video_player plugin can only play asset videos in iOS simulators.
  you must test network-hosted videos on physical iOS devices.
<topic_end>
<topic_start>
3. create and initialize a VideoPlayerController
now that you have the video_player plugin installed with the correct
permissions, create a VideoPlayerController. the
VideoPlayerController class allows you to connect to different types of
videos and control playback.
before you can play videos, you must also initialize the controller.
this establishes the connection to the video and prepare the
controller for playback.
to create and initialize the VideoPlayerController do the following:
<code_start>
class VideoPlayerScreen extends StatefulWidget {
  const VideoPlayerScreen({super.key});
  @override
  State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late VideoPlayerController _controller;
  late future<void> _initializeVideoPlayerFuture;
  @override
  void initState() {
    super.initState();
    // create and store the VideoPlayerController. the VideoPlayerController
    // offers several different constructors to play videos from assets, files,
    // or the internet.
    _controller = VideoPlayerController.networkUrl(
      uri.parse(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
      ),
    );
    _initializeVideoPlayerFuture = _controller.initialize();
  }
  @override
  void dispose() {
    // ensure disposing of the VideoPlayerController to free up resources.
    _controller.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    // complete the code in the next step.
    return container();
  }
}
<code_end>
<topic_end>
<topic_start>
4. display the video player
now, display the video. the video_player plugin provides the
VideoPlayer widget to display the video initialized by
the VideoPlayerController.
by default, the VideoPlayer widget takes up as much space as possible.
this often isn’t ideal for videos because they are meant
to be displayed in a specific aspect ratio, such as 16x9 or 4x3.
therefore, wrap the VideoPlayer widget in an AspectRatio
widget to ensure that the video has the correct proportions.
furthermore, you must display the VideoPlayer widget after the
_initializeVideoPlayerFuture() completes. use FutureBuilder to
display a loading spinner until the controller finishes initializing.
note: initializing the controller does not begin playback.
<code_start>
// use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
FutureBuilder(
  future: _initializeVideoPlayerFuture,
  builder: (context, snapshot) {
    if (snapshot.connectionstate == ConnectionState.done) {
      // if the VideoPlayerController has finished initialization, use
      // the data it provides to limit the aspect ratio of the video.
      return AspectRatio(
        aspectRatio: _controller.value.aspectRatio,
        // use the VideoPlayer widget to display the video.
        child: VideoPlayer(_controller),
      );
    } else {
      // if the VideoPlayerController is still initializing, show a
      // loading spinner.
      return const center(
        child: CircularProgressIndicator(),
      );
    }
  },
)
<code_end>
<topic_end>
<topic_start>
5. play and pause the video
by default, the video starts in a paused state. to begin playback,
call the play() method provided by the VideoPlayerController.
to pause playback, call the pause() method.
for this example,
add a FloatingActionButton to your app that displays a play
or pause icon depending on the situation.
when the user taps the button,
play the video if it’s currently paused,
or pause the video if it’s playing.
<code_start>
FloatingActionButton(
  onPressed: () {
    // wrap the play or pause in a call to `setstate`. this ensures the
    // correct icon is shown.
    setState(() {
      // if the video is playing, pause it.
      if (_controller.value.isplaying) {
        _controller.pause();
      } else {
        // if the video is paused, play it.
        _controller.play();
      }
    });
  },
  // display the correct icon depending on the state of the player.
  child: icon(
    _controller.value.isPlaying ? icons.pause : icons.play_arrow,
  ),
)
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(const VideoPlayerApp());
class VideoPlayerApp extends StatelessWidget {
  const VideoPlayerApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'video player demo',
      home: VideoPlayerScreen(),
    );
  }
}
class VideoPlayerScreen extends StatefulWidget {
  const VideoPlayerScreen({super.key});
  @override
  State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late VideoPlayerController _controller;
  late future<void> _initializeVideoPlayerFuture;
  @override
  void initState() {
    super.initState();
    // create and store the VideoPlayerController. the VideoPlayerController
    // offers several different constructors to play videos from assets, files,
    // or the internet.
    _controller = VideoPlayerController.networkUrl(
      uri.parse(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
      ),
    );
    // initialize the controller and store the future for later use.
    _initializeVideoPlayerFuture = _controller.initialize();
    // use the controller to loop the video.
    _controller.setLooping(true);
  }
  @override
  void dispose() {
    // ensure disposing of the VideoPlayerController to free up resources.
    _controller.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Butterfly video'),
      ),
      // use a FutureBuilder to display a loading spinner while waiting for the
      // VideoPlayerController to finish initializing.
      body: FutureBuilder(
        future: _initializeVideoPlayerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionstate == ConnectionState.done) {
            // if the VideoPlayerController has finished initialization, use
            // the data it provides to limit the aspect ratio of the video.
            return AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              // use the VideoPlayer widget to display the video.
              child: VideoPlayer(_controller),
            );
          } else {
            // if the VideoPlayerController is still initializing, show a
            // loading spinner.
            return const center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // wrap the play or pause in a call to `setstate`. this ensures the
          // correct icon is shown.
          setState(() {
            // if the video is playing, pause it.
            if (_controller.value.isplaying) {
              _controller.pause();
            } else {
              // if the video is paused, play it.
              _controller.play();
            }
          });
        },
        // display the correct icon depending on the state of the player.
        child: icon(
          _controller.value.isPlaying ? icons.pause : icons.play_arrow,
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
navigation and routing
flutter provides a complete system for navigating between screens and handling
deep links. small applications without complex deep linking can use
navigator, while apps with specific deep linking and navigation
requirements should also use the router to correctly handle deep links on
android and iOS, and to stay in sync with the address bar when the app is
running on the web.
to configure your android or iOS application to handle deep links, see 
deep linking.
<topic_end>
<topic_start>
using the navigator
the navigator widget displays screens as a stack using the correct transition
animations for the target platform. to navigate to a new screen, access the
navigator through the route’s BuildContext and call imperative methods such
as push() or pop():
because navigator keeps a stack of route objects (representing the history
stack), the push() method also takes a route object. the MaterialPageRoute
object is a subclass of route that specifies the transition animations for
material design. for more examples of how to use the navigator, follow the
navigation recipes from the flutter cookbook or visit the navigator API
documentation.
<topic_end>
<topic_start>
using named routes
info note
  we don’t recommend using named routes for most applications.
  for more information, see the limitations section below.
applications with simple navigation and deep linking requirements can use the
navigator for navigation and the MaterialApp.routes parameter for deep
links:
routes specified here are called named routes. for a complete example, follow
the navigate with named routes recipe from the flutter cookbook.
<topic_end>
<topic_start>
limitations
although named routes can handle deep links, the behavior is always the same and
can’t be customized. when a new deep link is received by the platform, flutter
pushes a new route onto the navigator regardless where the user currently is.
flutter also doesn’t support the browser forward button for applications using
named routes. for these reasons, we don’t recommend using named routes in most
applications.
<topic_end>
<topic_start>
using the router
flutter applications with advanced navigation and routing requirements (such as
a web app that uses direct links to each screen, or an app with multiple
navigator widgets) should use a routing package such as go_router that can
parse the route path and configure the navigator whenever the app receives a
new deep link.
to use the router, switch to the router constructor on MaterialApp or
CupertinoApp and provide it with a router configuration. routing packages,
such as go_router, typically provide a
configuration for you. for example:
because packages like go_router are declarative, they will always display the
same screen(s) when a deep link is received.
note for advanced developers:  if you prefer not to use a routing package
  and would like full control over navigation and routing in your app, override
  RouteInformationParser and RouterDelegate. when the state in your app
  changes, you can precisely control the stack of screens by providing a list of
  page objects using the navigator.pages parameter. for more details, see the
  router API documentation.
<topic_end>
<topic_start>
using router and navigator together
the router and navigator are designed to work together. you can navigate
using the router API through a declarative routing package, such as
go_router, or by calling imperative methods such as push() and pop() on
the navigator.
when you navigate using the router or a declarative routing package, each
route on the navigator is page-backed, meaning it was created from a
page using the pages
argument on the navigator constructor. conversely, any route
created by calling navigator.push or showDialog will add a pageless
route to the navigator. if you are using a routing package, routes that are
page-backed are always deep-linkable, whereas pageless routes
are not.
when a page-backed route is removed from the navigator, all of the
pageless routes after it are also removed. for example, if a deep link
navigates by removing a page-backed route from the navigator, all pageless
_routes after (up until the next _page-backed route) are removed too.
info note
  you can’t prevent navigation from page-backed screens using WillPopScope.
  instead, you should consult your routing package’s API documentation.
<topic_end>
<topic_start>
web support
apps using the router class integrate with the browser history API to provide
a consistent experience when using the browser’s back and forward buttons.
whenever you navigate using the router, a history API entry is added to the
browser’s history stack. pressing the back button uses reverse
chronological navigation, meaning that the user is taken to the previously
visited location that was shown using the router. this means that if the user
pops a page from the navigator and then presses the browser back button
the previous page is pushed back onto the stack.
<topic_end>
<topic_start>
more information
for more information on navigation and routing, check out the following
resources:
<topic_end>
<topic_start>
work with tabs
working with tabs is a common pattern in apps that follow the
material design guidelines.
flutter includes a convenient way to create tab layouts as part of
the material library.
this recipe creates a tabbed example using the following steps;
<topic_end>
<topic_start>
1. create a TabController
for tabs to work, you need to keep the selected tab and content
sections in sync.
this is the job of the TabController.
either create a TabController manually,
or automatically by using a DefaultTabController widget.
using DefaultTabController is the simplest option, since it
creates a TabController and makes it available to all descendant widgets.
<code_start>
return MaterialApp(
  home: DefaultTabController(
    length: 3,
    child: scaffold(),
  ),
);
<code_end>
<topic_end>
<topic_start>
2. create the tabs
when a tab is selected, it needs to display content.
you can create tabs using the TabBar widget.
in this example, create a TabBar with three
tab widgets and place it within an AppBar.
<code_start>
return MaterialApp(
  home: DefaultTabController(
    length: 3,
    child: scaffold(
      appBar: AppBar(
        bottom: const TabBar(
          tabs: [
            tab(icon: Icon(Icons.directions_car)),
            tab(icon: Icon(Icons.directions_transit)),
            tab(icon: Icon(Icons.directions_bike)),
          ],
        ),
      ),
    ),
  ),
);
<code_end>
by default, the TabBar looks up the widget tree for the nearest
DefaultTabController. if you’re manually creating a TabController,
pass it to the TabBar.
<topic_end>
<topic_start>
3. create content for each tab
now that you have tabs, display content when a tab is selected.
for this purpose, use the TabBarView widget.
info note
  order is important and must correspond to the order of the tabs in the
  TabBar.
<code_start>
body: const TabBarView(
  children: [
    Icon(Icons.directions_car),
    Icon(Icons.directions_transit),
    Icon(Icons.directions_bike),
  ],
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
  const TabBarDemo({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: scaffold(
          appBar: AppBar(
            bottom: const TabBar(
              tabs: [
                tab(icon: Icon(Icons.directions_car)),
                tab(icon: Icon(Icons.directions_transit)),
                tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: const Text('Tabs demo'),
          ),
          body: const TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
navigate to a new screen and back
most apps contain several screens for displaying different types of
information.
for example, an app might have a screen that displays products.
when the user taps the image of a product, a new screen displays
details about the product.
terminology: in flutter, screens and pages are called routes.
  the remainder of this recipe refers to routes.
in android, a route is equivalent to an activity.
in iOS, a route is equivalent to a ViewController.
in flutter, a route is just a widget.
this recipe uses the navigator to navigate to a new route.
the next few sections show how to navigate between two routes,
using these steps:
<topic_end>
<topic_start>
1. create two routes
first, create two routes to work with. since this is a basic example,
each route contains only a single button. tapping the button on the
first route navigates to the second route. tapping the button on the
second route returns to the first route.
first, set up the visual structure:
<code_start>
class FirstRoute extends StatelessWidget {
  const FirstRoute({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('First route'),
      ),
      body: center(
        child: ElevatedButton(
          child: const Text('Open route'),
          onPressed: () {
            // navigate to second route when tapped.
          },
        ),
      ),
    );
  }
}
class SecondRoute extends StatelessWidget {
  const SecondRoute({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Second route'),
      ),
      body: center(
        child: ElevatedButton(
          onPressed: () {
            // navigate back to first route when tapped.
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
2. navigate to the second route using navigator.push()
to switch to a new route, use the navigator.push()
method. the push() method adds a route to the stack of routes managed by
the navigator. where does the route come from?
you can create your own, or use a MaterialPageRoute,
which is useful because it transitions to the
new route using a platform-specific animation.
in the build() method of the FirstRoute widget,
update the onPressed() callback:
<code_start>
// within the `firstroute` widget
onPressed: () {
  navigator.push(
    context,
    MaterialPageRoute(builder: (context) => const SecondRoute()),
  );
}
<code_end>
<topic_end>
<topic_start>
3. return to the first route using navigator.pop()
how do you close the second route and return to the first?
by using the navigator.pop() method.
the pop() method removes the current route from the stack of
routes managed by the navigator.
to implement a return to the original route, update the onPressed()
callback in the SecondRoute widget:
<code_start>
// within the SecondRoute widget
onPressed: () {
  navigator.pop(context);
}
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MaterialApp(
    title: 'navigation basics',
    home: FirstRoute(),
  ));
}
class FirstRoute extends StatelessWidget {
  const FirstRoute({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('First route'),
      ),
      body: center(
        child: ElevatedButton(
          child: const Text('Open route'),
          onPressed: () {
            navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}
class SecondRoute extends StatelessWidget {
  const SecondRoute({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Second route'),
      ),
      body: center(
        child: ElevatedButton(
          onPressed: () {
            navigator.pop(context);
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
navigation with CupertinoPageRoute
in the previous example you learned how to navigate between screens
using the MaterialPageRoute from material components.
however, in flutter you are not limited to material design language,
instead, you also have access to cupertino (ios-style) widgets.
implementing navigation with cupertino widgets follows the same steps
as when using MaterialPageRoute, 
but instead you use CupertinoPageRoute
which provides an iOS-style transition animation.
in the following example, these widgets have been replaced:
this way, the example follows the current iOS design language.
you don’t need to replace all material widgets with cupertino versions
  to use CupertinoPageRoute
  since flutter allows you to mix and match material and cupertino widgets
  depending on your needs.
<code_start>
import 'package:flutter/cupertino.dart';
void main() {
  runApp(const CupertinoApp(
    title: 'navigation basics',
    home: FirstRoute(),
  ));
}
class FirstRoute extends StatelessWidget {
  const FirstRoute({super.key});
  @override
  widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text('First route'),
      ),
      child: center(
        child: CupertinoButton(
          child: const Text('Open route'),
          onPressed: () {
            navigator.push(
              context,
              CupertinoPageRoute(builder: (context) => const SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}
class SecondRoute extends StatelessWidget {
  const SecondRoute({super.key});
  @override
  widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: const CupertinoNavigationBar(
        middle: Text('Second route'),
      ),
      child: center(
        child: CupertinoButton(
          onPressed: () {
            navigator.pop(context);
          },
          child: const Text('Go back!'),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
send data to a new screen
often, you not only want to navigate to a new screen,
but also pass data to the screen as well.
for example, you might want to pass information about
the item that’s been tapped.
remember: screens are just widgets.
in this example, create a list of todos.
when a todo is tapped, navigate to a new screen (widget) that
displays information about the todo.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. define a todo class
first, you need a simple way to represent todos. for this example,
create a class that contains two pieces of data: the title and description.
<code_start>
class todo {
  final string title;
  final string description;
  const todo(this.title, this.description);
}
<code_end>
<topic_end>
<topic_start>
2. create a list of todos
second, display a list of todos. in this example, generate
20 todos and show them using a ListView.
for more information on working with lists,
see the use lists recipe.
<topic_end>
<topic_start>
generate the list of todos
<code_start>
final todos = list.generate(
  20,
  (i) => todo(
    'todo $i',
    'a description of what needs to be done for todo $i',
  ),
);
<code_end>
<topic_end>
<topic_start>
display the list of todos using a ListView
<code_start>
ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: text(todos[index].title),
    );
  },
),
<code_end>
so far, so good.
this generates 20 todos and displays them in a ListView.
<topic_end>
<topic_start>
3. create a todo screen to display the list
for this, we create a StatelessWidget. we call it TodosScreen.
since the contents of this page won’t change during runtime,
we’ll have to require the list
of todos within the scope of this widget.
we pass in our ListView.builder as body of the widget we’re returning to build().
this’ll render the list on to the screen for you to get going!
<code_start>
class TodosScreen extends StatelessWidget {
  // requiring the list of todos.
  const TodosScreen({super.key, required this.todos});
  final List<Todo> todos;
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Todos'),
      ),
      //passing in the ListView.builder
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: text(todos[index].title),
          );
        },
      ),
    );
  }
}
<code_end>
with flutter’s default styling, you’re good to go without sweating about 
things that you’d like to do later on!
<topic_end>
<topic_start>
4. create a detail screen to display information about a todo
now, create the second screen. the title of the screen contains the
title of the todo, and the body of the screen shows the description.
since the detail screen is a normal StatelessWidget,
require the user to enter a todo in the UI.
then, build the UI using the given todo.
<code_start>
class DetailScreen extends StatelessWidget {
  // in the constructor, require a todo.
  const DetailScreen({super.key, required this.todo});
  // declare a field that holds the todo.
  final todo todo;
  @override
  widget build(BuildContext context) {
    // use the todo to create the UI.
    return scaffold(
      appBar: AppBar(
        title: text(todo.title),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: text(todo.description),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
5. navigate and pass data to the detail screen
with a DetailScreen in place,
you’re ready to perform the navigation.
in this example, navigate to the DetailScreen when a user
taps a todo in the list. pass the todo to the DetailScreen.
to capture the user’s tap in the TodosScreen, write an onTap()
callback for the ListTile widget. within the onTap() callback,
use the navigator.push() method.
<code_start>
body: ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: text(todos[index].title),
      // when a user taps the ListTile, navigate to the DetailScreen.
      // notice that you're not only creating a DetailScreen, you're
      // also passing the current todo through to it.
      onTap: () {
        navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => DetailScreen(todo: todos[index]),
          ),
        );
      },
    );
  },
),
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
class todo {
  final string title;
  final string description;
  const todo(this.title, this.description);
}
void main() {
  runApp(
    MaterialApp(
      title: 'passing data',
      home: TodosScreen(
        todos: list.generate(
          20,
          (i) => todo(
            'todo $i',
            'a description of what needs to be done for todo $i',
          ),
        ),
      ),
    ),
  );
}
class TodosScreen extends StatelessWidget {
  const TodosScreen({super.key, required this.todos});
  final List<Todo> todos;
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Todos'),
      ),
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: text(todos[index].title),
            // when a user taps the ListTile, navigate to the DetailScreen.
            // notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailScreen(todo: todos[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
}
class DetailScreen extends StatelessWidget {
  // in the constructor, require a todo.
  const DetailScreen({super.key, required this.todo});
  // declare a field that holds the todo.
  final todo todo;
  @override
  widget build(BuildContext context) {
    // use the todo to create the UI.
    return scaffold(
      appBar: AppBar(
        title: text(todo.title),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: text(todo.description),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
alternatively, pass the arguments using RouteSettings
repeat the first two steps.
<topic_end>
<topic_start>
create a detail screen to extract the arguments
next, create a detail screen that extracts and displays the title and description from the todo. to access the todo, use the ModalRoute.of() method. this method returns the current route with the arguments.
<code_start>
class DetailScreen extends StatelessWidget {
  const DetailScreen({super.key});
  @override
  widget build(BuildContext context) {
    final todo = ModalRoute.of(context)!.settings.arguments as todo;
    // use the todo to create the UI.
    return scaffold(
      appBar: AppBar(
        title: text(todo.title),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: text(todo.description),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
navigate and pass the arguments to the detail screen
finally, navigate to the DetailScreen when a user taps
a ListTile widget using navigator.push().
pass the arguments as part of the RouteSettings.
the DetailScreen extracts these arguments.
<code_start>
ListView.builder(
  itemCount: todos.length,
  itemBuilder: (context, index) {
    return ListTile(
      title: text(todos[index].title),
      // when a user taps the ListTile, navigate to the DetailScreen.
      // notice that you're not only creating a DetailScreen, you're
      // also passing the current todo through to it.
      onTap: () {
        navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => const DetailScreen(),
            // pass the arguments as part of the RouteSettings. the
            // DetailScreen reads the arguments from these settings.
            settings: RouteSettings(
              arguments: todos[index],
            ),
          ),
        );
      },
    );
  },
)
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
class todo {
  final string title;
  final string description;
  const todo(this.title, this.description);
}
void main() {
  runApp(
    MaterialApp(
      title: 'passing data',
      home: TodosScreen(
        todos: list.generate(
          20,
          (i) => todo(
            'todo $i',
            'a description of what needs to be done for todo $i',
          ),
        ),
      ),
    ),
  );
}
class TodosScreen extends StatelessWidget {
  const TodosScreen({super.key, required this.todos});
  final List<Todo> todos;
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Todos'),
      ),
      body: ListView.builder(
        itemCount: todos.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: text(todos[index].title),
            // when a user taps the ListTile, navigate to the DetailScreen.
            // notice that you're not only creating a DetailScreen, you're
            // also passing the current todo through to it.
            onTap: () {
              navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const DetailScreen(),
                  // pass the arguments as part of the RouteSettings. the
                  // DetailScreen reads the arguments from these settings.
                  settings: RouteSettings(
                    arguments: todos[index],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}
class DetailScreen extends StatelessWidget {
  const DetailScreen({super.key});
  @override
  widget build(BuildContext context) {
    final todo = ModalRoute.of(context)!.settings.arguments as todo;
    // use the todo to create the UI.
    return scaffold(
      appBar: AppBar(
        title: text(todo.title),
      ),
      body: padding(
        padding: const EdgeInsets.all(16),
        child: text(todo.description),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
return data from a screen
in some cases, you might want to return data from a new screen.
for example, say you push a new screen that presents two options to a user.
when the user taps an option, you want to inform the first screen
of the user’s selection so that it can act on that information.
you can do this with the navigator.pop()
method using the following steps:
<topic_end>
<topic_start>
1. define the home screen
the home screen displays a button. when tapped,
it launches the selection screen.
<code_start>
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Returning data demo'),
      ),
      // create the SelectionButton widget in the next step.
      body: const center(
        child: SelectionButton(),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
2. add a button that launches the selection screen
now, create the SelectionButton, which does the following:
<code_start>
class SelectionButton extends StatefulWidget {
  const SelectionButton({super.key});
  @override
  State<SelectionButton> createState() => _SelectionButtonState();
}
class _SelectionButtonState extends State<SelectionButton> {
  @override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        _navigateAndDisplaySelection(context);
      },
      child: const Text('Pick an option, any option!'),
    );
  }
  future<void> _navigateAndDisplaySelection(BuildContext context) async {
    // navigator.push returns a future that completes after calling
    // navigator.pop on the selection screen.
    final result = await navigator.push(
      context,
      // create the SelectionScreen in the next step.
      MaterialPageRoute(builder: (context) => const SelectionScreen()),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
3. show the selection screen with two buttons
now, build a selection screen that contains two buttons.
when a user taps a button,
that app closes the selection screen and lets the home
screen know which button was tapped.
this step defines the UI.
the next step adds code to return data.
<code_start>
class SelectionScreen extends StatelessWidget {
  const SelectionScreen({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Pick an option'),
      ),
      body: center(
        child: column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            padding(
              padding: const EdgeInsets.all(8),
              child: ElevatedButton(
                onPressed: () {
                  // pop here with "yep"...
                },
                child: const Text('Yep!'),
              ),
            ),
            padding(
              padding: const EdgeInsets.all(8),
              child: ElevatedButton(
                onPressed: () {
                  // pop here with "nope"...
                },
                child: const Text('Nope.'),
              ),
            )
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
4. when a button is tapped, close the selection screen
now, update the onPressed() callback for both of the buttons.
to return data to the first screen,
use the navigator.pop() method,
which accepts an optional second argument called result.
any result is returned to the future in the SelectionButton.
<topic_end>
<topic_start>
yep button
<code_start>
ElevatedButton(
  onPressed: () {
    // close the screen and return "yep!" as the result.
    navigator.pop(context, 'yep!');
  },
  child: const Text('Yep!'),
)
<code_end>
<topic_end>
<topic_start>
nope button
<code_start>
ElevatedButton(
  onPressed: () {
    // close the screen and return "nope." as the result.
    navigator.pop(context, 'nope.');
  },
  child: const Text('Nope.'),
)
<code_end>
<topic_end>
<topic_start>
5. show a snackbar on the home screen with the selection
now that you’re launching a selection screen and awaiting the result,
you’ll want to do something with the information that’s returned.
in this case, show a snackbar displaying the result by using the
_navigateAndDisplaySelection() method in SelectionButton:
<code_start>
// a method that launches the SelectionScreen and awaits the result from
// navigator.pop.
future<void> _navigateAndDisplaySelection(BuildContext context) async {
  // navigator.push returns a future that completes after calling
  // navigator.pop on the selection screen.
  final result = await navigator.push(
    context,
    MaterialPageRoute(builder: (context) => const SelectionScreen()),
  );
  // when a BuildContext is used from a StatefulWidget, the mounted property
  // must be checked after an asynchronous gap.
  if (!context.mounted) return;
  // after the selection screen returns a result, hide any previous snackbars
  // and show the new result.
  ScaffoldMessenger.of(context)
    ..removeCurrentSnackBar()
    ..showSnackBar(SnackBar(content: text('$result')));
}
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      title: 'returning data',
      home: HomeScreen(),
    ),
  );
}
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Returning data demo'),
      ),
      body: const center(
        child: SelectionButton(),
      ),
    );
  }
}
class SelectionButton extends StatefulWidget {
  const SelectionButton({super.key});
  @override
  State<SelectionButton> createState() => _SelectionButtonState();
}
class _SelectionButtonState extends State<SelectionButton> {
  @override
  widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        _navigateAndDisplaySelection(context);
      },
      child: const Text('Pick an option, any option!'),
    );
  }
  // a method that launches the SelectionScreen and awaits the result from
  // navigator.pop.
  future<void> _navigateAndDisplaySelection(BuildContext context) async {
    // navigator.push returns a future that completes after calling
    // navigator.pop on the selection screen.
    final result = await navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const SelectionScreen()),
    );
    // when a BuildContext is used from a StatefulWidget, the mounted property
    // must be checked after an asynchronous gap.
    if (!context.mounted) return;
    // after the selection screen returns a result, hide any previous snackbars
    // and show the new result.
    ScaffoldMessenger.of(context)
      ..removeCurrentSnackBar()
      ..showSnackBar(SnackBar(content: text('$result')));
  }
}
class SelectionScreen extends StatelessWidget {
  const SelectionScreen({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Pick an option'),
      ),
      body: center(
        child: column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <widget>[
            padding(
              padding: const EdgeInsets.all(8),
              child: ElevatedButton(
                onPressed: () {
                  // close the screen and return "yep!" as the result.
                  navigator.pop(context, 'yep!');
                },
                child: const Text('Yep!'),
              ),
            ),
            padding(
              padding: const EdgeInsets.all(8),
              child: ElevatedButton(
                onPressed: () {
                  // close the screen and return "nope." as the result.
                  navigator.pop(context, 'nope.');
                },
                child: const Text('Nope.'),
              ),
            )
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
add a drawer to a screen
in apps that use material design,
there are two primary options for navigation: tabs and drawers.
when there is insufficient space to support tabs,
drawers provide a handy alternative.
in flutter, use the drawer widget in combination with a
scaffold to create a layout with a material design drawer.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. create a scaffold
to add a drawer to the app, wrap it in a scaffold widget.
the scaffold widget provides a consistent visual structure to apps that
follow the material design guidelines.
it also supports special material design
components, such as drawers, AppBars, and SnackBars.
in this example, create a scaffold with a drawer:
<code_start>
scaffold(
  appBar: AppBar(
    title: const Text('AppBar without hamburger button'),
  ),
  drawer: // add a drawer here in the next step.
);
<code_end>
<topic_end>
<topic_start>
2. add a drawer
now add a drawer to the scaffold. a drawer can be any widget,
but it’s often best to use the drawer widget from the
material library,
which adheres to the material design spec.
<code_start>
scaffold(
  appBar: AppBar(
    title: const Text('AppBar with hamburger button'),
  ),
  drawer: drawer(
    child: // populate the drawer in the next step.
  ),
);
<code_end>
<topic_end>
<topic_start>
3. populate the drawer with items
now that you have a drawer in place, add content to it.
for this example, use a ListView.
while you could use a column widget,
ListView is handy because it allows users to scroll
through the drawer if the
content takes more space than the screen supports.
populate the ListView with a DrawerHeader
and two ListTile widgets.
for more information on working with lists,
see the list recipes.
<code_start>
drawer(
  // add a ListView to the drawer. this ensures the user can scroll
  // through the options in the drawer if there isn't enough vertical
  // space to fit everything.
  child: ListView(
    // important: remove any padding from the ListView.
    padding: EdgeInsets.zero,
    children: [
      const DrawerHeader(
        decoration: BoxDecoration(
          color: colors.blue,
        ),
        child: Text('Drawer header'),
      ),
      ListTile(
        title: const Text('Item 1'),
        onTap: () {
          // update the state of the app.
          // ...
        },
      ),
      ListTile(
        title: const Text('Item 2'),
        onTap: () {
          // update the state of the app.
          // ...
        },
      ),
    ],
  ),
);
<code_end>
<topic_end>
<topic_start>
4. close the drawer programmatically
after a user taps an item, you might want to close the drawer.
you can do this by using the navigator.
when a user opens the drawer, flutter adds the drawer to the navigation
stack. therefore, to close the drawer, call navigator.pop(context).
<code_start>
ListTile(
  title: const Text('Item 1'),
  onTap: () {
    // update the state of the app
    // ...
    // then close the drawer
    navigator.pop(context);
  },
),
<code_end>
<topic_end>
<topic_start>
interactive example
this example shows a drawer as it is used within a scaffold widget.
the drawer has three ListTile items.
the _onItemTapped function changes the selected item’s index
and displays the corresponding text in the center of the scaffold.
info note
  for more information on implementing navigation,
  check out the navigation section of the cookbook.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  static const appTitle = 'drawer demo';
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final string title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <widget>[
    text(
      'index 0: home',
      style: optionStyle,
    ),
    text(
      'index 1: business',
      style: optionStyle,
    ),
    text(
      'index 2: school',
      style: optionStyle,
    ),
  ];
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: text(widget.title)),
      body: center(
        child: _widgetOptions[_selectedIndex],
      ),
      drawer: drawer(
        // add a ListView to the drawer. this ensures the user can scroll
        // through the options in the drawer if there isn't enough vertical
        // space to fit everything.
        child: ListView(
          // important: remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: [
            const DrawerHeader(
              decoration: BoxDecoration(
                color: colors.blue,
              ),
              child: Text('Drawer header'),
            ),
            ListTile(
              title: const Text('Home'),
              selected: _selectedIndex == 0,
              onTap: () {
                // update the state of the app
                _onItemTapped(0);
                // then close the drawer
                navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('Business'),
              selected: _selectedIndex == 1,
              onTap: () {
                // update the state of the app
                _onItemTapped(1);
                // then close the drawer
                navigator.pop(context);
              },
            ),
            ListTile(
              title: const Text('School'),
              selected: _selectedIndex == 2,
              onTap: () {
                // update the state of the app
                _onItemTapped(2);
                // then close the drawer
                navigator.pop(context);
              },
            ),
          ],
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
deep linking
flutter supports deep linking on iOS, android, and web browsers.
opening a URL displays that screen in your app. with the following
steps, you can launch and display routes by using named routes
(either with the routes parameter or
onGenerateRoute), or by
using the router widget.
info note
  named routes are no longer recommended for most
  applications. for more information, see
  limitations in the navigation overview page.
if you’re running the app in a web browser, there’s no additional setup
required. route paths are handled in the same way as an iOS or android deep
link. by default, web apps read the deep link path from the url fragment using
the pattern: /#/path/to/app/screen, but this can be changed by
configuring the URL strategy for your app.
if you are a visual learner, check out the following video:
deep linking in flutter
<topic_end>
<topic_start>
get started
to get started, see our cookbooks for android and iOS:
<topic_end>
<topic_start>
migrating from plugin-based deep linking
if you have written a plugin to handle deep links, as described in
deep links and flutter applications
(a free article on medium),
it will continue to work until you opt in to this behavior by adding
FlutterDeepLinkingEnabled to info.plist or
flutter_deeplinking_enabled to AndroidManifest.xml, respectively.
<topic_end>
<topic_start>
behavior
the behavior varies slightly based on the platform and whether the app is
launched and running.
when using the router widget,
your app has the ability to replace the
current set of pages when a new deep link
is opened while the app is running.
<topic_end>
<topic_start>
for more information
learning flutter’s new navigation and routing system provides an
introduction to the router system.
<topic_end>
<topic_start>
set up app links for android
deep linking is a mechanism for launching an app with a URI.
this URI contains scheme, host, and path,
and opens the app to a specific screen.
a app link is a type of deep link that uses
http or https and is exclusive to android devices.
setting up app links requires one to own a web domain.
otherwise, consider using firebase hosting
or GitHub pages as a temporary solution.
<topic_end>
<topic_start>
1. customize a flutter application
write a flutter app that can handle an incoming URL.
this example uses the go_router package to handle the routing.
the flutter team maintains the go_router package.
it provides a simple API to handle complex routing scenarios.
to create a new application, type flutter create <app-name>:
to include go_router package in your app,
add a dependency for go_router to the project:
to add the go_router package as a dependency,
 run flutter pub add:
to handle the routing,
create a GoRouter object in the main.dart file:
<code_start>
import 'package:flutter/material.dart';
 import 'package:go_router/go_router.dart';
 void main() => runApp(MaterialApp.router(routerConfig: router));
 /// this handles '/' and '/details'.
 final router = GoRouter(
   routes: [
     GoRoute(
       path: '/',
       builder: (_, __) => scaffold(
         appBar: AppBar(title: const Text('Home screen')),
       ),
       routes: [
         GoRoute(
           path: 'details',
           builder: (_, __) => scaffold(
             appBar: AppBar(title: const Text('Details screen')),
           ),
         ),
       ],
     ),
   ],
 );
<code_end>
<topic_end>
<topic_start>
2. modify AndroidManifest.xml
add the following metadata tag and intent filter inside the
<activity> tag with .mainactivity.
replace example.com with your own web domain.
info note
  the metadata tag flutter_deeplinking_enabled opts
  into flutter’s default deeplink handler.
  if you are using the third-party plugins,
  such as uni_links, setting this metadata tag will
  break these plugins. omit this metadata tag
  if you prefer to use third-party plugins.
<topic_end>
<topic_start>
3. hosting assetlinks.json file
host an assetlinks.json file in using a web server
with a domain that you own. this file tells the
mobile browser which android application to open instead
of the browser. to create the file,
get the package name of the flutter app you created in
the previous step and the sha256 fingerprint of the
signing key you will be using to build the APK.
<topic_end>
<topic_start>
package name
locate the package name in AndroidManifest.xml,
the package property under <manifest> tag.
package names are usually in the format of com.example.*.
<topic_end>
<topic_start>
sha256 fingerprint
the process might differ depending on how the apk is signed.
<topic_end>
<topic_start>
using google play app signing
you can find the sha256 fingerprint directly from play
developer console. open your app in the play console,
under release> setup > app integrity> app signing tab:
<topic_end>
<topic_start>
using local keystore
if you are storing the key locally,
you can generate sha256 using the following command:
<topic_end>
<topic_start>
assetlinks.json
the hosted file should look similar to this:
set the package_name value to your android application ID.
set sha256_cert_fingerprints to the value you got
from the previous step.
host the file at a URL that resembles the following:
<webdomain>/.well-known/assetlinks.json
verify that your browser can access this file.
<topic_end>
<topic_start>
testing
you can use a real device or the emulator to test an app link,
but first make sure you have executed flutter run at least once on
the devices. this ensures that the flutter application is installed.
to test only the app setup, use the adb command:
info note
   this doesn’t test whether the web files are
   hosted correctly,
   the command launches the app even
   if web files are not presented.
to test both web and app setup, you must click a link
directly through web browser or another app.
one way is to create a google doc, add the link, and tap on it.
if everything is set up correctly, the flutter application
launches and displays the details screen:
<topic_end>
<topic_start>
appendix
source code: deeplink_cookbook
<topic_end>
<topic_start>
set up universal links for iOS
deep linking is a mechanism for launching an app with a URI. this URI
contains scheme, host, and path, and opens the app to a specific
screen.
a universal link is a type of deep link that uses http or https
and is exclusive to apple devices.
setting up universal links requires one to own a web domain.
otherwise, consider using firebase hosting or GitHub pages
as a temporary solution.
<topic_end>
<topic_start>
1. customize a flutter application
write a flutter app that can handle an incoming URL.
this example uses the go_router package to handle the routing.
the flutter team maintains the go_router package.
it provides a simple API to handle complex routing scenarios.
to create a new application, type flutter create <app-name>.
to include the go_router package as a dependency,
run flutter pub add:
to handle the routing, create a GoRouter object in the main.dart file:
<code_start>
import 'package:flutter/material.dart';
 import 'package:go_router/go_router.dart';
 void main() => runApp(MaterialApp.router(routerConfig: router));
 /// this handles '/' and '/details'.
 final router = GoRouter(
   routes: [
     GoRoute(
       path: '/',
       builder: (_, __) => scaffold(
         appBar: AppBar(title: const Text('Home screen')),
       ),
       routes: [
         GoRoute(
           path: 'details',
           builder: (_, __) => scaffold(
             appBar: AppBar(title: const Text('Details screen')),
           ),
         ),
       ],
     ),
   ],
 );
<code_end>
<topic_end>
<topic_start>
2. adjust iOS build settings
navigate to the info plist file in the ios/Runner folder.
update the key to FlutterDeepLinkingEnabled with a boolean value set to YES.
info note
    the FlutterDeepLinkingEnabled property opts into flutter’s default deeplink handler. if
    you are using the third-party plugins, such as uni_links, setting this property will
    break these plugins. skip this step if you prefer to use third-party plugins.
click associated domains.
enter applinks:<web domain>. replace <web domain> with your own domain name.
you have finished configuring the application for deep linking.
<topic_end>
<topic_start>
3. hosting apple-app-site-association file
you need to host an apple-app-site-association file in the web domain.
this file tells the mobile browser which iOS application to open instead of the browser.
to create the file, get the app ID of the flutter app you created in the previous step.
<topic_end>
<topic_start>
app ID
apple formats the app ID as <team id>.<bundle id>.
for example: given a team ID of S8QB4VV633
and a bundle ID of com.example.deeplinkCookbook, the app ID is
S8QB4VV633.com.example.deeplinkCookbook.
<topic_end>
<topic_start>
apple-app-site-association
the hosted file should have the following content:
set the appID value to <team id>.<bundle id>.
set the paths value to ["*"].
the paths field specifies the allowed universal links.
using the asterisk, * redirects every path to the flutter application.
if needed, change the paths value to a setting more appropriate
to your app.
host the file at a URL that resembles the following:
<webdomain>/.well-known/apple-app-site-association
verify that your browser can access this file.
<topic_end>
<topic_start>
testing
info note
  it might take up to 24 hours before apple’s
  content delivery network (cdn)
  requests the apple-app-site-association (aasa) file from your web domain.
  the universal link won’t work until the CDN requests the file.
  to bypass apple’s CDN, check out the alternate mode section.
you can use a real device or the simulator to test a universal link,
but first make sure you have executed flutter run at least once on
the devices. this ensures that the flutter application is installed.
if using the simulator, test using the xcode CLI:
otherwise, type the URL in the note app and click it.
if everything is set up correctly, the flutter application
launches and displays the details screen:
<topic_end>
<topic_start>
appendix
source code: deeplink_cookbook
<topic_end>
<topic_start>
configuring the URL strategy on the web
flutter web apps support two ways of configuring
URL-based navigation on the web:
<topic_end>
<topic_start>
configuring the URL strategy
to configure flutter to use the path instead, use the
usePathUrlStrategy function provided by the flutter_web_plugins library
in the SDK:
<topic_end>
<topic_start>
configuring your web server
PathUrlStrategy uses the history API, which requires additional
configuration for web servers.
to configure your web server to support PathUrlStrategy, check your web server’s
documentation to rewrite requests to index.html.Check your web server’s
documentation for details on how to configure single-page apps.
if you are using firebase hosting, choose the “configure as a single-page app”
option when initializing your project. for more information see firebase’s
configure rewrites documentation.
the local dev server created by running flutter run -d chrome is configured to
handle any path gracefully and fallback to your app’s index.html file.
<topic_end>
<topic_start>
hosting a flutter app at a non-root location
update the <base href="/"> tag in web/index.html
to the path where your app is hosted.
for example, to host your flutter app at
my_app.dev/flutter_app, change
this tag to <base href="/flutter_app/">.
<topic_end>
<topic_start>
introduction to animations
well-designed animations make a UI feel more intuitive,
contribute to the slick look and feel of a polished app,
and improve the user experience.
flutter’s animation support makes it easy to implement a variety of
animation types. many widgets, especially material widgets,
come with the standard motion effects defined in their design spec,
but it’s also possible to customize these effects.
<topic_end>
<topic_start>
choosing an approach
there are different approaches you can take when creating
animations in flutter. which approach is right for you?
to help you decide, check out the video,
how to choose which flutter animation widget is right for you?
(also published as a companion article.)
(to dive deeper into the decision process,
watch the animations in flutter done right video,
presented at flutter europe.)
as shown in the video, the following
decision tree helps you decide what approach
to use when implementing a flutter animation:
if a pre-packaged implicit animation (the easiest animation
to implement) suits your needs, watch
animation basics with implicit animations.
(also published as a companion article.)
learn about animation basics with implicit animations
to create a custom implicit animation, watch
creating your own custom implicit animations with TweenAnimationBuilder.
(also published as a companion article.)
learn about building custom implicit animations with TweenAnimationBuilder
to create an explicit animation (where you control the animation,
rather than letting the framework control it), perhaps
you can use one of the built-in explicit animations classes.
for more information, watch
making your first directional animations with
built-in explicit animations.
(also published as a companion article.)
if you need to build an explicit animation from scratch, watch
creating custom explicit animations with
AnimatedBuilder and AnimatedWidget.
(also published as a companion article.)
for a deeper understanding of just how animations work in flutter, watch
animation deep dive.
(also published as a companion article.)
<topic_end>
<topic_start>
codelabs, tutorials, and articles
the following resources are a good place to start learning
the flutter animation framework. each of these documents
shows how to write animation code.
implicit animations codelab
covers how to use implicit animations
using step-by-step instructions and interactive examples.
animations tutorial
explains the fundamental classes in the flutter animation package
(controllers, animatable, curves, listeners, builders),
as it guides you through a progression of tween animations using
different aspects of the animation APIs. this tutorial shows
how to create your own custom explicit animations.
zero to one with flutter, part 1 and part 2
medium articles showing how to create an animated chart using tweening.
write your first flutter app on the web
codelab demonstrating how to create a form
that uses animation to show the user’s progress
as they fill in the fields.
<topic_end>
<topic_start>
animation types
generally, animations are either tween- or physics-based.
the following sections explain what these terms mean,
and point you to resources where you can learn more.
<topic_end>
<topic_start>
tween animation
short for in-betweening. in a tween animation, the beginning
and ending points are defined, as well as a timeline, and a curve
that defines the timing and speed of the transition.
the framework calculates how to transition from the beginning point
to the end point.
the documents listed above, such as the
animations tutorial, are not specifically
about tweening, but they use tweens in their examples.
<topic_end>
<topic_start>
physics-based animation
in physics-based animation, motion is modeled to resemble real-world
behavior. when you toss a ball, for example, where and when it lands
depends on how fast it was tossed and how far it was from the ground.
similarly, dropping a ball attached to a spring falls
(and bounces) differently than dropping a ball attached to a string.
animate a widget using a physics simulation
a recipe in the animations section of the flutter cookbook.
also see the API documentation for
AnimationController.animateWith and
SpringSimulation.
<topic_end>
<topic_start>
pre-canned animations
if you are using material widgets, you might check
out the animations package available on pub.dev.
this package contains pre-built animations for
the following commonly used patterns:
container transforms, shared axis transitions,
fade through transitions, and fade transitions.
<topic_end>
<topic_start>
common animation patterns
most UX or motion designers find that certain
animation patterns are used repeatedly when designing a UI.
this section lists some of the commonly
used animation patterns, and tells you where to learn more.
<topic_end>
<topic_start>
animated list or grid
this pattern involves animating the addition or removal of
elements from a list or grid.
<topic_end>
<topic_start>
shared element transition
in this pattern, the user selects an element—often an
image—from the page, and the UI animates the selected element
to a new page with more detail. in flutter, you can easily implement
shared element transitions between routes (pages)
using the hero widget.
<topic_end>
<topic_start>
staggered animation
animations that are broken into smaller motions,
where some of the motion is delayed.
the smaller animations might be sequential,
or might partially or completely overlap.
<topic_end>
<topic_start>
other resources
learn more about flutter animations at the following links:
animation samples from the sample app catalog.
animation recipes from the flutter cookbook.
animation videos from the flutter YouTube channel.
animations: overview
a look at some of the major classes in the
animations library, and flutter’s animation architecture.
animation and motion widgets
a catalog of some of the animation widgets
provided in the flutter APIs.
the animation library in the flutter API documentation
the animation API for the flutter framework. this link
takes you to a technical overview page for the library.
<topic_end>
<topic_start>
animations tutorial
<topic_end>
<topic_start>
what you'll learn
this tutorial shows you how to build explicit animations in flutter.
after introducing some of the essential concepts, classes,
and methods in the animation library, it walks you through 5
animation examples. the examples build on each other,
introducing you to different aspects of the animation library.
the flutter SDK also provides built-in explicit animations,
such as FadeTransition, SizeTransition,
and SlideTransition. these simple animations are
triggered by setting a beginning and ending point.
they are simpler to implement
than custom explicit animations, which are described here.
<topic_end>
<topic_start>
essential animation concepts and classes
<topic_end>
<topic_start>
what's the point?
the animation system in flutter is based on typed
animation objects. widgets can either incorporate
these animations in their build functions directly by
reading their current value and listening to their state
changes or they can use the animations as the basis of
more elaborate animations that they pass along to
other widgets.
<topic_end>
<topic_start>
animation<double>
in flutter, an animation object knows nothing about what
is onscreen. an animation is an abstract class that
understands its current value and its state (completed or dismissed).
one of the more commonly used animation types is animation<double>.
an animation object sequentially generates
interpolated numbers between two values over a certain duration.
the output of an animation object might be linear,
a curve, a step function, or any other mapping you can devise.
depending on how the animation object is controlled,
it could run in reverse, or even switch directions in the
middle.
animations can also interpolate types other than double, such as
Animation<Color> or Animation<Size>.
an animation object has state. its current value is
always available in the .value member.
an animation object knows nothing about rendering or
build() functions.
<topic_end>
<topic_start>
Curved­Animation
a CurvedAnimation defines the animation’s progress
as a non-linear curve.
<code_start>
animation = CurvedAnimation(parent: controller, curve: Curves.easeIn);
<code_end>
info note
  the curves class defines many commonly used curves,
  or you can create your own. for example:
browse the curves documentation for a complete listing
  (with visual previews) of the curves constants that ship with flutter.
CurvedAnimation and AnimationController (described in the next section)
are both of type animation<double>, so you can pass them interchangeably.
the CurvedAnimation wraps the object it’s modifying—you
don’t subclass AnimationController to implement a curve.
<topic_end>
<topic_start>
Animation­Controller
AnimationController is a special animation
object that generates a new value whenever the hardware
is ready for a new frame. by default,
an AnimationController linearly produces the numbers
from 0.0 to 1.0 during a given duration.
for example, this code creates an animation object,
but does not start it running:
<code_start>
controller =
    AnimationController(duration: const duration(seconds: 2), vsync: this);
<code_end>
AnimationController derives from animation<double>, so it can be used
wherever an animation object is needed. however, the AnimationController
has additional methods to control the animation. for example, you start
an animation with the .forward() method. the generation of numbers is
tied to the screen refresh, so typically 60 numbers are generated per
second. after each number is generated, each animation object calls the
attached listener objects. to create a custom display list for each
child, see RepaintBoundary.
when creating an AnimationController, you pass it a vsync argument.
the presence of vsync prevents offscreen animations from consuming
unnecessary resources.
you can use your stateful object as the vsync by adding
SingleTickerProviderStateMixin to the class definition.
you can see an example of this in animate1 on GitHub.
info note
  in some cases, a position might exceed the AnimationController’s
  0.0-1.0 range. for example, the fling() function
  allows you to provide velocity, force, and position
  (via the force object). the position can be anything and
  so can be outside of the 0.0 to 1.0 range.
a CurvedAnimation can also exceed the 0.0 to 1.0 range,
  even if the AnimationController doesn’t.
  depending on the curve selected, the output of
  the CurvedAnimation can have a wider range than the input.
  for example, elastic curves such as Curves.elasticIn
  significantly overshoots or undershoots the default range.
<topic_end>
<topic_start>
tween
by default, the AnimationController object ranges from 0.0 to 1.0.
if you need a different range or a different data type, you can use a
tween to configure an animation to interpolate to a
different range or data type. for example, the
following tween goes from -200.0 to 0.0:
<code_start>
tween = tween<double>(begin: -200, end: 0);
<code_end>
a tween is a stateless object that takes only begin and end.
the sole job of a tween is to define a mapping from an
input range to an output range. the input range is commonly
0.0 to 1.0, but that’s not a requirement.
a tween inherits from Animatable<T>, not from Animation<T>.
an animatable, like animation, doesn’t have to output double.
for example, ColorTween specifies a progression between two colors.
<code_start>
colorTween = ColorTween(begin: colors.transparent, end: colors.black54);
<code_end>
a tween object doesn’t store any state. instead, it provides the
evaluate(Animation<double> animation) method that uses the 
transform function to map the current value of the animation
(between 0.0 and 1.0), to the actual animation value.
the current value of the animation object can be found in the
.value method. the evaluate function also performs some housekeeping,
such as ensuring that begin and end are returned when the
animation values are 0.0 and 1.0, respectively.
<topic_end>
<topic_start>
tween.animate
to use a tween object, call animate() on the tween,
passing in the controller object. for example,
the following code generates the
integer values from 0 to 255 over the course of 500 ms.
<code_start>
AnimationController controller = AnimationController(
    duration: const duration(milliseconds: 500), vsync: this);
animation<int> alpha = IntTween(begin: 0, end: 255).animate(controller);
<code_end>
info note
  the animate() method returns an animation,
  not an animatable.
the following example shows a controller, a curve, and a tween:
<code_start>
AnimationController controller = AnimationController(
    duration: const duration(milliseconds: 500), vsync: this);
final animation<double> curve =
    CurvedAnimation(parent: controller, curve: Curves.easeOut);
animation<int> alpha = IntTween(begin: 0, end: 255).animate(curve);
<code_end>
<topic_end>
<topic_start>
animation notifications
an animation object can have listeners and StatusListeners,
defined with addListener() and addStatusListener().
a listener is called whenever the value of the animation changes.
the most common behavior of a listener is to call setState()
to cause a rebuild. a StatusListener is called when an animation begins,
ends, moves forward, or moves reverse, as defined by AnimationStatus.
the next section has an example of the addListener() method,
and monitoring the progress of the animation shows an
example of addStatusListener().
<topic_end>
<topic_start>
animation examples
this section walks you through 5 animation examples.
each section provides a link to the source code for that example.
<topic_end>
<topic_start>
rendering animations
<topic_end>
<topic_start>
what's the point?
so far you’ve learned how to generate a sequence of numbers over time.
nothing has been rendered to the screen. to render with an
animation object, store the animation object as a
member of your widget, then use its value to decide how to draw.
consider the following app that draws the flutter logo without animation:
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const LogoApp());
class LogoApp extends StatefulWidget {
  const LogoApp({super.key});
  @override
  State<LogoApp> createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> {
  @override
  widget build(BuildContext context) {
    return center(
      child: container(
        margin: const EdgeInsets.symmetric(vertical: 10),
        height: 300,
        width: 300,
        child: const FlutterLogo(),
      ),
    );
  }
}
<code_end>
app source: animate0
the following shows the same code modified to animate the
logo to grow from nothing to full size.
when defining an AnimationController, you must pass in a
vsync object. the vsync parameter is described in the
AnimationController section.
the changes from the non-animated example are highlighted:
app source: animate1
the addListener() function calls setState(),
so every time the animation generates a new number,
the current frame is marked dirty, which forces
build() to be called again. in build(),
the container changes size because its height and
width now use animation.value instead of a hardcoded value.
dispose of the controller when the state object is
discarded to prevent memory leaks.
with these few changes,
you’ve created your first animation in flutter!
dart language tricks:
  you might not be familiar with dart’s cascade notation—the two
  dots in ..addListener(). this syntax means that the addListener()
  method is called with the return value from animate().
  consider the following example:
this code is equivalent to:
to learn more about cascades,
  check out cascade notation
  in the dart language documentation.
<topic_end>
<topic_start>
simplifying with Animated­Widget
<topic_end>
<topic_start>
what's the point?
the AnimatedWidget base class allows you to separate out
the core widget code from the animation code.
AnimatedWidget doesn’t need to maintain a state
object to hold the animation. add the following AnimatedLogo class:
<code_start>
class AnimatedLogo extends AnimatedWidget {
  const AnimatedLogo({super.key, required animation<double> animation})
      : super(listenable: animation);
  @override
  widget build(BuildContext context) {
    final animation = listenable as animation<double>;
    return center(
      child: container(
        margin: const EdgeInsets.symmetric(vertical: 10),
        height: animation.value,
        width: animation.value,
        child: const FlutterLogo(),
      ),
    );
  }
}
<code_end>
AnimatedLogo uses the current value of the animation
when drawing itself.
the LogoApp still manages the AnimationController and the tween,
and it passes the animation object to AnimatedLogo:
app source: animate2
<topic_end>
<topic_start>
monitoring the progress of the animation
<topic_end>
<topic_start>
what's the point?
it’s often helpful to know when an animation changes state,
such as finishing, moving forward, or reversing.
you can get notifications for this with addStatusListener().
the following code modifies the previous example so that
it listens for a state change and prints an update.
the highlighted line shows the change:
<code_start>
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
  late animation<double> animation;
  late AnimationController controller;
  @override
  void initState() {
    super.initState();
    controller =
        AnimationController(duration: const duration(seconds: 2), vsync: this);
    animation = tween<double>(begin: 0, end: 300).animate(controller)
      ..addStatusListener((status) => print('$status'));
    controller.forward();
  }
  // ...
}
<code_end>
running this code produces this output:
next, use addStatusListener() to reverse the animation
at the beginning or the end. this creates a “breathing” effect:
app source: animate3
<topic_end>
<topic_start>
refactoring with AnimatedBuilder
<topic_end>
<topic_start>
what's the point?
one problem with the code in the animate3 example,
is that changing the animation required changing the widget
that renders the logo. a better solution
is to separate responsibilities into different classes:
you can accomplish this separation with the help of the
AnimatedBuilder class. an AnimatedBuilder is a
separate class in the render tree. like AnimatedWidget,
AnimatedBuilder automatically listens to notifications
from the animation object, and marks the widget tree
dirty as necessary, so you don’t need to call addListener().
the widget tree for the animate4
example looks like this:
starting from the bottom of the widget tree, the code for rendering
the logo is straightforward:
<code_start>
class LogoWidget extends StatelessWidget {
  const LogoWidget({super.key});
  // leave out the height and width so it fills the animating parent
  @override
  widget build(BuildContext context) {
    return container(
      margin: const EdgeInsets.symmetric(vertical: 10),
      child: const FlutterLogo(),
    );
  }
}
<code_end>
the middle three blocks in the diagram are all created in the
build() method in GrowTransition, shown below.
the GrowTransition widget itself is stateless and holds
the set of final variables necessary to define the transition animation.
the build() function creates and returns the AnimatedBuilder,
which takes the (anonymous builder) method and the
LogoWidget object as parameters. the work of rendering the
transition actually happens in the (anonymous builder)
method, which creates a container of the appropriate size
to force the LogoWidget to shrink to fit.
one tricky point in the code below is that the child looks
like it’s specified twice. what’s happening is that the
outer reference of child is passed to AnimatedBuilder,
which passes it to the anonymous closure, which then uses
that object as its child. the net result is that the
AnimatedBuilder is inserted in between the two widgets
in the render tree.
<code_start>
class GrowTransition extends StatelessWidget {
  const GrowTransition(
      {required this.child, required this.animation, super.key});
  final widget child;
  final animation<double> animation;
  @override
  widget build(BuildContext context) {
    return center(
      child: AnimatedBuilder(
        animation: animation,
        builder: (context, child) {
          return SizedBox(
            height: animation.value,
            width: animation.value,
            child: child,
          );
        },
        child: child,
      ),
    );
  }
}
<code_end>
finally, the code to initialize the animation looks very
similar to the animate2 example. the initState()
method creates an AnimationController and a tween,
then binds them with animate(). the magic happens in
the build() method, which returns a GrowTransition
object with a LogoWidget as a child, and an animation object to
drive the transition. these are the three elements listed
in the bullet points above.
app source: animate4
<topic_end>
<topic_start>
simultaneous animations
<topic_end>
<topic_start>
what's the point?
in this section, you’ll build on the example from
monitoring the progress of the animation
(animate3), which used AnimatedWidget
to animate in and out continuously. consider the case
where you want to animate in and out while the
opacity animates from transparent to opaque.
info note
  this example shows how to use multiple tweens on the same animation
  controller, where each tween manages a different effect in
  the animation. it is for illustrative purposes only.
  if you were tweening opacity and size in production code,
  you’d probably use FadeTransition and SizeTransition
  instead.
each tween manages an aspect of the animation. for example:
<code_start>
controller =
    AnimationController(duration: const duration(seconds: 2), vsync: this);
sizeAnimation = tween<double>(begin: 0, end: 300).animate(controller);
opacityAnimation = tween<double>(begin: 0.1, end: 1).animate(controller);
<code_end>
you can get the size with sizeAnimation.value and the opacity
with opacityAnimation.value, but the constructor for AnimatedWidget
only takes a single animation object. to solve this problem,
the example creates its own tween objects and explicitly calculates the
values.
change AnimatedLogo to encapsulate its own tween objects,
and its build() method calls tween.evaluate()
on the parent’s animation object to calculate
the required size and opacity values.
the following code shows the changes with highlights:
<code_start>
class AnimatedLogo extends AnimatedWidget {
  const AnimatedLogo({super.key, required animation<double> animation})
      : super(listenable: animation);
  // make the tweens static because they don't change.
  static final _opacityTween = tween<double>(begin: 0.1, end: 1);
  static final _sizeTween = tween<double>(begin: 0, end: 300);
  @override
  widget build(BuildContext context) {
    final animation = listenable as animation<double>;
    return center(
      child: opacity(
        opacity: _opacityTween.evaluate(animation),
        child: container(
          margin: const EdgeInsets.symmetric(vertical: 10),
          height: _sizeTween.evaluate(animation),
          width: _sizeTween.evaluate(animation),
          child: const FlutterLogo(),
        ),
      ),
    );
  }
}
class LogoApp extends StatefulWidget {
  const LogoApp({super.key});
  @override
  State<LogoApp> createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
  late animation<double> animation;
  late AnimationController controller;
  @override
  void initState() {
    super.initState();
    controller =
        AnimationController(duration: const duration(seconds: 2), vsync: this);
    animation = CurvedAnimation(parent: controller, curve: Curves.easeIn)
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          controller.reverse();
        } else if (status == AnimationStatus.dismissed) {
          controller.forward();
        }
      });
    controller.forward();
  }
  @override
  widget build(BuildContext context) => AnimatedLogo(animation: animation);
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
<code_end>
app source: animate5
<topic_end>
<topic_start>
next steps
this tutorial gives you a foundation for creating animations in
flutter using tweens, but there are many other classes to explore.
you might investigate the specialized tween classes,
animations specific to material design,
ReverseAnimation,
shared element transitions (also known as hero animations),
physics simulations and fling() methods.
see the animations landing page
for the latest available documents and examples.
<topic_end>
<topic_start>
implicit animations
with flutter’s animation library,
you can add motion and create visual effects
for the widgets in your UI.
one part of the library is an assortment of widgets
that manage animations for you.
these widgets are collectively referred to as implicit animations,
or implicitly animated widgets, deriving their name from the
ImplicitlyAnimatedWidget class that they implement.
the following set of resources provide many ways to learn
about implicit animations in flutter.
<topic_end>
<topic_start>
documentation
<topic_end>
<topic_start>
flutter in focus videos
flutter in focus videos feature 5-10 minute tutorials
with real code that cover techniques
that every flutter dev needs to know from top to bottom.
the following videos cover topics
that are relevant to implicit animations.
learn about animation basics with implicit animations
learn about building custom implicit animations with TweenAnimationBuilder
<topic_end>
<topic_start>
the boring show
watch the boring show to follow google engineers build apps
from scratch in flutter. the following episode covers
using implicit animations in a news aggregator app.
learn about implicitly animating the hacker news app
<topic_end>
<topic_start>
widget of the week videos
a weekly series of short animated videos each showing
the important features of one particular widget.
in about 60 seconds, you’ll see real code for each
widget with a demo about how it works.
the following widget of the week videos cover
implicitly animated widgets:
learn about the AnimatedOpacity flutter widget
learn about the AnimatedPadding flutter widget
learn about the AnimatedPositioned flutter widget
learn about the AnimatedSwitcher flutter widget
<topic_end>
<topic_start>
animate the properties of a container
the container class provides a convenient way
to create a widget with specific properties:
width, height, background color, padding, borders, and more.
simple animations often involve changing these properties over time.
for example,
you might want to animate the background color from grey to green to
indicate that an item has been selected by the user.
to animate these properties,
flutter provides the AnimatedContainer widget.
like the container widget, AnimatedContainer allows you to define
the width, height, background colors, and more. however, when the
AnimatedContainer is rebuilt with new properties, it automatically
animates between the old and new values. in flutter, these types of
animations are known as “implicit animations.”
this recipe describes how to use an AnimatedContainer to animate the size,
background color, and border radius when the user taps a button
using the following steps:
<topic_end>
<topic_start>
1. create a StatefulWidget with default properties
to start, create StatefulWidget and state classes.
use the custom state class to define the properties that change over
time. in this example, that includes the width, height, color, and border
radius. you can also define the default value of each property.
these properties belong to a custom state class so they
can be updated when the user taps a button.
<code_start>
class AnimatedContainerApp extends StatefulWidget {
  const AnimatedContainerApp({super.key});
  @override
  State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}
class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
  // define the various properties with default values. update these properties
  // when the user taps a FloatingActionButton.
  double _width = 50;
  double _height = 50;
  color _color = colors.green;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);
  @override
  widget build(BuildContext context) {
    // fill this out in the next steps.
  }
}
<code_end>
<topic_end>
<topic_start>
2. build an AnimatedContainer using the properties
next, build the AnimatedContainer using the properties defined in the
previous step. furthermore, provide a duration that defines how long
the animation should run.
<code_start>
AnimatedContainer(
  // use the properties stored in the state class.
  width: _width,
  height: _height,
  decoration: BoxDecoration(
    color: _color,
    borderRadius: _borderRadius,
  ),
  // define how long the animation should take.
  duration: const duration(seconds: 1),
  // provide an optional curve to make the animation feel smoother.
  curve: Curves.fastOutSlowIn,
)
<code_end>
<topic_end>
<topic_start>
3. start the animation by rebuilding with new properties
finally, start the animation by rebuilding the
AnimatedContainer with the new properties.
how to trigger a rebuild?
use the setState() method.
add a button to the app. when the user taps the button, update
the properties with a new width, height, background color and border radius
inside a call to setState().
a real app typically transitions between fixed values (for example,
from a grey to a green background). for this app,
generate new values each time the user taps the button.
<code_start>
FloatingActionButton(
  // when the user taps the button
  onPressed: () {
    // use setState to rebuild the widget with new values.
    setState(() {
      // create a random number generator.
      final random = random();
      // generate a random width and height.
      _width = random.nextInt(300).toDouble();
      _height = random.nextInt(300).toDouble();
      // generate a random color.
      _color = Color.fromRGBO(
        random.nextInt(256),
        random.nextInt(256),
        random.nextInt(256),
        1,
      );
      // generate a random border radius.
      _borderRadius =
          BorderRadius.circular(random.nextInt(100).toDouble());
    });
  },
  child: const Icon(Icons.play_arrow),
)
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(const AnimatedContainerApp());
class AnimatedContainerApp extends StatefulWidget {
  const AnimatedContainerApp({super.key});
  @override
  State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}
class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
  // define the various properties with default values. update these properties
  // when the user taps a FloatingActionButton.
  double _width = 50;
  double _height = 50;
  color _color = colors.green;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      home: scaffold(
        appBar: AppBar(
          title: const Text('AnimatedContainer demo'),
        ),
        body: center(
          child: AnimatedContainer(
            // use the properties stored in the state class.
            width: _width,
            height: _height,
            decoration: BoxDecoration(
              color: _color,
              borderRadius: _borderRadius,
            ),
            // define how long the animation should take.
            duration: const duration(seconds: 1),
            // provide an optional curve to make the animation feel smoother.
            curve: Curves.fastOutSlowIn,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          // when the user taps the button
          onPressed: () {
            // use setState to rebuild the widget with new values.
            setState(() {
              // create a random number generator.
              final random = random();
              // generate a random width and height.
              _width = random.nextInt(300).toDouble();
              _height = random.nextInt(300).toDouble();
              // generate a random color.
              _color = Color.fromRGBO(
                random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256),
                1,
              );
              // generate a random border radius.
              _borderRadius =
                  BorderRadius.circular(random.nextInt(100).toDouble());
            });
          },
          child: const Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
fade a widget in and out
UI developers often need to show and hide elements on screen.
however, quickly popping elements on and off the screen can
feel jarring to end users. instead,
fade elements in and out with an opacity animation to create
a smooth experience.
the AnimatedOpacity widget makes it easy to perform opacity
animations. this recipe uses the following steps:
<topic_end>
<topic_start>
1. create a box to fade in and out
first, create something to fade in and out. for this example,
draw a green box on screen.
<code_start>
container(
  width: 200,
  height: 200,
  color: colors.green,
)
<code_end>
<topic_end>
<topic_start>
2. define a StatefulWidget
now that you have a green box to animate,
you need a way to know whether the box should be visible.
to accomplish this, use a StatefulWidget.
a StatefulWidget is a class that creates a state object.
the state object holds some data about the app and provides a way to
update that data. when updating the data,
you can also ask flutter to rebuild the UI with those changes.
in this case, you have one piece of data:
a boolean representing whether the button is visible.
to construct a StatefulWidget, create two classes: a
StatefulWidget and a corresponding state class.
pro tip: the flutter plugins for android studio and VSCode include
the stful snippet to quickly generate this code.
<code_start>
// the StatefulWidget's job is to take data and create a state class.
// in this case, the widget takes a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  final string title;
  const MyHomePage({
    super.key,
    required this.title,
  });
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
// the state class is responsible for two things: holding some data you can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // whether the green box should be visible.
  bool _visible = true;
  @override
  widget build(BuildContext context) {
    // the green box goes here with some other widgets.
  }
}
<code_end>
<topic_end>
<topic_start>
3. display a button that toggles the visibility
now that you have some data to determine whether the green box
should be visible, you need a way to update that data.
in this example, if the box is visible, hide it.
if the box is hidden, show it.
to handle this, display a button. when a user presses the button,
flip the boolean from true to false, or false to true.
make this change using setState(),
which is a method on the state class.
this tells flutter to rebuild the widget.
for more information on working with user input,
see the gestures section of the cookbook.
<code_start>
FloatingActionButton(
  onPressed: () {
    // call setState. this tells flutter to rebuild the
    // UI with the changes.
    setState(() {
      _visible = !_visible;
    });
  },
  tooltip: 'toggle opacity',
  child: const Icon(Icons.flip),
)
<code_end>
<topic_end>
<topic_start>
4. fade the box in and out
you have a green box on screen and a button to toggle the visibility
to true or false. how to fade the box in and out? with an
AnimatedOpacity widget.
the AnimatedOpacity widget requires three arguments:
<code_start>
AnimatedOpacity(
  // if the widget is visible, animate to 0.0 (invisible).
  // if the widget is hidden, animate to 1.0 (fully visible).
  opacity: _visible ? 1.0 : 0.0,
  duration: const duration(milliseconds: 500),
  // the green box must be a child of the AnimatedOpacity widget.
  child: container(
    width: 200,
    height: 200,
    color: colors.green,
  ),
)
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const appTitle = 'opacity demo';
    return const MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}
// the StatefulWidget's job is to take data and create a state class.
// in this case, the widget takes a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
    required this.title,
  });
  final string title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
// the state class is responsible for two things: holding some data you can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // whether the green box should be visible
  bool _visible = true;
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(widget.title),
      ),
      body: center(
        child: AnimatedOpacity(
          // if the widget is visible, animate to 0.0 (invisible).
          // if the widget is hidden, animate to 1.0 (fully visible).
          opacity: _visible ? 1.0 : 0.0,
          duration: const duration(milliseconds: 500),
          // the green box must be a child of the AnimatedOpacity widget.
          child: container(
            width: 200,
            height: 200,
            color: colors.green,
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // call setState. this tells flutter to rebuild the
          // UI with the changes.
          setState(() {
            _visible = !_visible;
          });
        },
        tooltip: 'toggle opacity',
        child: const Icon(Icons.flip),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
hero animations
<topic_end>
<topic_start>
what you'll learn
you’ve probably seen hero animations many times. for example, a screen displays
a list of thumbnails representing items for sale.  selecting an item flies it to
a new screen, containing more details and a “buy” button. flying an image from
one screen to another is called a hero animation in flutter, though the same
motion is sometimes referred to as a shared element transition.
you might want to watch this one-minute video introducing the hero widget:
this guide demonstrates how to build standard hero animations, and hero
animations that transform the image from a circular shape to a square shape
during flight.
examples: this guide provides examples of each hero animation style at
  the following links.
new to flutter?
  this page assumes you know how to create a layout
  using flutter’s widgets. for more information, see
  building layouts in flutter.
terminology:
  a route describes a page or screen in a flutter app.
you can create this animation in flutter with hero widgets.
as the hero animates from the source to the destination route,
the destination route (minus the hero) fades into view.
typically, heroes are small parts of the UI, like images,
that both routes have in common. from the user’s perspective
the hero “flies” between the routes. this guide shows how
to create the following hero animations:
standard hero animations
a standard hero animation flies the hero from one route to a new route,
usually landing at a different location and with a different size.
the following video (recorded at slow speed) shows a typical example.
tapping the flippers in the center of the route flies them to the
upper left corner of a new, blue route, at a smaller size.
tapping the flippers in the blue route (or using the device’s
back-to-previous-route gesture) flies the flippers back to
the original route.
radial hero animations
in radial hero animation, as the hero flies between routes
its shape appears to change from circular to rectangular.
the following video (recorded at slow speed),
shows an example of a radial hero animation. at the start, a
row of three circular images appears at the bottom of the route.
tapping any of the circular images flies that image to a new route
that displays it with a square shape.
tapping the square image flies the hero back to
the original route, displayed with a circular shape.
before moving to the sections specific to
standard
or radial hero animations,
read basic structure of a hero animation
to learn how to structure hero animation code,
and behind the scenes to understand
how flutter performs a hero animation.
<topic_end>
<topic_start>
basic structure of a hero animation
<topic_end>
<topic_start>
what's the point?
terminology:
  if the concept of tweens or tweening is new to you,
  see the animations in flutter tutorial.
hero animations are implemented using two hero
widgets: one describing the widget in the source route,
and another describing the widget in the destination route.
from the user’s point of view, the hero appears to be shared, and
only the programmer needs to understand this implementation detail.
hero animation code has the following structure:
flutter calculates the tween that animates the hero’s bounds from
the starting point to the endpoint (interpolating size and position),
and performs the animation in an overlay.
the next section describes flutter’s process in greater detail.
<topic_end>
<topic_start>
behind the scenes
the following describes how flutter performs the
transition from one route to another.
before transition, the source hero waits in the source
route’s widget tree. the destination route does not yet exist,
and the overlay is empty.
pushing a route to the navigator triggers the animation.
at t=0.0, flutter does the following:
calculates the destination hero’s path, offscreen,
using the curved motion as described in the material
motion spec. flutter now knows where the hero ends up.
places the destination hero in the overlay,
at the same location and size as the source hero.
adding a hero to the overlay changes its z-order so that it
appears on top of all routes.
moves the source hero offscreen.
as the hero flies, its rectangular bounds are animated using
Tween<Rect>, specified in hero’s
createRectTween property.
by default, flutter uses an instance of
MaterialRectArcTween, which animates the
rectangle’s opposing corners along a curved path.
(see radial hero animations for an example
that uses a different tween animation.)
when the flight completes:
flutter moves the hero widget from the overlay to
the destination route. the overlay is now empty.
the destination hero appears in its final position
in the destination route.
the source hero is restored to its route.
popping the route performs the same process,
animating the hero back to its size
and location in the source route.
<topic_end>
<topic_start>
essential classes
the examples in this guide use the following classes to
implement hero animations:
<topic_end>
<topic_start>
standard hero animations
<topic_end>
<topic_start>
what's the point?
standard hero animation code
each of the following examples demonstrates flying an image from one
  route to another. this guide describes the first example.
<topic_end>
<topic_start>
what’s going on?
flying an image from one route to another is easy to implement
using flutter’s hero widget. when using MaterialPageRoute
to specify the new route, the image flies along a curved path,
as described by the material design motion spec.
create a new flutter example and
update it using the files from the hero_animation.
to run the example:
<topic_end>
<topic_start>
PhotoHero class
the custom PhotoHero class maintains the hero,
and its size, image, and behavior when tapped.
the PhotoHero builds the following widget tree:
here’s the code:
key information:
<topic_end>
<topic_start>
HeroAnimation class
the HeroAnimation class creates the source and destination
PhotoHeroes, and sets up the transition.
here’s the code:
key information:
<topic_end>
<topic_start>
radial hero animations
<topic_end>
<topic_start>
what's the point?
flying a hero from one route to another as it transforms
from a circular shape to a rectangular shape is a slick
effect that you can implement using hero widgets.
to accomplish this, the code animates the intersection of
two clip shapes: a circle and a square.
throughout the animation, the circle clip (and the image)
scales from minRadius to maxRadius, while the square
clip maintains constant size. at the same time,
the image flies from its position in the source route to its
position in the destination route. for visual examples
of this transition, see radial transformation
in the material motion spec.
this animation might seem complex (and it is), but you can customize the
provided example to your needs. the heavy lifting is done for you.
radial hero animation code
each of the following examples demonstrates a radial hero animation.
  this guide describes the first example.
pro tip:
  the radial hero animation involves intersecting a round shape with
  a square shape. this can be hard to see, even when slowing
  the animation with timeDilation, so you might consider enabling
  the debugPaintSizeEnabled flag during development.
<topic_end>
<topic_start>
what’s going on?
the following diagram shows the clipped image at the beginning
(t = 0.0), and the end (t = 1.0) of the animation.
the blue gradient (representing the image), indicates where the clip
shapes intersect. at the beginning of the transition,
the result of the intersection is a circular clip (clipoval).
during the transformation, the ClipOval scales from minRadius
to maxRadius while the ClipRect maintains a constant size.
at the end of the transition the intersection of the circular and
rectangular clips yield a rectangle that’s the same size as the hero
widget. in other words, at the end of the transition the image is no
longer clipped.
create a new flutter example and
update it using the files from the
radial_hero_animation GitHub directory.
to run the example:
<topic_end>
<topic_start>
photo class
the photo class builds the widget tree that holds the image:
key information:
<topic_end>
<topic_start>
RadialExpansion class
the RadialExpansion widget, the core of the demo, builds the
widget tree that clips the image during the transition.
the clipped shape results from the intersection of a circular clip
(that grows during flight),
with a rectangular clip (that remains a constant size throughout).
to do this, it builds the following widget tree:
here’s the code:
key information:
the example defines the tweening interpolation using
MaterialRectCenterArcTween.
the default flight path for a hero animation
interpolates the tweens using the corners of the heroes.
this approach affects the hero’s aspect ratio during
the radial transformation, so the new flight path uses
MaterialRectCenterArcTween to interpolate the tweens using the
center point of each hero.
here’s the code:
the hero’s flight path still follows an arc,
but the image’s aspect ratio remains constant.
<topic_end>
<topic_start>
animate a page route transition
a design language, such as material, defines standard behaviors when
transitioning between routes (or screens). sometimes, though, a custom
transition between screens can make an app more unique. to help,
PageRouteBuilder provides an animation object.
this animation can be used with tween and
curve objects to customize the transition animation.
this recipe shows how to transition between
routes by animating the new route into view from
the bottom of the screen.
to create a custom page route transition, this recipe uses the following steps:
<topic_end>
<topic_start>
1. set up a PageRouteBuilder
to start, use a PageRouteBuilder to create a route.
PageRouteBuilder has two callbacks, one to build the content of the route
(pagebuilder), and one to build the route’s transition (transitionsbuilder).
info note
  the child parameter in transitionsBuilder is the widget returned from
  pageBuilder. the pageBuilder function is only called the first time the
  route is built. the framework can avoid extra work because child stays the
  same throughout the transition.
the following example creates two routes: a home route with a “go!” button, and
a second route titled “page 2”.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: page1(),
    ),
  );
}
class page1 extends StatelessWidget {
  const page1({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(),
      body: center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.of(context).push(_createRoute());
          },
          child: const Text('Go!'),
        ),
      ),
    );
  }
}
route _createRoute() {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => const page2(),
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      return child;
    },
  );
}
class page2 extends StatelessWidget {
  const page2({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(),
      body: const center(
        child: Text('Page 2'),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
2. create a tween
to make the new page animate in from the bottom, it should animate from
offset(0,1) to offset(0, 0) (usually defined using the offset.zero
constructor). in this case, the offset is a 2d vector for the
‘fractionaltranslation’ widget.
setting the dy argument to 1 represents a vertical translation one
full height of the page.
the transitionsBuilder callback has an animation parameter. it’s an
animation<double> that produces values between 0 and 1. convert the
animation into an animation using a tween:
<code_start>
transitionsBuilder: (context, animation, secondaryAnimation, child) {
  const begin = offset(0.0, 1.0);
  const end = offset.zero;
  final tween = tween(begin: begin, end: end);
  final offsetAnimation = animation.drive(tween);
  return child;
},
<code_end>
<topic_end>
<topic_start>
3. use an AnimatedWidget
flutter has a set of widgets extending AnimatedWidget
that rebuild themselves when the value of the animation changes. for instance,
SlideTransition takes an Animation<Offset> and translates its child (using a
FractionalTranslation widget) whenever the value of the animation changes.
AnimatedWidget return a SlideTransition
with the Animation<Offset> and the child widget:
<code_start>
transitionsBuilder: (context, animation, secondaryAnimation, child) {
  const begin = offset(0.0, 1.0);
  const end = offset.zero;
  final tween = tween(begin: begin, end: end);
  final offsetAnimation = animation.drive(tween);
  return SlideTransition(
    position: offsetAnimation,
    child: child,
  );
},
<code_end>
<topic_end>
<topic_start>
4. use a CurveTween
flutter provides a selection of easing curves that
adjust the rate of the animation over time.
the curves class
provides a predefined set of commonly used curves.
for example, Curves.easeOut
makes the animation start quickly and end slowly.
to use a curve, create a new CurveTween
and pass it a curve:
<code_start>
var curve = curves.ease;
var curveTween = CurveTween(curve: curve);
<code_end>
this new tween still produces values from 0 to 1. in the next step, it will be
combined the Tween<Offset> from step 2.
<topic_end>
<topic_start>
5. combine the two tweens
to combine the tweens,
use chain():
<code_start>
const begin = offset(0.0, 1.0);
const end = offset.zero;
const curve = curves.ease;
var tween = tween(begin: begin, end: end).chain(CurveTween(curve: curve));
<code_end>
then use this tween by passing it to animation.drive(). this creates a new
Animation<Offset> that can be given to the SlideTransition widget:
<code_start>
return SlideTransition(
  position: animation.drive(tween),
  child: child,
);
<code_end>
this new tween (or animatable) produces offset values by first evaluating the
CurveTween, then evaluating the Tween<Offset>. when the animation runs, the
values are computed in this order:
another way to create an Animation<Offset> with an easing curve is to use a
CurvedAnimation:
<code_start>
transitionsBuilder: (context, animation, secondaryAnimation, child) {
  const begin = offset(0.0, 1.0);
  const end = offset.zero;
  const curve = curves.ease;
  final tween = tween(begin: begin, end: end);
  final curvedAnimation = CurvedAnimation(
    parent: animation,
    curve: curve,
  );
  return SlideTransition(
    position: tween.animate(curvedAnimation),
    child: child,
  );
}
<code_end>
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: page1(),
    ),
  );
}
class page1 extends StatelessWidget {
  const page1({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(),
      body: center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.of(context).push(_createRoute());
          },
          child: const Text('Go!'),
        ),
      ),
    );
  }
}
route _createRoute() {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => const page2(),
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      const begin = offset(0.0, 1.0);
      const end = offset.zero;
      const curve = curves.ease;
      var tween = tween(begin: begin, end: end).chain(CurveTween(curve: curve));
      return SlideTransition(
        position: animation.drive(tween),
        child: child,
      );
    },
  );
}
class page2 extends StatelessWidget {
  const page2({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(),
      body: const center(
        child: Text('Page 2'),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
animate a widget using a physics simulation
physics simulations can make app interactions feel realistic and interactive.
for example, you might want to animate a widget to act as if it were attached to
a spring or falling with gravity.
this recipe demonstrates how to move a widget from a dragged point back to the
center using a spring simulation.
this recipe uses these steps:
<topic_end>
<topic_start>
step 1: set up an animation controller
start with a stateful widget called DraggableCard:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(const MaterialApp(home: PhysicsCardDragDemo()));
}
class PhysicsCardDragDemo extends StatelessWidget {
  const PhysicsCardDragDemo({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(),
      body: const DraggableCard(
        child: FlutterLogo(
          size: 128,
        ),
      ),
    );
  }
}
class DraggableCard extends StatefulWidget {
  const DraggableCard({required this.child, super.key});
  final widget child;
  @override
  State<DraggableCard> createState() => _DraggableCardState();
}
class _DraggableCardState extends State<DraggableCard> {
  @override
  void initState() {
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return align(
      child: card(
        child: widget.child,
      ),
    );
  }
}
<code_end>
make the _DraggableCardState class extend from
SingleTickerProviderStateMixin.
then construct an AnimationController in
initState and set vsync to this.
info note
  extending SingleTickerProviderStateMixin allows the state object to be a
  TickerProvider for the AnimationController. for more information, see the
  documentation for TickerProvider.
<topic_end>
<topic_start>
step 2: move the widget using gestures
make the widget move when it’s dragged, and add an alignment field to the
_DraggableCardState class:
add a GestureDetector that handles the onPanDown, onPanUpdate, and
onPanEnd callbacks. to adjust the alignment, use a MediaQuery to get the
size of the widget, and divide by 2. (this converts units of “pixels dragged” to
coordinates that align uses.) then, set the align widget’s alignment to
_dragAlignment:
<topic_end>
<topic_start>
step 3: animate the widget
when the widget is released, it should spring back to the center.
add an Animation<Alignment> field and an _runAnimation method. this
method defines a tween that interpolates between the point the widget was
dragged to, to the point in the center.
<code_start>
void _runAnimation() {
  _animation = _controller.drive(
    AlignmentTween(
      begin: _dragAlignment,
      end: alignment.center,
    ),
  );
  _controller.reset();
  _controller.forward();
}
<code_end>
next, update _dragAlignment when the AnimationController produces a
value:
next, make the align widget use the _dragAlignment field:
<code_start>
child: align(
  alignment: _dragAlignment,
  child: card(
    child: widget.child,
  ),
),
<code_end>
finally, update the GestureDetector to manage the animation controller:
<topic_end>
<topic_start>
step 4: calculate the velocity to simulate a springing motion
the last step is to do a little math, to calculate the velocity of the widget
after it’s finished being dragged. this is so that the widget realistically
continues at that speed before being snapped back. (the _runAnimation method
already sets the direction by setting the animation’s start and end alignment.)
first, import the physics package:
<code_start>
import 'package:flutter/physics.dart';
<code_end>
the onPanEnd callback provides a DragEndDetails object. this object
provides the velocity of the pointer when it stopped contacting the screen. the
velocity is in pixels per second, but the align widget doesn’t use pixels. it
uses coordinate values between [-1.0, -1.0] and [1.0, 1.0], where [0.0, 0.0]
represents the center. the size calculated in step 2 is used to convert pixels
to coordinate values in this range.
finally, AnimationController has an animateWith() method that can be given a
SpringSimulation:
<code_start>
/// calculates and runs a [springsimulation].
void _runAnimation(Offset pixelsPerSecond, size size) {
  _animation = _controller.drive(
    AlignmentTween(
      begin: _dragAlignment,
      end: alignment.center,
    ),
  );
  // calculate the velocity relative to the unit interval, [0,1],
  // used by the animation controller.
  final unitsPerSecondX = pixelsPerSecond.dx / size.width;
  final unitsPerSecondY = pixelsPerSecond.dy / size.height;
  final unitsPerSecond = Offset(unitsPerSecondX, unitsPerSecondY);
  final unitVelocity = unitsPerSecond.distance;
  const spring = SpringDescription(
    mass: 30,
    stiffness: 1,
    damping: 1,
  );
  final simulation = SpringSimulation(spring, 0, 1, -unitvelocity);
  _controller.animateWith(simulation);
}
<code_end>
don’t forget to call _runAnimation()  with the velocity and size:
<code_start>
onPanEnd: (details) {
  _runAnimation(details.velocity.pixelsPerSecond, size);
},
<code_end>
info note
  now that the animation controller uses a simulation it’s duration argument
  is no longer required.
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
void main() {
  runApp(const MaterialApp(home: PhysicsCardDragDemo()));
}
class PhysicsCardDragDemo extends StatelessWidget {
  const PhysicsCardDragDemo({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(),
      body: const DraggableCard(
        child: FlutterLogo(
          size: 128,
        ),
      ),
    );
  }
}
/// a draggable card that moves back to [alignment.center] when it's
/// released.
class DraggableCard extends StatefulWidget {
  const DraggableCard({required this.child, super.key});
  final widget child;
  @override
  State<DraggableCard> createState() => _DraggableCardState();
}
class _DraggableCardState extends State<DraggableCard>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  /// the alignment of the card as it is dragged or being animated.
  ///
  /// while the card is being dragged, this value is set to the values computed
  /// in the GestureDetector onPanUpdate callback. if the animation is running,
  /// this value is set to the value of the [_animation].
  alignment _dragAlignment = alignment.center;
  late Animation<Alignment> _animation;
  /// calculates and runs a [springsimulation].
  void _runAnimation(Offset pixelsPerSecond, size size) {
    _animation = _controller.drive(
      AlignmentTween(
        begin: _dragAlignment,
        end: alignment.center,
      ),
    );
    // calculate the velocity relative to the unit interval, [0,1],
    // used by the animation controller.
    final unitsPerSecondX = pixelsPerSecond.dx / size.width;
    final unitsPerSecondY = pixelsPerSecond.dy / size.height;
    final unitsPerSecond = Offset(unitsPerSecondX, unitsPerSecondY);
    final unitVelocity = unitsPerSecond.distance;
    const spring = SpringDescription(
      mass: 30,
      stiffness: 1,
      damping: 1,
    );
    final simulation = SpringSimulation(spring, 0, 1, -unitvelocity);
    _controller.animateWith(simulation);
  }
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    _controller.addListener(() {
      setState(() {
        _dragAlignment = _animation.value;
      });
    });
  }
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return GestureDetector(
      onPanDown: (details) {
        _controller.stop();
      },
      onPanUpdate: (details) {
        setState(() {
          _dragAlignment += alignment(
            details.delta.dx / (size.width / 2),
            details.delta.dy / (size.height / 2),
          );
        });
      },
      onPanEnd: (details) {
        _runAnimation(details.velocity.pixelsPerSecond, size);
      },
      child: align(
        alignment: _dragAlignment,
        child: card(
          child: widget.child,
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
staggered animations
<topic_end>
<topic_start>
what you'll learn
terminology:
  if the concept of tweens or tweening is new to you, see the
  animations in flutter tutorial.
staggered animations are a straightforward concept: visual changes
happen as a series of operations, rather than all at once.
the animation might be purely sequential, with one change occurring after
the next, or it might partially or completely overlap. it might also
have gaps, where no changes occur.
this guide shows how to build a staggered animation in flutter.
<topic_end>
<topic_start>
examples
this guide explains the basic_staggered_animation example.
  you can also refer to a more complex example,
  staggered_pic_selection.
the following video demonstrates the animation performed by
basic_staggered_animation:
in the video, you see the following animation of a single widget,
which begins as a bordered blue square with slightly rounded corners.
the square runs through changes in the following order:
after running forward, the animation runs in reverse.
new to flutter?
  this page assumes you know how to create a layout using flutter’s
  widgets.  for more information, see building layouts in flutter.
<topic_end>
<topic_start>
basic structure of a staggered animation
<topic_end>
<topic_start>
what's the point?
the following diagram shows the intervals used in the
basic_staggered_animation example.
you might notice the following characteristics:
to set up the animation:
when the controlling animation’s value changes,
the new animation’s value changes, triggering the UI to update.
the following code creates a tween for the width property.
it builds a CurvedAnimation,
specifying an eased curve. see curves for
other available pre-defined animation curves.
the begin and end values don’t have to be doubles.
the following code builds the tween for the borderRadius property
(which controls the roundness of the square’s corners),
using BorderRadius.circular().
<topic_end>
<topic_start>
complete staggered animation
like all interactive widgets, the complete animation consists
of a widget pair: a stateless and a stateful widget.
the stateless widget specifies the tweens,
defines the animation objects, and provides a build() function
responsible for building the animating portion of the widget tree.
the stateful widget creates the controller, plays the animation,
and builds the non-animating portion of the widget tree.
the animation begins when a tap is detected anywhere in the screen.
full code for basic_staggered_animation’s main.dart
<topic_end>
<topic_start>
stateless widget: StaggerAnimation
in the stateless widget, StaggerAnimation,
the build() function instantiates an
AnimatedBuilder—a general purpose widget for building
animations. the AnimatedBuilder
builds a widget and configures it using the tweens’ current values.
the example creates a function named _buildAnimation() (which performs
the actual UI updates), and assigns it to its builder property.
AnimatedBuilder listens to notifications from the animation controller,
marking the widget tree dirty as values change.
for each tick of the animation, the values are updated,
resulting in a call to _buildAnimation().
<topic_end>
<topic_start>
stateful widget: StaggerDemo
the stateful widget, StaggerDemo, creates the AnimationController
(the one who rules them all), specifying a 2000 ms duration. it plays
the animation, and builds the non-animating portion of the widget tree.
the animation begins when a tap is detected in the screen.
the animation runs forward, then backward.
<topic_end>
<topic_start>
create a staggered menu animation
a single app screen might contain multiple animations.
playing all of the animations at the same time can be
overwhelming. playing the animations one after the other
can take too long. a better option is to stagger the animations. 
each animation begins at a different time,
but the animations overlap to create a shorter duration.
in this recipe, you build a drawer menu with animated 
content that is staggered and has a button that pops
in at the bottom.
the following animation shows the app’s behavior:
<topic_end>
<topic_start>
create the menu without animations
the drawer menu displays a list of titles,
followed by a get started button at 
the bottom of the menu.
define a stateful widget called menu
that displays the list and button 
in static locations.
<code_start>
class menu extends StatefulWidget {
  const menu({super.key});
  @override
  State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
  static const _menuTitles = [
    'declarative style',
    'premade widgets',
    'stateful hot reload',
    'native performance',
    'great community',
  ];
  @override
  widget build(BuildContext context) {
    return container(
      color: colors.white,
      child: stack(
        fit: StackFit.expand,
        children: [
          _buildFlutterLogo(),
          _buildContent(),
        ],
      ),
    );
  }
  widget _buildFlutterLogo() {
    // TODO: we'll implement this later.
    return container();
  }
  widget _buildContent() {
    return column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 16),
        ..._buildlistitems(),
        const spacer(),
        _buildGetStartedButton(),
      ],
    );
  }
  List<Widget> _buildListItems() {
    final listItems = <widget>[];
    for (var i = 0; i < _menuTitles.length; ++i) {
      listItems.add(
        padding(
          padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 16),
          child: text(
            _menuTitles[i],
            textAlign: TextAlign.left,
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      );
    }
    return listItems;
  }
  widget _buildGetStartedButton() {
    return SizedBox(
      width: double.infinity,
      child: padding(
        padding: const EdgeInsets.all(24),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            shape: const StadiumBorder(),
            backgroundColor: colors.blue,
            padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 14),
          ),
          onPressed: () {},
          child: const text(
            'get started',
            style: TextStyle(
              color: colors.white,
              fontSize: 22,
            ),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
prepare for animations
control of the animation timing requires an
AnimationController.
add the SingleTickerProviderStateMixin
to the MenuState class. then, declare and
instantiate an AnimationController.
<code_start>
class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  late AnimationController _staggeredController;
  @override
  void initState() {
    super.initState();
    _staggeredController = AnimationController(
      vsync: this,
    );
  }
}
  @override
  void dispose() {
    _staggeredController.dispose();
    super.dispose();
  }
}
<code_end>
the length of the delay before every animation is
up to you. define the animation delays,
individual animation durations, and the total 
animation duration.
<code_start>
class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  static const _initialDelayTime = duration(milliseconds: 50);
  static const _itemSlideTime = duration(milliseconds: 250);
  static const _staggerTime = duration(milliseconds: 50);
  static const _buttonDelayTime = duration(milliseconds: 150);
  static const _buttonTime = duration(milliseconds: 500);
  final _animationDuration = _initialDelayTime +
      (_staggertime * _menuTitles.length) +
      _buttonDelayTime +
      _buttonTime;
}
<code_end>
in this case, all the animations are delayed by 50 ms.
after that, list items begin to appear.
each list item’s appearance is delayed by 50 ms after the 
previous list item begins to slide in.
each list item takes 250 ms to slide from right to left.
after the last list item begins to slide in,
the button at the bottom waits another 150 ms to pop in.
the button animation takes 500 ms.
with each delay and animation duration defined,
the total duration is calculated so that it can be
used to calculate the individual animation times.
the desired animation times are shown in the following diagram:
to animate a value during a subsection of a larger animation,
flutter provides the interval class.
an interval takes a start time percentage and an end 
time percentage. that interval can then be used to
animate a value between those start and end times,
instead of using the entire animation’s start and 
end times. for example, given an animation that takes 1 second, 
an interval from 0.2 to 0.5 would start at 200 ms
(20%) and end at 500 ms (50%).
declare and calculate each list item’s interval and the 
bottom button interval.
<code_start>
class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  final List<Interval> _itemSlideIntervals = [];
  late interval _buttonInterval;
  @override
  void initState() {
    super.initState();
    _createAnimationIntervals();
    _staggeredController = AnimationController(
      vsync: this,
      duration: _animationDuration,
    );
  }
  void _createAnimationIntervals() {
    for (var i = 0; i < _menuTitles.length; ++i) {
      final startTime = _initialDelayTime + (_staggertime * i);
      final endTime = startTime + _itemSlideTime;
      _itemSlideIntervals.add(
        interval(
          startTime.inMilliseconds / _animationDuration.inMilliseconds,
          endTime.inMilliseconds / _animationDuration.inMilliseconds,
        ),
      );
    }
    final buttonStartTime =
        duration(milliseconds: (_menutitles.length * 50)) + _buttonDelayTime;
    final buttonEndTime = buttonStartTime + _buttonTime;
    _buttonInterval = interval(
      buttonStartTime.inMilliseconds / _animationDuration.inMilliseconds,
      buttonEndTime.inMilliseconds / _animationDuration.inMilliseconds,
    );
  }
}
<code_end>
<topic_end>
<topic_start>
animate the list items and button
the staggered animation plays as soon as the menu becomes visible.
start the animation in initState().
<code_start>
@override
void initState() {
  super.initState();
  _createAnimationIntervals();
  _staggeredController = AnimationController(
    vsync: this,
    duration: _animationDuration,
  )..forward();
}
<code_end>
each list item slides from right to left and
fades in at the same time.
use the list item’s interval and an easeOut
curve to animate the opacity and translation
values for each list item.
<code_start>
List<Widget> _buildListItems() {
  final listItems = <widget>[];
  for (var i = 0; i < _menuTitles.length; ++i) {
    listItems.add(
      AnimatedBuilder(
        animation: _staggeredController,
        builder: (context, child) {
          final animationPercent = Curves.easeOut.transform(
            _itemSlideIntervals[i].transform(_staggeredController.value),
          );
          final opacity = animationPercent;
          final slideDistance = (1.0 - animationPercent) * 150;
          return opacity(
            opacity: opacity,
            child: transform.translate(
              offset: Offset(slideDistance, 0),
              child: child,
            ),
          );
        },
        child: padding(
          padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 16),
          child: text(
            _menuTitles[i],
            textAlign: TextAlign.left,
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ),
    );
  }
  return listItems;
}
<code_end>
use the same approach to animate the opacity and
scale of the bottom button. this time, use an
elasticOut curve to give the button a springy effect.
<code_start>
widget _buildGetStartedButton() {
  return SizedBox(
    width: double.infinity,
    child: padding(
      padding: const EdgeInsets.all(24),
      child: AnimatedBuilder(
        animation: _staggeredController,
        builder: (context, child) {
          final animationPercent = Curves.elasticOut.transform(
              _buttonInterval.transform(_staggeredController.value));
          final opacity = animationPercent.clamp(0.0, 1.0);
          final scale = (animationpercent * 0.5) + 0.5;
          return opacity(
            opacity: opacity,
            child: transform.scale(
              scale: scale,
              child: child,
            ),
          );
        },
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            shape: const StadiumBorder(),
            backgroundColor: colors.blue,
            padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 14),
          ),
          onPressed: () {},
          child: const text(
            'get started',
            style: TextStyle(
              color: colors.white,
              fontSize: 22,
            ),
          ),
        ),
      ),
    ),
  );
}
<code_end>
congratulations!
you have an animated menu where the appearance of each 
list item is staggered, followed by a bottom button that
pops into place.
<topic_end>
<topic_start>
interactive example
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: ExampleStaggeredAnimations(),
      debugShowCheckedModeBanner: false,
    ),
  );
}
class ExampleStaggeredAnimations extends StatefulWidget {
  const ExampleStaggeredAnimations({
    super.key,
  });
  @override
  State<ExampleStaggeredAnimations> createState() =>
      _ExampleStaggeredAnimationsState();
}
class _ExampleStaggeredAnimationsState extends State<ExampleStaggeredAnimations>
    with SingleTickerProviderStateMixin {
  late AnimationController _drawerSlideController;
  @override
  void initState() {
    super.initState();
    _drawerSlideController = AnimationController(
      vsync: this,
      duration: const duration(milliseconds: 150),
    );
  }
  @override
  void dispose() {
    _drawerSlideController.dispose();
    super.dispose();
  }
  bool _isDrawerOpen() {
    return _drawerSlideController.value == 1.0;
  }
  bool _isDrawerOpening() {
    return _drawerSlideController.status == AnimationStatus.forward;
  }
  bool _isDrawerClosed() {
    return _drawerSlideController.value == 0.0;
  }
  void _toggleDrawer() {
    if (_isdraweropen() || _isDrawerOpening()) {
      _drawerSlideController.reverse();
    } else {
      _drawerSlideController.forward();
    }
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      backgroundColor: colors.white,
      appBar: _buildAppBar(),
      body: stack(
        children: [
          _buildContent(),
          _buildDrawer(),
        ],
      ),
    );
  }
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: const text(
        'flutter menu',
        style: TextStyle(
          color: colors.black,
        ),
      ),
      backgroundColor: colors.transparent,
      elevation: 0.0,
      automaticallyImplyLeading: false,
      actions: [
        AnimatedBuilder(
          animation: _drawerSlideController,
          builder: (context, child) {
            return IconButton(
              onPressed: _toggleDrawer,
              icon: _isDrawerOpen() || _isDrawerOpening()
                  ? const icon(
                      icons.clear,
                      color: colors.black,
                    )
                  : const icon(
                      icons.menu,
                      color: colors.black,
                    ),
            );
          },
        ),
      ],
    );
  }
  widget _buildContent() {
    // put page content here.
    return const SizedBox();
  }
  widget _buildDrawer() {
    return AnimatedBuilder(
      animation: _drawerSlideController,
      builder: (context, child) {
        return FractionalTranslation(
          translation: offset(1.0 - _drawerSlideController.value, 0.0),
          child: _isDrawerClosed() ? const SizedBox() : const menu(),
        );
      },
    );
  }
}
class menu extends StatefulWidget {
  const menu({super.key});
  @override
  State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
  static const _menuTitles = [
    'declarative style',
    'premade widgets',
    'stateful hot reload',
    'native performance',
    'great community',
  ];
  static const _initialDelayTime = duration(milliseconds: 50);
  static const _itemSlideTime = duration(milliseconds: 250);
  static const _staggerTime = duration(milliseconds: 50);
  static const _buttonDelayTime = duration(milliseconds: 150);
  static const _buttonTime = duration(milliseconds: 500);
  final _animationDuration = _initialDelayTime +
      (_staggertime * _menuTitles.length) +
      _buttonDelayTime +
      _buttonTime;
  late AnimationController _staggeredController;
  final List<Interval> _itemSlideIntervals = [];
  late interval _buttonInterval;
  @override
  void initState() {
    super.initState();
    _createAnimationIntervals();
    _staggeredController = AnimationController(
      vsync: this,
      duration: _animationDuration,
    )..forward();
  }
  void _createAnimationIntervals() {
    for (var i = 0; i < _menuTitles.length; ++i) {
      final startTime = _initialDelayTime + (_staggertime * i);
      final endTime = startTime + _itemSlideTime;
      _itemSlideIntervals.add(
        interval(
          startTime.inMilliseconds / _animationDuration.inMilliseconds,
          endTime.inMilliseconds / _animationDuration.inMilliseconds,
        ),
      );
    }
    final buttonStartTime =
        duration(milliseconds: (_menutitles.length * 50)) + _buttonDelayTime;
    final buttonEndTime = buttonStartTime + _buttonTime;
    _buttonInterval = interval(
      buttonStartTime.inMilliseconds / _animationDuration.inMilliseconds,
      buttonEndTime.inMilliseconds / _animationDuration.inMilliseconds,
    );
  }
  @override
  void dispose() {
    _staggeredController.dispose();
    super.dispose();
  }
  @override
  widget build(BuildContext context) {
    return container(
      color: colors.white,
      child: stack(
        fit: StackFit.expand,
        children: [
          _buildFlutterLogo(),
          _buildContent(),
        ],
      ),
    );
  }
  widget _buildFlutterLogo() {
    return const positioned(
      right: -100,
      bottom: -30,
      child: opacity(
        opacity: 0.2,
        child: FlutterLogo(
          size: 400,
        ),
      ),
    );
  }
  widget _buildContent() {
    return column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 16),
        ..._buildlistitems(),
        const spacer(),
        _buildGetStartedButton(),
      ],
    );
  }
  List<Widget> _buildListItems() {
    final listItems = <widget>[];
    for (var i = 0; i < _menuTitles.length; ++i) {
      listItems.add(
        AnimatedBuilder(
          animation: _staggeredController,
          builder: (context, child) {
            final animationPercent = Curves.easeOut.transform(
              _itemSlideIntervals[i].transform(_staggeredController.value),
            );
            final opacity = animationPercent;
            final slideDistance = (1.0 - animationPercent) * 150;
            return opacity(
              opacity: opacity,
              child: transform.translate(
                offset: Offset(slideDistance, 0),
                child: child,
              ),
            );
          },
          child: padding(
            padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 16),
            child: text(
              _menuTitles[i],
              textAlign: TextAlign.left,
              style: const TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      );
    }
    return listItems;
  }
  widget _buildGetStartedButton() {
    return SizedBox(
      width: double.infinity,
      child: padding(
        padding: const EdgeInsets.all(24),
        child: AnimatedBuilder(
          animation: _staggeredController,
          builder: (context, child) {
            final animationPercent = Curves.elasticOut.transform(
                _buttonInterval.transform(_staggeredController.value));
            final opacity = animationPercent.clamp(0.0, 1.0);
            final scale = (animationpercent * 0.5) + 0.5;
            return opacity(
              opacity: opacity,
              child: transform.scale(
                scale: scale,
                child: child,
              ),
            );
          },
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              shape: const StadiumBorder(),
              backgroundColor: colors.blue,
              padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 14),
            ),
            onPressed: () {},
            child: const text(
              'get started',
              style: TextStyle(
                color: colors.white,
                fontSize: 22,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
animations API overview
the animation system in flutter is based on typed
animation objects. widgets can either
incorporate these animations in their build
functions directly by reading their current value and listening to their
state changes or they can use the animations as the basis of more elaborate
animations that they pass along to other widgets.
<topic_end>
<topic_start>
animation
the primary building block of the animation system is the
animation class. an animation represents a value
of a specific type that can change over the lifetime of
the animation. most widgets that perform an animation
receive an animation object as a parameter,
from which they read the current value of the animation
and to which they listen for changes to that value.
<topic_end>
<topic_start>
addListener
whenever the animation’s value changes,
the animation notifies all the listeners added with
addListener. typically, a state
object that listens to an animation calls
setState on itself in its listener callback
to notify the widget system that it needs to
rebuild with the new value of the animation.
this pattern is so common that there are two widgets
that help widgets rebuild when animations change value:
AnimatedWidget and AnimatedBuilder.
the first, AnimatedWidget, is most useful for
stateless animated widgets. to use AnimatedWidget,
simply subclass it and implement the build function.
the second, AnimatedBuilder, is useful for more complex widgets
that wish to include an animation as part of a larger build function.
to use AnimatedBuilder, simply construct the widget
and pass it a builder function.
<topic_end>
<topic_start>
addStatusListener
animations also provide an AnimationStatus,
which indicates how the animation will evolve over time.
whenever the animation’s status changes,
the animation notifies all the listeners added with
addStatusListener. typically, animations start
out in the dismissed status, which means they’re
at the beginning of their range. for example,
animations that progress from 0.0 to 1.0
will be dismissed when their value is 0.0.
an animation might then run forward (from 0.0 to 1.0)
or perhaps in reverse (from 1.0 to 0.0).
eventually, if the animation reaches the end of its range
(1.0), the animation reaches the completed status.
<topic_end>
<topic_start>
Animation­Controller
to create an animation, first create an AnimationController.
as well as being an animation itself, an AnimationController
lets you control the animation. for example,
you can tell the controller to play the animation
forward or stop the animation.
you can also fling animations,
which uses a physical simulation, such as a spring,
to drive the animation.
once you’ve created an animation controller,
you can start building other animations based on it.
for example, you can create a ReverseAnimation
that mirrors the original animation but runs in the
opposite direction (from 1.0 to 0.0).
similarly, you can create a CurvedAnimation
whose value is adjusted by a curve.
<topic_end>
<topic_start>
tweens
to animate beyond the 0.0 to 1.0 interval, you can use a
Tween<T>, which interpolates between its
begin and end values. many types have specific
tween subclasses that provide type-specific interpolation.
for example, ColorTween interpolates between colors and
RectTween interpolates between rects.
you can define your own interpolations by creating
your own subclass of tween and overriding its
lerp function.
by itself, a tween just defines how to interpolate
between two values. to get a concrete value for the
current frame of an animation, you also need an
animation to determine the current state.
there are two ways to combine a tween
with an animation to get a concrete value:
you can evaluate the tween at the current
value of an animation. this approach is most useful
for widgets that are already listening to the animation and hence
rebuilding whenever the animation changes value.
you can animate the tween based on the animation.
rather than returning a single value, the animate function
returns a new animation that incorporates the tween.
this approach is most useful when you want to give the
newly created animation to another widget,
which can then read the current value that incorporates
the tween as well as listen for changes to the value.
<topic_end>
<topic_start>
architecture
animations are actually built from a number of core building blocks.
<topic_end>
<topic_start>
scheduler
the SchedulerBinding is a singleton class
that exposes the flutter scheduling primitives.
for this discussion, the key primitive is the frame callbacks.
each time a frame needs to be shown on the screen,
flutter’s engine triggers a “begin frame” callback that
the scheduler multiplexes to all the listeners registered using
scheduleFrameCallback(). all these callbacks are
given the official time stamp of the frame, in
the form of a duration from some arbitrary epoch. since all the
callbacks have the same time, any animations triggered from these
callbacks will appear to be exactly synchronised even
if they take a few milliseconds to be executed.
<topic_end>
<topic_start>
tickers
the ticker class hooks into the scheduler’s
scheduleFrameCallback()
mechanism to invoke a callback every tick.
a ticker can be started and stopped. when started,
it returns a future that will resolve when it is stopped.
each tick, the ticker provides the callback with the
duration since the first tick after it was started.
because tickers always give their elapsed time relative to the first
tick after they were started; tickers are all synchronised. if you
start three tickers at different times between two ticks, they will all
nonetheless be synchronised with the same starting time, and will
subsequently tick in lockstep. like people at a bus-stop,
all the tickers wait for a regularly occurring event
(the tick) to begin moving (counting time).
<topic_end>
<topic_start>
simulations
the simulation abstract class maps a
relative time value (an elapsed time) to a
double value, and has a notion of completion.
in principle simulations are stateless but in practice
some simulations (for example,
BouncingScrollSimulation and
ClampingScrollSimulation)
change state irreversibly when queried.
there are various concrete implementations
of the simulation class for different effects.
<topic_end>
<topic_start>
animatables
the animatable abstract class maps a
double to a value of a particular type.
animatable classes are stateless and immutable.
<topic_end>
<topic_start>
tweens
the Tween<T> abstract class maps a double
value nominally in the range 0.0-1.0 to a typed value
(for example, a color, or another double).
it is an animatable.
it has a notion of an output type (t),
a begin value and an end value of that type,
and a way to interpolate (lerp) between the begin
and end values for a given input value (the double nominally in
the range 0.0-1.0).
tween classes are stateless and immutable.
<topic_end>
<topic_start>
composing animatables
passing an animatable<double> (the parent) to an animatable’s
chain() method creates a new animatable subclass that applies the
parent’s mapping then the child’s mapping.
<topic_end>
<topic_start>
curves
the curve abstract class maps doubles
nominally in the range 0.0-1.0 to doubles
nominally in the range 0.0-1.0.
curve classes are stateless and immutable.
<topic_end>
<topic_start>
animations
the animation abstract class provides a
value of a given type, a concept of animation
direction and animation status, and a listener interface to
register callbacks that get invoked when the value or status change.
some subclasses of animation have values that never change
(kalwayscompleteanimation, kAlwaysDismissedAnimation,
AlwaysStoppedAnimation); registering callbacks on
these has no effect as the callbacks are never called.
the animation<double> variant is special because it can be used to
represent a double nominally in the range 0.0-1.0, which is the input
expected by curve and tween classes, as well as some further
subclasses of animation.
some animation subclasses are stateless,
merely forwarding listeners to their parents.
some are very stateful.
<topic_end>
<topic_start>
composable animations
most animation subclasses take an explicit “parent”
animation<double>. they are driven by that parent.
the CurvedAnimation subclass takes an animation<double> class (the
parent) and a couple of curve classes (the forward and reverse
curves) as input, and uses the value of the parent as input to the
curves to determine its output. CurvedAnimation is immutable and
stateless.
the ReverseAnimation subclass takes an
animation<double> class as its parent and reverses
all the values of the animation. it assumes the parent
is using a value nominally in the range 0.0-1.0 and returns
a value in the range 1.0-0.0. the status and direction of the parent
animation are also reversed. ReverseAnimation is immutable and
stateless.
the ProxyAnimation subclass takes an animation<double> class as
its parent and merely forwards the current state of that parent.
however, the parent is mutable.
the TrainHoppingAnimation subclass takes two parents,
and switches between them when their values cross.
<topic_end>
<topic_start>
animation controllers
the AnimationController is a stateful
animation<double> that uses a ticker to give itself life.
it can be started and stopped. at each tick, it takes the time
elapsed since it was started and passes it to a simulation to obtain
a value. that is then the value it reports. if the simulation
reports that at that time it has ended, then the controller stops
itself.
the animation controller can be given a lower and upper bound to
animate between, and a duration.
in the simple case (using forward() or reverse()), the animation controller simply does a linear
interpolation from the lower bound to the upper bound (or vice versa,
for the reverse direction) over the given duration.
when using repeat(), the animation controller uses a linear
interpolation between the given bounds over the given duration, but
does not stop.
when using animateTo(), the animation controller does a linear
interpolation over the given duration from the current value to the
given target. if no duration is given to the method, the default
duration of the controller and the range described by the controller’s
lower bound and upper bound is used to determine the velocity of the
animation.
when using fling(), a force is used to create a specific
simulation which is then used to drive the controller.
when using animateWith(), the given simulation is used to drive the
controller.
these methods all return the future that the ticker provides and
which will resolve when the controller next stops or changes
simulation.
<topic_end>
<topic_start>
attaching animatables to animations
passing an animation<double> (the new parent) to an animatable’s
animate() method creates a new animation subclass that acts like
the animatable but is driven from the given parent.
<topic_end>
<topic_start>
accessibility
ensuring apps are accessible to a broad range of users is an essential
part of building a high-quality app. applications that are poorly
designed create barriers to people of all ages. the UN convention on
the rights of persons with disabilities states the moral and legal
imperative to ensure universal access to information systems; countries
around the world enforce accessibility as a requirement; and companies
recognize the business advantages of maximizing access to their services.
we strongly encourage you to include an accessibility checklist
as a key criteria before shipping your app. flutter is committed to
supporting developers in making their apps more accessible, and includes
first-class framework support for accessibility in addition to that
provided by the underlying operating system, including:
details of these features are discussed below.
<topic_end>
<topic_start>
inspecting accessibility support
in addition to testing for these specific topics,
we recommend using automated accessibility scanners:
<topic_end>
<topic_start>
large fonts
both android and iOS contain system settings to configure the desired font
sizes used by apps. flutter text widgets respect this OS setting when
determining font sizes.
font sizes are calculated automatically by flutter based on the OS setting.
however, as a developer you should make sure your layout has enough room to
render all its contents when the font sizes are increased.
for example, you can test all parts of your app on a small-screen
device configured to use the largest font setting.
<topic_end>
<topic_start>
example
the following two screenshots show the standard flutter app
template rendered with the default iOS font setting,
and with the largest font setting selected in iOS accessibility settings.
<topic_end>
<topic_start>
screen readers
for mobile, screen readers (talkback, VoiceOver)
enable visually impaired users to get spoken feedback about
the contents of the screen and interact with the UI by using
gestures on mobile and keyboard shortcuts on desktop.
turn on VoiceOver or TalkBack on your mobile device and
navigate around your app.
to turn on the screen reader on your device, complete the following steps:
to learn how to find and customize android’s
accessibility features, view the following video.
to learn how to find and customize iOS
accessibility features, view the following video.
for web, the following screen readers are currently supported:
mobile browsers:
desktop browsers:
screen readers users on web must toggle the
“enable accessibility” button to build the semantics tree.
users can skip this step if you programmatically auto-enable
accessibility for your app using this API:
windows comes with a screen reader called narrator
but some developers recommend using the more popular
NVDA screen reader. to learn about using NVDA to test
windows apps, check out
screen readers 101 for Front-End developers (windows).
on a mac, you can use the desktop version of VoiceOver,
which is included in macOS.
on linux, a popular screen reader is called orca.
it comes pre-installed with some distributions
and is available on package repositories such as apt.
to learn about using orca, check out
getting started with orca screen reader on gnome desktop.
check out the following video demo to see victor tsaran,
using VoiceOver with the now-archived flutter gallery web app.
flutter’s standard widgets generate an accessibility tree automatically.
however, if your app needs something different,
it can be customized using the semantics widget.
when there is text in your app that should be voiced
with a specific voice, inform the screen reader
which voice to use by calling TextSpan.locale.
note that MaterialApp.locale and localizations.override
don’t affect which voice the screen reader uses.
usually, the screen reader uses the system voice
except where you explicitly set it with TextSpan.locale.
<topic_end>
<topic_start>
sufficient contrast
sufficient color contrast makes text and images easier to read.
along with benefitting users with various visual impairments,
sufficient color contrast helps all users when viewing an interface
on devices in extreme lighting conditions,
such as when exposed to direct sunlight or on a display with low
brightness.
the W3C recommends:
<topic_end>
<topic_start>
building with accessibility in mind
ensuring your app can be used by everyone means building accessibility
into it from the start. for some apps, that’s easier said than done.
in the video below, two of our engineers take a mobile app from a dire
accessibility state to one that takes advantage of flutter’s built-in
widgets to offer a dramatically more accessible experience.
<topic_end>
<topic_start>
testing accessibility on mobile
test your app using flutter’s accessibility guideline API.
this API checks if your app’s UI meets flutter’s accessibility recommendations.
these cover recommendations for text contrast, target size, and target labels.
the following example shows how to use the guideline API on name generator.
you created this app as part of the
write your first flutter app codelab.
each button on the app’s main screen serves as a tappable target
with text represented in 18 point.
<code_start>
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(MyApp());
// checks that tappable nodes have a minimum size of 48 by 48 pixels
// for android.
await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
// checks that tappable nodes have a minimum size of 44 by 44 pixels
// for iOS.
await expectLater(tester, meetsGuideline(iOSTapTargetGuideline));
// checks that touch targets with a tap or long press action are labeled.
await expectLater(tester, meetsGuideline(labeledTapTargetGuideline));
// checks whether semantic nodes meet the minimum text contrast levels.
// the recommended text contrast is 3:1 for larger text
// (18 point and above regular).
await expectLater(tester, meetsGuideline(textContrastGuideline));
handle.dispose();
<code_end>
you can add guideline API tests
in test/widget_test.dart of your app directory, or as a separate test
file (such as test/a11y_test.dart in the case of the name generator).
<topic_end>
<topic_start>
testing accessibility on web
you can debug accessibility by visualizing the semantic nodes created for your web app
using the following command line flag in profile and release modes:
with the flag activated, the semantic nodes appear on top of the widgets;
you can verify that the semantic elements are placed where they should be.
if the semantic nodes are incorrectly placed, please file a bug report.
<topic_end>
<topic_start>
accessibility release checklist
here is a non-exhaustive list of things to consider as you prepare your
app for release.
<topic_end>
<topic_start>
learn more
to learn more about flutter and accessibility, check out
the following articles written by community members:
<topic_end>
<topic_start>
internationalizing flutter apps
<topic_end>
<topic_start>
what you'll learn
if your app might be deployed to users who speak another
language then you’ll need to internationalize it.
that means you need to write the app in a way that makes
it possible to localize values like text and layouts
for each language or locale that the app supports.
flutter provides widgets and classes that help with
internationalization and the flutter libraries
themselves are internationalized.
this page covers concepts and workflows necessary to
localize a flutter application using the
MaterialApp and CupertinoApp classes,
as most apps are written that way.
however, applications written using the lower level
WidgetsApp class can also be internationalized
using the same classes and logic.
<topic_end>
<topic_start>
introduction to localizations in flutter
this section provides a tutorial on how to create and
internationalize a new flutter application,
along with any additional setup
that a target platform might require.
you can find the source code for this example in
gen_l10n_example.
<topic_end>
<topic_start>
setting up an internation­alized app: the flutter_localizations package
by default, flutter only provides US english localizations.
to add support for other languages,
an application must specify additional
MaterialApp (or CupertinoApp) properties,
and include a package called flutter_localizations.
as of december 2023, this package supports 115 languages
and language variants.
to begin, start by creating a new flutter application
in a directory of your choice with the flutter create command.
to use flutter_localizations,
add the package as a dependency to your pubspec.yaml file, 
as well as the intl package:
this creates a pubspec.yml file with the following entries:
<code_start>
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: any
<code_end>
then import the flutter_localizations library and specify
localizationsDelegates and supportedLocales for
your MaterialApp or CupertinoApp:
<code_start>
import 'package:flutter_localizations/flutter_localizations.dart';
<code_end>
<code_start>
return const MaterialApp(
  title: 'localizations sample app',
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: [
    locale('en'), // english
    locale('es'), // spanish
  ],
  home: MyHomePage(),
);
<code_end>
after introducing the flutter_localizations package
and adding the previous code,
the material and cupertino
packages should now be correctly localized in
one of the 115 supported locales.
widgets should be adapted to the localized messages,
along with correct left-to-right or right-to-left layout.
try switching the target platform’s locale to
spanish (es) and the messages should be localized.
apps based on WidgetsApp are similar except that the
GlobalMaterialLocalizations.delegate isn’t needed.
the full Locale.fromSubtags constructor is preferred
as it supports scriptCode, though the locale default
constructor is still fully valid.
the elements of the localizationsDelegates list are
factories that produce collections of localized values.
GlobalMaterialLocalizations.delegate provides localized
strings and other values for the material components
library. GlobalWidgetsLocalizations.delegate
defines the default text direction,
either left-to-right or right-to-left, for the widgets library.
more information about these app properties, the types they
depend on, and how internationalized flutter apps are typically
structured, is covered in this page.
<topic_end>
<topic_start>
overriding the locale
localizations.override is a factory constructor
for the localizations widget that allows for
(the typically rare) situation where a section of your application
needs to be localized to a different locale than the locale
configured for your device.
to observe this behavior, add a call to localizations.override
and a simple CalendarDatePicker:
<code_start>
widget build(BuildContext context) {
  return scaffold(
    appBar: AppBar(
      title: text(widget.title),
    ),
    body: center(
      child: column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <widget>[
          // add the following code
          localizations.override(
            context: context,
            locale: const locale('es'),
            // using a builder to get the correct BuildContext.
            // alternatively, you can create a new widget and localizations.override
            // will pass the updated BuildContext to the new widget.
            child: builder(
              builder: (context) {
                // a toy example for an internationalized material widget.
                return CalendarDatePicker(
                  initialDate: DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime(2100),
                  onDateChanged: (value) {},
                );
              },
            ),
          ),
        ],
      ),
    ),
  );
}
<code_end>
hot reload the app and the CalendarDatePicker
widget should re-render in spanish.
<topic_end>
<topic_start>
adding your own localized messages
after adding the flutter_localizations package,
you can configure localization.
to add localized text to your application,
complete the following instructions:
add the intl package as a dependency, pulling
in the version pinned by flutter_localizations:
open the pubspec.yaml file and enable the generate flag. 
this flag is found in the flutter section in the pubspec file.
<code_start>
# the following section is specific to flutter.
flutter:
  generate: true # add this line
<code_end>
add a new yaml file to the root directory of the flutter project.
name this file l10n.yaml and include following content:
<code_start>
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
<code_end>
this file configures the localization tool.
in this example, you’ve done the following:
in ${flutter_project}/lib/l10n,
add the app_en.arb template file. for example:
<code_start>
{
  "helloworld": "hello world!",
  "@helloworld": {
    "description": "the conventional newborn programmer greeting"
  }
}
<code_end>
add another bundle file called app_es.arb in the same directory.
in this file, add the spanish translation of the same message.
<code_start>
{
    "helloworld": "¡hola mundo!"
}
<code_end>
now, run flutter pub get or flutter run and codegen takes place automatically.
you should find generated files in
${flutter_project}/.dart_tool/flutter_gen/gen_l10n.
alternatively, you can also run flutter gen-l10n to
generate the same files without running the app.
add the import statement on app_localizations.dart and
AppLocalizations.delegate
in your call to the constructor for MaterialApp:
<code_start>
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
<code_end>
<code_start>
return const MaterialApp(
  title: 'localizations sample app',
  localizationsDelegates: [
    AppLocalizations.delegate, // add this line
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: [
    locale('en'), // english
    locale('es'), // spanish
  ],
  home: MyHomePage(),
);
<code_end>
the AppLocalizations class also provides auto-generated
localizationsDelegates and supportedLocales lists.
you can use these instead of providing them manually.
<code_start>
const MaterialApp(
  title: 'localizations sample app',
  localizationsDelegates: AppLocalizations.localizationsDelegates,
  supportedLocales: AppLocalizations.supportedLocales,
);
<code_end>
once the material app has started,
you can use AppLocalizations anywhere in your app:
<code_start>
appBar: AppBar(
  // the [appbar] title text should update its message
  // according to the system locale of the target platform.
  // switching between english and spanish locales should
  // cause this text to update.
  title: Text(AppLocalizations.of(context)!.helloWorld),
),
<code_end>
info note
  the material app has to actually be started to initialize
  AppLocalizations. if the app hasn’t yet started,
  AppLocalizations.of(context)!.helloWorld causes a
  null exception.
this code generates a text widget that displays “hello world!”
   if the target device’s locale is set to english,
   and “¡hola mundo!” if the target device’s locale is set
   to spanish. in the arb files,
   the key of each entry is used as the method name of the getter,
   while the value of that entry contains the localized message.
the gen_l10n_example uses this tool.
to localize your device app description,
pass the localized string to
MaterialApp.onGenerateTitle:
<code_start>
return MaterialApp(
  onGenerateTitle: (context) => DemoLocalizations.of(context).title,
<code_end>
<topic_end>
<topic_start>
placeholders, plurals, and selects
lightbulb tip
  when using VS code, add the arb-editor extension.
  this extension adds syntax highlighting, snippets, 
  diagnostics, and quick fixes to help edit .arb template files.
you can also include application values in a message with
special syntax that uses a placeholder to generate a method
instead of a getter.
a placeholder, which must be a valid dart identifier name,
becomes a positional parameter in the generated method in the
AppLocalizations code. define a placeholder name by wrapping
it in curly braces as follows:
define each placeholder in the placeholders object
in the app’s .arb file. for example,
to define a hello message with a userName parameter,
add the following to lib/l10n/app_en.arb:
<code_start>
"hello": "hello {username}",
"@hello": {
  "description": "a message with a single parameter",
  "placeholders": {
    "username": {
      "type": "string",
      "example": "bob"
    }
  }
}
<code_end>
this code snippet adds a hello method call to
the AppLocalizations.of(context) object,
and the method accepts a parameter of type string;
the hello method returns a string.
regenerate the AppLocalizations file.
replace the code passed into builder with the following:
<code_start>
// examples of internationalized strings.
return column(
  children: <widget>[
    // returns 'hello john'
    Text(AppLocalizations.of(context)!.hello('John')),
  ],
);
<code_end>
you can also use numerical placeholders to specify multiple values.
different languages have different ways to pluralize words.
the syntax also supports specifying how a word should be pluralized.
a pluralized message must include a num parameter indicating
how to pluralize the word in different situations.
english, for example, pluralizes “person” to “people”,
but that doesn’t go far enough.
the message0 plural might be “no people” or “zero people”.
the messageFew plural might be
“several people”, “some people”, or “a few people”. 
the messageMany plural might
be  “most people” or “many people”, or “a crowd”. 
only the more general messageOther field is required.
the following example shows what options are available:
the previous expression is replaced by the message variation
(message0, message1, …) corresponding to the value
of the countPlaceholder.
only the messageOther field is required.
the following example defines a message that pluralizes
the word, “wombat”:
<code_start>
"nwombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
"@nwombats": {
  "description": "a plural message",
  "placeholders": {
    "count": {
      "type": "num",
      "format": "compact"
    }
  }
}
<code_end>
use a plural method by passing in the count parameter:
<code_start>
// examples of internationalized strings.
return column(
  children: <widget>[
    ...
    // returns 'no wombats'
    Text(AppLocalizations.of(context)!.nWombats(0)),
    // returns '1 wombat'
    Text(AppLocalizations.of(context)!.nWombats(1)),
    // returns '5 wombats'
    Text(AppLocalizations.of(context)!.nWombats(5)),
  ],
);
<code_end>
similar to plurals,
you can also choose a value based on a string placeholder.
this is most often used to support gendered languages.
the syntax is as follows:
the next example defines a message that
selects a pronoun based on gender:
<code_start>
"pronoun": "{gender, select, male{he} female{she} other{they}}",
"@pronoun": {
  "description": "a gendered message",
  "placeholders": {
    "gender": {
      "type": "string"
    }
  }
}
<code_end>
use this feature by
passing the gender string as a parameter:
<code_start>
// examples of internationalized strings.
return column(
  children: <widget>[
    ...
    // returns 'he'
    Text(AppLocalizations.of(context)!.pronoun('male')),
    // returns 'she'
    Text(AppLocalizations.of(context)!.pronoun('female')),
    // returns 'they'
    Text(AppLocalizations.of(context)!.pronoun('other')),
  ],
);
<code_end>
keep in mind that when using select statements,
comparison between the parameter and the actual
value is case-sensitive.
that is, AppLocalizations.of(context)!.pronoun("Male")
defaults to the “other” case, and returns “they”.
<topic_end>
<topic_start>
escaping syntax
sometimes, you have to use tokens,
such as { and }, as normal characters.
to ignore such tokens from being parsed,
enable the use-escaping flag by adding the
following to l10n.yaml:
the parser ignores any string of characters
wrapped with a pair of single quotes.
to use a normal single quote character,
use a pair of consecutive single quotes.
for example, the follow text is converted
to a dart string:
the resulting string is as follows:
<topic_end>
<topic_start>
messages with numbers and currencies
numbers, including those that represent currency values,
are displayed very differently in different locales. 
the localizations generation tool in
flutter_localizations uses the
NumberFormat
class in the intl package to format
numbers based on the locale and the desired format.
the int, double, and number types can use any of the
following NumberFormat constructors:
the starred NumberFormat constructors in the table
offer optional, named parameters.
those parameters can be specified as the value
of the placeholder’s optionalParameters object.
for example, to specify the optional decimalDigits
parameter for compactCurrency,
make the following changes to the lib/l10n/app_en.arg file:
<code_start>
"numberofdatapoints": "number of data points: {value}",
"@numberofdatapoints": {
  "description": "a message with a formatted int parameter",
  "placeholders": {
    "value": {
      "type": "int",
      "format": "compactcurrency",
      "optionalparameters": {
        "decimaldigits": 2
      }
    }
  }
}
<code_end>
<topic_end>
<topic_start>
messages with dates
dates strings are formatted in many different ways
depending both the locale and the app’s needs.
placeholder values with type DateTime are formatted with
DateFormat in the intl package.
there are 41 format variations,
identified by the names of their DateFormat factory constructors.
in the following example, the DateTime value
that appears in the helloWorldOn message is
formatted with DateFormat.yMd:
in an app where the locale is US english,
the following expression would produce  “7/9/1959”.
in a russian locale, it would produce “9.07.1959”.
<topic_end>
<topic_start>
localizing for iOS: updating the iOS app bundle
typically, iOS applications define key application metadata,
including supported locales, in an info.plist file
that is built into the application bundle.
to configure the locales supported by your app,
use the following instructions:
open your project’s ios/Runner.xcworkspace xcode file.
in the project navigator, open the info.plist file
under the runner project’s runner folder.
select the information property list item.
then select add item from the editor menu,
and select localizations from the pop-up menu.
select and expand the newly-created localizations item.
for each locale your application supports,
add a new item and select the locale you wish to add
from the pop-up menu in the value field.
this list should be consistent with the languages listed
in the supportedLocales parameter.
once all supported locales have been added, save the file.
<topic_end>
<topic_start>
advanced topics for further customization
this section covers additional ways to customize a
localized flutter application.
<topic_end>
<topic_start>
advanced locale definition
some languages with multiple variants require more than just a
language code to properly differentiate.
for example, fully differentiating all variants of
chinese requires specifying the language code, script code,
and country code. this is due to the existence
of simplified and traditional script, as well as regional
differences in the way characters are written within the same script type.
in order to fully express every variant of chinese for the
country codes CN, TW, and HK, the list of supported
locales should include:
<code_start>
supportedLocales: [
  Locale.fromSubtags(languageCode: 'zh'), // generic chinese 'zh'
  Locale.fromSubtags(
      languageCode: 'zh',
      scriptCode: 'hans'), // generic simplified chinese 'zh_hans'
  Locale.fromSubtags(
      languageCode: 'zh',
      scriptCode: 'hant'), // generic traditional chinese 'zh_hant'
  Locale.fromSubtags(
      languageCode: 'zh',
      scriptCode: 'hans',
      countryCode: 'cn'), // 'zh_hans_cn'
  Locale.fromSubtags(
      languageCode: 'zh',
      scriptCode: 'hant',
      countryCode: 'tw'), // 'zh_hant_tw'
  Locale.fromSubtags(
      languageCode: 'zh',
      scriptCode: 'hant',
      countryCode: 'hk'), // 'zh_hant_hk'
],
<code_end>
this explicit full definition ensures that your app can
distinguish between and provide the fully nuanced localized
content to all combinations of these country codes.
if a user’s preferred locale isn’t specified,
flutter selects the closest match,
which likely contains differences to what the user expects.
flutter only resolves to locales defined in supportedLocales
and provides scriptCode-differentiated localized
content for commonly used languages.
see localizations for information on how the supported
locales and the preferred locales are resolved.
although chinese is a primary example,
other languages like french (fr_fr, fr_CA)
should also be fully differentiated for more nuanced localization.
<topic_end>
<topic_start>
tracking the locale: the locale class and the localizations widget
the locale class identifies the user’s language.
mobile devices support setting the locale for all applications,
usually using a system settings menu.
internationalized apps respond by displaying values that are
locale-specific. for example, if the user switches the device’s locale
from english to french, then a text widget that originally
displayed “hello world” would be rebuilt with “bonjour le monde”.
the localizations widget defines the locale
for its child and the localized resources that the child depends on.
the WidgetsApp widget creates a localizations widget
and rebuilds it if the system’s locale changes.
you can always look up an app’s current locale with
Localizations.localeOf():
<code_start>
locale myLocale = Localizations.localeOf(context);
<code_end>
<topic_end>
<topic_start>
specifying the app’s supported­Locales parameter
although the flutter_localizations library currently supports
115 languages and language variants, only english language translations
are available by default. it’s up to the developer to decide exactly
which languages to support.
the MaterialApp supportedLocales
parameter limits locale changes. when the user changes the locale
setting on their device, the app’s localizations widget only
follows suit if the new locale is a member of this list.
if an exact match for the device locale isn’t found,
then the first supported locale with a matching languageCode
is used. if that fails, then the first element of the
supportedLocales list is used.
an app that wants to use a different “locale resolution”
method can provide a localeResolutionCallback.
for example, to have your app unconditionally accept
whatever locale the user selects:
<code_start>
MaterialApp(
  localeResolutionCallback: (
    locale,
    supportedLocales,
  ) {
    return locale;
  },
);
<code_end>
<topic_end>
<topic_start>
configuring the l10n.yaml file
the l10n.yaml file allows you to configure the gen-l10n tool
to specify the following:
for a full list of options, either run flutter gen-l10n --help
at the command line or refer to the following table:
<topic_end>
<topic_start>
how internationalization in flutter works
this section covers the technical details of how localizations work
in flutter. if you’re planning on supporting your own set of localized
messages, the following content would be helpful.
otherwise, you can skip this section.
<topic_end>
<topic_start>
loading and retrieving localized values
the localizations widget is used to load and
look up objects that contain collections of localized values.
apps refer to these objects with localizations.of(context,type).
if the device’s locale changes,
the localizations widget automatically loads values for
the new locale and then rebuilds widgets that used it.
this happens because localizations works like an
InheritedWidget.
when a build function refers to an inherited widget,
an implicit dependency on the inherited widget is created.
when an inherited widget changes
(when the localizations widget’s locale changes),
its dependent contexts are rebuilt.
localized values are loaded by the localizations widget’s
list of LocalizationsDelegates.
each delegate must define an asynchronous load()
method that produces an object that encapsulates a
collection of localized values.
typically these objects define one method per localized value.
in a large app, different modules or packages might be bundled with
their own localizations. that’s why the localizations widget
manages a table of objects, one per LocalizationsDelegate.
to retrieve the object produced by one of the LocalizationsDelegate’s
load methods, specify a BuildContext and the object’s type.
for example,
the localized strings for the material components widgets
are defined by the MaterialLocalizations class.
instances of this class are created by a LocalizationDelegate
provided by the MaterialApp class.
they can be retrieved with localizations.of():
this particular localizations.of() expression is used frequently,
so the MaterialLocalizations class provides a convenient shorthand:
<topic_end>
<topic_start>
defining a class for the app’s localized resources
putting together an internationalized flutter app usually
starts with the class that encapsulates the app’s localized values.
the example that follows is typical of such classes.
complete source code for the intl_example for this app.
this example is based on the APIs and tools provided by the
intl package. the an alternative class for the app’s
localized resources section
describes an example that doesn’t depend on the intl package.
the DemoLocalizations class
(defined in the following code snippet)
contains the app’s strings (just one for the example)
translated into the locales that the app supports.
it uses the initializeMessages() function
generated by dart’s intl package,
intl.message(), to look them up.
<code_start>
class DemoLocalizations {
  DemoLocalizations(this.localeName);
  static Future<DemoLocalizations> load(Locale locale) {
    final string name =
        locale.countryCode == null || locale.countryCode!.isEmpty
            ? locale.languageCode
            : locale.toString();
    final string localeName = Intl.canonicalizedLocale(name);
    return initializeMessages(localeName).then((_) {
      return DemoLocalizations(localeName);
    });
  }
  static DemoLocalizations of(BuildContext context) {
    return Localizations.of<DemoLocalizations>(context, DemoLocalizations)!;
  }
  final string localeName;
  string get title {
    return intl.message(
      'hello world',
      name: 'title',
      desc: 'title for the demo application',
      locale: localeName,
    );
  }
}
<code_end>
a class based on the intl package imports a generated
message catalog that provides the initializeMessages()
function and the per-locale backing store for intl.message().
the message catalog is produced by an intl tool
that analyzes the source code for classes that contain
intl.message() calls.
in this case that would just be the DemoLocalizations class.
<topic_end>
<topic_start>
adding support for a new language
an app that needs to support a language that’s not included in
GlobalMaterialLocalizations has to do some extra work:
it must provide about 70 translations (“localizations”)
for words or phrases and the date patterns and symbols for the
locale.
see the following for an example of how to add
support for the norwegian nynorsk language.
a new GlobalMaterialLocalizations subclass defines the
localizations that the material library depends on.
a new LocalizationsDelegate subclass, which serves
as factory for the GlobalMaterialLocalizations subclass,
must also be defined.
here’s the source code for the complete add_language example,
minus the actual nynorsk translations.
the locale-specific GlobalMaterialLocalizations subclass
is called NnMaterialLocalizations,
and the LocalizationsDelegate subclass is
_NnMaterialLocalizationsDelegate.
the value of NnMaterialLocalizations.delegate
is an instance of the delegate, and is all
that’s needed by an app that uses these localizations.
the delegate class includes basic date and number format
localizations. all of the other localizations are defined by string
valued property getters in NnMaterialLocalizations, like this:
<code_start>
@override
string get moreButtonTooltip => r'More';
@override
string get aboutListTileTitleRaw => r'About $applicationname';
@override
string get alertDialogLabel => r'Alert';
<code_end>
these are the english translations, of course.
to complete the job you need to change the return
value of each getter to an appropriate nynorsk string.
the getters return “raw” dart strings that have an r prefix,
such as r'About $applicationname',
because sometimes the strings contain variables with a $ prefix.
the variables are expanded by parameterized localization methods:
<code_start>
@override
string get pageRowsInfoTitleRaw => r'$firstRow–$lastRow of $rowcount';
@override
string get pageRowsInfoTitleApproximateRaw =>
    r'$firstRow–$lastRow of about $rowcount';
<code_end>
the date patterns and symbols of the locale also need to
be specified, which are defined in the source code as follows:
<code_start>
const nnLocaleDatePatterns = {
  'd': 'd.',
  'e': 'ccc',
  'eeee': 'cccc',
  'lll': 'lll',
  // ...
}
<code_end>
<code_start>
const nnDateSymbols = {
  'name': 'nn',
  'eras': <dynamic>[
    'f.kr.',
    'e.kr.',
  ],
  // ...
}
<code_end>
these values need to be modified for the locale to use the correct
date formatting. unfortunately, since the intl library doesn’t
share the same flexibility for number formatting,
the formatting for an existing locale must be used
as a substitute in _NnMaterialLocalizationsDelegate:
<code_start>
class _NnMaterialLocalizationsDelegate
    extends LocalizationsDelegate<MaterialLocalizations> {
  const _NnMaterialLocalizationsDelegate();
  @override
  bool isSupported(Locale locale) => locale.languageCode == 'nn';
  @override
  Future<MaterialLocalizations> load(Locale locale) async {
    final string localeName = intl.Intl.canonicalizedLocale(locale.toString());
    // the locale (in this case `nn`) needs to be initialized into the custom
    // date symbols and patterns setup that flutter uses.
    date_symbol_data_custom.initializeDateFormattingCustom(
      locale: localeName,
      patterns: nnLocaleDatePatterns,
      symbols: intl.DateSymbols.deserializeFromMap(nnDateSymbols),
    );
    return SynchronousFuture<MaterialLocalizations>(
      NnMaterialLocalizations(
        localeName: localeName,
        // the `intl` library's NumberFormat class is generated from CLDR data
        // (see https://github.com/dart-lang/i18n/blob/main/pkgs/intl/lib/number_symbols_data.dart).
        // unfortunately, there is no way to use a locale that isn't defined in
        // this map and the only way to work around this is to use a listed
        // locale's NumberFormat symbols. so, here we use the number formats
        // for 'en_us' instead.
        decimalFormat: intl.NumberFormat('#,##0.###', 'en_us'),
        twoDigitZeroPaddedFormat: intl.NumberFormat('00', 'en_us'),
        // DateFormat here will use the symbols and patterns provided in the
        // `date_symbol_data_custom.initializedateformattingcustom` call above.
        // however, an alternative is to simply use a supported locale's
        // DateFormat symbols, similar to NumberFormat above.
        fullYearFormat: intl.DateFormat('y', localeName),
        compactDateFormat: intl.DateFormat('yMd', localeName),
        shortDateFormat: intl.DateFormat('yMMMd', localeName),
        mediumDateFormat: intl.DateFormat('EEE, MMM d', localeName),
        longDateFormat: intl.DateFormat('EEEE, MMMM d, y', localeName),
        yearMonthFormat: intl.DateFormat('MMMM y', localeName),
        shortMonthDayFormat: intl.DateFormat('MMM d'),
      ),
    );
  }
  @override
  bool shouldReload(_NnMaterialLocalizationsDelegate old) => false;
}
<code_end>
for more information about localization strings,
check out the flutter_localizations README.
once you’ve implemented your language-specific subclasses of
GlobalMaterialLocalizations and LocalizationsDelegate,
you  need to add the language and a delegate instance to your app.
the following code sets the app’s language to nynorsk and
adds the NnMaterialLocalizations delegate instance to the app’s
localizationsDelegates list:
<code_start>
const MaterialApp(
  localizationsDelegates: [
    GlobalWidgetsLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    NnMaterialLocalizations.delegate, // add the newly created delegate
  ],
  supportedLocales: [
    locale('en', 'us'),
    locale('nn'),
  ],
  home: home(),
),
<code_end>
<topic_end>
<topic_start>
alternative internationalization workflows
this section describes different approaches to internationalize
your flutter application.
<topic_end>
<topic_start>
an alternative class for the app’s localized resources
the previous example was defined in terms of the dart intl
package. you can choose your own approach for managing
localized values for the sake of simplicity or perhaps to integrate
with a different i18n framework.
complete source code for the minimal app.
in the following example, the DemoLocalizations class 
includes all of its translations directly in per language maps:
<code_start>
class DemoLocalizations {
  DemoLocalizations(this.locale);
  final locale locale;
  static DemoLocalizations of(BuildContext context) {
    return Localizations.of<DemoLocalizations>(context, DemoLocalizations)!;
  }
  static const _localizedValues = <string, Map<String, string>>{
    'en': {
      'title': 'hello world',
    },
    'es': {
      'title': 'hola mundo',
    },
  };
  static List<String> languages() => _localizedValues.keys.toList();
  string get title {
    return _localizedValues[locale.languageCode]!['title']!;
  }
}
<code_end>
in the minimal app the DemoLocalizationsDelegate is slightly
different. its load method returns a SynchronousFuture
because no asynchronous loading needs to take place.
<code_start>
class DemoLocalizationsDelegate
    extends LocalizationsDelegate<DemoLocalizations> {
  const DemoLocalizationsDelegate();
  @override
  bool isSupported(Locale locale) =>
      DemoLocalizations.languages().contains(locale.languageCode);
  @override
  Future<DemoLocalizations> load(Locale locale) {
    // returning a SynchronousFuture here because an async "load" operation
    // isn't needed to produce an instance of DemoLocalizations.
    return SynchronousFuture<DemoLocalizations>(DemoLocalizations(locale));
  }
  @override
  bool shouldReload(DemoLocalizationsDelegate old) => false;
}
<code_end>
<topic_end>
<topic_start>
using the dart intl tools
before building an API using the dart intl package,
review the intl package’s documentation.
the following list summarizes the process for
localizing an app that depends on the intl package:
the demo app depends on a generated source file called
l10n/messages_all.dart, which defines all of the
localizable strings used by the app.
rebuilding l10n/messages_all.dart requires two steps.
with the app’s root directory as the current directory,
generate l10n/intl_messages.arb from lib/main.dart:
the intl_messages.arb file is a JSON format map with one entry for
each intl.message() function defined in main.dart.
this file serves as a template for the english and spanish translations,
intl_en.arb and intl_es.arb.
these translations are created by you, the developer.
with the app’s root directory as the current directory,
generate intl_messages_<locale>.dart for each
intl_<locale>.arb file and intl_messages_all.dart,
which imports all of the messages files:
windows doesn’t support file name wildcarding.
instead, list the .arb files that were generated by the
intl_translation:extract_to_arb command.
the DemoLocalizations class uses the generated
initializeMessages() function
(defined in intl_messages_all.dart)
to load the localized messages and intl.message()
to look them up.
<topic_end>
<topic_start>
more information
if you learn best by reading code,
check out the following examples.
if dart’s intl package is new to you,
check out using the dart intl tools.
<topic_end>
<topic_start>
state management
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
state management
info note
  if you have written a mobile app using flutter
  and wonder why your app’s state is lost
  on a restart, check out restore state on android
  or restore state on iOS.
if you are already familiar with state management in reactive apps,
you can skip this section, though you might want to review the
list of different approaches.
as you explore flutter,
there comes a time when you need to share application
state between screens, across your app.
there are many approaches you can take,
and many questions to think about.
in the following pages,
you will learn the basics of dealing with state in flutter apps.
<topic_end>
<topic_start>
start thinking declaratively
if you’re coming to flutter from an imperative framework
(such as android SDK or iOS UIKit), you need to start
thinking about app development from a new perspective.
many assumptions that you might have don’t apply to flutter. for example, in
flutter it’s okay to rebuild parts of your UI from scratch instead of modifying
it. flutter is fast enough to do that, even on every frame if needed.
flutter is declarative. this means that flutter builds its user interface to
reflect the current state of your app:
when the state of your app changes
(for example, the user flips a switch in the settings screen),
you change the state, and that triggers a redraw of the user interface.
there is no imperative changing of the UI itself
(like widget.setText)—you change the state,
and the UI rebuilds from scratch.
read more about the declarative approach to UI programming
in the get started guide.
the declarative style of UI programming has many benefits.
remarkably, there is only one code path for any state of the UI.
you describe what the UI should look
like for any given state, once—and that is it.
at first,
this style of programming might not seem as intuitive as the
imperative style. this is why this section is here. read on.
<topic_end>
<topic_start>
differentiate between ephemeral state and app state
this doc introduces app state, ephemeral state,
and how you might manage each in a flutter app.
in the broadest possible sense, the state of an app is everything that
exists in memory when the app is running. this includes the app’s assets,
all the variables that the flutter framework keeps about the UI,
animation state, textures, fonts, and so on. while this broadest
possible definition of state is valid, it’s not very useful for
architecting an app.
first, you don’t even manage some state (like textures).
the framework handles those for you. so a more useful definition of
state is “whatever data you need in order to rebuild your UI at any
moment in time”. second, the state that you do manage yourself can
be separated into two conceptual types: ephemeral state and app state.
<topic_end>
<topic_start>
ephemeral state
ephemeral state (sometimes called UI state or local state)
is the state you can neatly contain in a single widget.
this is, intentionally, a vague definition, so here are a few examples.
other parts of the widget tree seldom need to access this kind of state.
there is no need to serialize it, and it doesn’t change in complex ways.
in other words, there is no need to use state management techniques
(scopedmodel, redux, etc.) on this kind of state.
all you need is a StatefulWidget.
below, you see how the currently selected item in a bottom navigation bar is
held in the _index field of the _MyHomepageState class.
in this example, _index is ephemeral state.
<code_start>
class MyHomepage extends StatefulWidget {
  const MyHomepage({super.key});
  @override
  State<MyHomepage> createState() => _MyHomepageState();
}
class _MyHomepageState extends State<MyHomepage> {
  int _index = 0;
  @override
  widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: _index,
      onTap: (newindex) {
        setState(() {
          _index = newIndex;
        });
      },
      // ... items ...
    );
  }
}
<code_end>
here, using setState() and a field inside the StatefulWidget’s state
class is completely natural. no other part of your app needs to access
_index. the variable only changes inside the MyHomepage widget.
and, if the user closes and restarts the app,
you don’t mind that _index resets to zero.
<topic_end>
<topic_start>
app state
state that is not ephemeral,
that you want to share across many parts of your app,
and that you want to keep between user sessions,
is what we call application state
(sometimes also called shared state).
examples of application state:
for managing app state, you’ll want to research your options.
your choice depends on the complexity and nature of your app,
your team’s previous experience, and many other aspects. read on.
<topic_end>
<topic_start>
there is no clear-cut rule
to be clear, you can use state and setState() to manage all of
the state in your app. in fact, the flutter team does this in many
simple app samples (including the starter app that you get with every
flutter create).
it goes the other way, too. for example, you might decide that—in
the context of your particular app—the selected tab in a bottom
navigation bar is not ephemeral state. you might need to change it
from outside the class, keep it between sessions, and so on.
in that case, the _index variable is app state.
there is no clear-cut, universal rule to distinguish
whether a particular variable is ephemeral or app state.
sometimes, you’ll have to refactor one into another.
for example, you’ll start with some clearly ephemeral state,
but as your application grows in features,
it might need to be moved to app state.
for that reason, take the following diagram with a large grain of salt:
when asked about react’s setState versus redux’s store, the author of redux,
dan abramov, replied:
“the rule of thumb is: do whatever is less awkward.”
in summary, there are two conceptual types of state in any flutter app.
ephemeral state can be implemented using state and setState(),
and is often local to a single widget. the rest is your app state.
both types have their place in any flutter app, and the split between
the two depends on your own preference and the complexity of the app.
<topic_end>
<topic_start>
simple app state management
now that you know about declarative UI programming
and the difference between ephemeral and app state,
you are ready to learn about simple app state management.
on this page, we are going to be using the provider package.
if you are new to flutter and you don’t have a strong reason to choose
another approach (redux, rx, hooks, etc.), this is probably the approach
you should start with. the provider package is easy to understand
and it doesn’t use much code.
it also uses concepts that are applicable in every other approach.
that said, if you have a strong background in
state management from other reactive frameworks,
you can find packages and tutorials listed on the options page.
<topic_end>
<topic_start>
our example
for illustration, consider the following simple app.
the app has two separate screens: a catalog,
and a cart (represented by the MyCatalog,
and MyCart widgets, respectively). it could be a shopping app,
but you can imagine the same structure in a simple social networking
app (replace catalog for “wall” and cart for “favorites”).
the catalog screen includes a custom app bar (myappbar)
and a scrolling view of many list items (mylistitems).
here’s the app visualized as a widget tree.
so we have at least 5 subclasses of widget. many of them need
access to state that “belongs” elsewhere. for example, each
MyListItem needs to be able to add itself to the cart.
it might also want to see whether the currently displayed item
is already in the cart.
this takes us to our first question: where should we put the current
state of the cart?
<topic_end>
<topic_start>
lifting state up
in flutter,
it makes sense to keep the state above the widgets that use it.
why? in declarative frameworks like flutter, if you want to change the UI,
you have to rebuild it. there is no easy way to have
MyCart.updateWith(somethingNew). in other words, it’s hard to
imperatively change a widget from outside, by calling a method on it.
and even if you could make this work, you would be fighting the
framework instead of letting it help you.
even if you get the above code to work,
you would then have to deal
with the following in the MyCart widget:
you would need to take into consideration the current state of the UI
and apply the new data to it. it’s hard to avoid bugs this way.
in flutter, you construct a new widget every time its contents change.
instead of MyCart.updateWith(somethingNew) (a method call)
you use MyCart(contents) (a constructor). because you can only
construct new widgets in the build methods of their parents,
if you want to change contents, it needs to live in MyCart’s
parent or above.
<code_start>
// GOOD
void myTapHandler(BuildContext context) {
  var cartModel = somehowGetMyCartModel(context);
  cartModel.add(item);
}
<code_end>
now MyCart has only one code path for building any version of the UI.
<code_start>
// GOOD
widget build(BuildContext context) {
  var cartModel = somehowGetMyCartModel(context);
  return SomeWidget(
    // just construct the UI once, using the current state of the cart.
    // ···
  );
}
<code_end>
in our example, contents needs to live in MyApp. whenever it changes,
it rebuilds MyCart from above (more on that later). because of this,
MyCart doesn’t need to worry about lifecycle—it just declares
what to show for any given contents. when that changes, the old
MyCart widget disappears and is completely replaced by the new one.
this is what we mean when we say that widgets are immutable.
they don’t change—they get replaced.
now that we know where to put the state of the cart, let’s see how
to access it.
<topic_end>
<topic_start>
accessing the state
when a user clicks on one of the items in the catalog,
it’s added to the cart. but since the cart lives above MyListItem,
how do we do that?
a simple option is to provide a callback that MyListItem can call
when it is clicked. dart’s functions are first class objects,
so you can pass them around any way you want. so, inside
MyCatalog you can define the following:
<code_start>
@override
widget build(BuildContext context) {
  return SomeWidget(
    // construct the widget, passing it a reference to the method above.
    MyListItem(myTapCallback),
  );
}
void myTapCallback(Item item) {
  print('user tapped on $item');
}
<code_end>
this works okay, but for an app state that you need to modify from
many different places, you’d have to pass around a lot of
callbacks—which gets old pretty quickly.
fortunately, flutter has mechanisms for widgets to provide data and
services to their descendants (in other words, not just their children,
but any widgets below them). as you would expect from flutter,
where everything is a widget™, these mechanisms are just special
kinds of widgets—InheritedWidget, InheritedNotifier,
InheritedModel, and more. we won’t be covering those here,
because they are a bit low-level for what we’re trying to do.
instead, we are going to use a package that works with the low-level
widgets but is simple to use. it’s called provider.
before working with provider,
don’t forget to add the dependency on it to your pubspec.yaml.
to add the provider package as a dependency, run flutter pub add:
now you can import 'package:provider/provider.dart';
and start building.
with provider, you don’t need to worry about callbacks or
InheritedWidgets. but you do need to understand 3 concepts:
<topic_end>
<topic_start>
ChangeNotifier
ChangeNotifier is a simple class included in the flutter SDK which provides
change notification to its listeners. in other words, if something is
a ChangeNotifier, you can subscribe to its changes. (it is a form of
observable, for those familiar with the term.)
in provider, ChangeNotifier is one way to encapsulate your application
state. for very simple apps, you get by with a single ChangeNotifier.
in complex ones, you’ll have several models, and therefore several
ChangeNotifiers. (you don’t need to use ChangeNotifier with provider
at all, but it’s an easy class to work with.)
in our shopping app example, we want to manage the state of the cart in a
ChangeNotifier. we create a new class that extends it, like so:
<code_start>
class CartModel extends ChangeNotifier {
  /// internal, private state of the cart.
  final List<Item> _items = [];
  /// an unmodifiable view of the items in the cart.
  UnmodifiableListView<Item> get items => UnmodifiableListView(_items);
  /// the current total price of all items (assuming all items cost $42).
  int get totalPrice => _items.length * 42;
  /// adds [item] to cart. this and [removeall] are the only ways to modify the
  /// cart from the outside.
  void add(Item item) {
    _items.add(item);
    // this call tells the widgets that are listening to this model to rebuild.
    notifyListeners();
  }
  /// removes all items from the cart.
  void removeAll() {
    _items.clear();
    // this call tells the widgets that are listening to this model to rebuild.
    notifyListeners();
  }
}
<code_end>
the only code that is specific to ChangeNotifier is the call
to notifyListeners(). call this method any time the model changes in a way
that might change your app’s UI. everything else in CartModel is the
model itself and its business logic.
ChangeNotifier is part of flutter:foundation and doesn’t depend on
any higher-level classes in flutter. it’s easily testable (you don’t even need
to use widget testing for it). for example,
here’s a simple unit test of CartModel:
<code_start>
test('adding item increases total cost', () {
  final cart = CartModel();
  final startingPrice = cart.totalPrice;
  var i = 0;
  cart.addListener(() {
    expect(cart.totalPrice, greaterThan(startingPrice));
    i++;
  });
  cart.add(Item('Dash'));
  expect(i, 1);
});
<code_end>
<topic_end>
<topic_start>
ChangeNotifierProvider
ChangeNotifierProvider is the widget that provides an instance of
a ChangeNotifier to its descendants. it comes from the provider package.
we already know where to put ChangeNotifierProvider: above the widgets that
need to access it. in the case of CartModel, that means somewhere
above both MyCart and MyCatalog.
you don’t want to place ChangeNotifierProvider higher than necessary
(because you don’t want to pollute the scope). but in our case,
the only widget that is on top of both MyCart and MyCatalog is MyApp.
<code_start>
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => CartModel(),
      child: const MyApp(),
    ),
  );
}
<code_end>
note that we’re defining a builder that creates a new instance
of CartModel. ChangeNotifierProvider is smart enough not to rebuild
CartModel unless absolutely necessary. it also automatically calls
dispose() on CartModel when the instance is no longer needed.
if you want to provide more than one class, you can use MultiProvider:
<code_start>
void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => CartModel()),
        provider(create: (context) => SomeOtherClass()),
      ],
      child: const MyApp(),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
consumer
now that CartModel is provided to widgets in our app through the
ChangeNotifierProvider declaration at the top, we can start using it.
this is done through the consumer widget.
<code_start>
return Consumer<CartModel>(
  builder: (context, cart, child) {
    return Text('Total price: ${cart.totalprice}');
  },
);
<code_end>
we must specify the type of the model that we want to access.
in this case, we want CartModel, so we write
Consumer<CartModel>. if you don’t specify the generic (<cartmodel>),
the provider package won’t be able to help you. provider is based on types,
and without the type, it doesn’t know what you want.
the only required argument of the consumer widget
is the builder. builder is a function that is called whenever the
ChangeNotifier changes. (in other words, when you call notifyListeners()
in your model, all the builder methods of all the corresponding
consumer widgets are called.)
the builder is called with three arguments. the first one is context,
which you also get in every build method.
the second argument of the builder function is the instance of
the ChangeNotifier. it’s what we were asking for in the first place.
you can use the data in the model to define what the UI should look like
at any given point.
the third argument is child, which is there for optimization.
if you have a large widget subtree under your consumer
that doesn’t change when the model changes, you can construct it
once and get it through the builder.
<code_start>
return Consumer<CartModel>(
  builder: (context, cart, child) => stack(
    children: [
      // use SomeExpensiveWidget here, without rebuilding every time.
      if (child != null) child,
      Text('Total price: ${cart.totalprice}'),
    ],
  ),
  // build the expensive widget here.
  child: const SomeExpensiveWidget(),
);
<code_end>
it is best practice to put your consumer widgets as deep in the tree
as possible. you don’t want to rebuild large portions of the UI
just because some detail somewhere changed.
<code_start>
// DON'T DO THIS
return Consumer<CartModel>(
  builder: (context, cart, child) {
    return HumongousWidget(
      // ...
      child: AnotherMonstrousWidget(
        // ...
        child: Text('Total price: ${cart.totalprice}'),
      ),
    );
  },
);
<code_end>
instead:
<code_start>
// DO THIS
return HumongousWidget(
  // ...
  child: AnotherMonstrousWidget(
    // ...
    child: Consumer<CartModel>(
      builder: (context, cart, child) {
        return Text('Total price: ${cart.totalprice}');
      },
    ),
  ),
);
<code_end>
<topic_end>
<topic_start>
provider.of
sometimes, you don’t really need the data in the model to change the
UI but you still need to access it. for example, a ClearCart
button wants to allow the user to remove everything from the cart.
it doesn’t need to display the contents of the cart,
it just needs to call the clear() method.
we could use Consumer<CartModel> for this,
but that would be wasteful. we’d be asking the framework to
rebuild a widget that doesn’t need to be rebuilt.
for this use case, we can use provider.of,
with the listen parameter set to false.
<code_start>
Provider.of<CartModel>(context, listen: false).removeAll();
<code_end>
using the above line in a build method won’t cause this widget to
rebuild when notifyListeners is called.
<topic_end>
<topic_start>
putting it all together
you can check out the example covered in this article.
if you want something simpler,
see what the simple counter app looks like when
built with provider.
by following along with these articles, you’ve greatly 
improved your ability to create state-based applications. 
try building an application with provider yourself to 
master these skills.
<topic_end>
<topic_start>
list of state management approaches
state management is a complex topic.
if you feel that some of your questions haven’t been answered,
or that the approach described on these pages
is not viable for your use cases, you are probably right.
learn more at the following links,
many of which have been contributed by the flutter community:
<topic_end>
<topic_start>
general overview
things to review before selecting an approach.
<topic_end>
<topic_start>
provider
<topic_end>
<topic_start>
riverpod
riverpod works in a similar fashion to provider.
it offers compile safety and testing without depending on the flutter SDK.
<topic_end>
<topic_start>
setState
the low-level approach to use for widget-specific, ephemeral state.
<topic_end>
<topic_start>
InheritedWidget & InheritedModel
the low-level approach used to communicate between ancestors and children
in the widget tree. this is what provider and many other approaches
use under the hood.
the following instructor-led video workshop covers how to
use InheritedWidget:
other useful docs include:
<topic_end>
<topic_start>
june
a lightweight and modern state management library that focuses on providing
a pattern similar to flutter’s built-in state management.
<topic_end>
<topic_start>
redux
a state container approach familiar to many web developers.
<topic_end>
<topic_start>
Fish-Redux
fish redux is an assembled flutter application framework
based on redux state management.
it is suitable for building medium and large applications.
<topic_end>
<topic_start>
BLoC / rx
a family of stream/observable based patterns.
<topic_end>
<topic_start>
GetIt
a service locator based state management approach that
doesn’t need a BuildContext.
info note
  to learn more, watch this short package of the week video on the GetIt package:
<topic_end>
<topic_start>
MobX
a popular library based on observables and reactions.
<topic_end>
<topic_start>
flutter commands
reactive state management that uses the command pattern
and is based on ValueNotifiers. best in combination with
GetIt, but can be used with provider or other
locators too.
<topic_end>
<topic_start>
binder
a state management package that uses InheritedWidget
at its core. inspired in part by recoil.
this package promotes the separation of concerns.
<topic_end>
<topic_start>
GetX
a simplified reactive state management solution.
<topic_end>
<topic_start>
states_rebuilder
an approach that combines state management with a
dependency injection solution and an integrated router.
for more information, see the following info:
<topic_end>
<topic_start>
triple pattern (segmented state pattern)
triple is a pattern for state management that uses streams or ValueNotifier.
this mechanism (nicknamed triple because the stream always uses three
values: error, loading, and state), is based on the
segmented state pattern.
for more information, refer to the following resources:
<topic_end>
<topic_start>
solidart
a simple but powerful state management solution inspired by SolidJS.
<topic_end>
<topic_start>
flutter_reactive_value
the flutter_reactive_value library might offer the least complex solution for state
management in flutter. it might help flutter newcomers add reactivity to their UI,
without the complexity of the mechanisms described before.
the flutter_reactive_value library defines the reactiveValue(BuildContext)
extension method on ValueNotifier. this extension allows a widget to
fetch the current value of the ValueNotifier and
subscribe the widget to changes in the value of the ValueNotifier.
if the value of the ValueNotifier changes, widget rebuilds.
<topic_end>
<topic_start>
networking
<topic_end>
<topic_start>
cross-platform http networking
the http package provides the simplest way to issue http requests. this
package is supported on android, iOS, macOS, windows, linux and the web.
<topic_end>
<topic_start>
platform notes
some platforms require additional steps, as detailed below.
<topic_end>
<topic_start>
android
android apps must declare their use of the internet in the android
manifest (androidmanifest.xml):
<topic_end>
<topic_start>
macOS
macOS apps must allow network access in the relevant *.entitlements files.
learn more about setting up entitlements.
<topic_end>
<topic_start>
samples
for a practical sample of various networking tasks (incl. fetching data,
WebSockets, and parsing data in the background) see the 
networking cookbook.
<topic_end>
<topic_start>
fetch data from the internet
fetching data from the internet is necessary for most apps.
luckily, dart and flutter provide tools, such as the
http package, for this type of work.
info note
  you should avoid directly using dart:io or dart:html
  to make HTTP requests.
  those libraries are platform-dependent
  and tied to a single implementation.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the http package
the http package provides the
simplest way to fetch data from the internet.
to add the http package as a dependency,
run flutter pub add:
import the http package.
<code_start>
import 'package:http/http.dart' as http;
<code_end>
if you are deploying to android, edit your AndroidManifest.xml file to 
add the internet permission.
likewise, if you are deploying to macOS, edit your 
macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements
files to include the network client entitlement.
<topic_end>
<topic_start>
2. make a network request
this recipe covers how to fetch a sample album from the
JSONPlaceholder using the http.get() method.
<code_start>
Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
<code_end>
the http.get() method returns a future that contains a response.
<topic_end>
<topic_start>
3. convert the response into a custom dart object
while it’s easy to make a network request, working with a raw
Future<http.Response> isn’t very convenient.
to make your life easier,
convert the http.Response into a dart object.
<topic_end>
<topic_start>
create an album class
first, create an album class that contains the data from the
network request. it includes a factory constructor that
creates an album from JSON.
converting JSON using pattern matching is only one option.
for more information, see the full article on
JSON and serialization.
<code_start>
class album {
  final int userId;
  final int id;
  final string title;
  const album({
    required this.userId,
    required this.id,
    required this.title,
  });
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'userid': int userId,
        'id': int id,
        'title': string title,
      } =>
        album(
          userId: userId,
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
<code_end>
<topic_end>
<topic_start>
convert the http.Response to an album
now, use the following steps to update the fetchAlbum()
function to return a Future<Album>:
<code_start>
Future<Album> fetchAlbum() async {
  final response = await http
      .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
<code_end>
hooray!
now you’ve got a function that fetches an album from the internet.
<topic_end>
<topic_start>
4. fetch the data
call the fetchAlbum() method in either the
initState() or didChangeDependencies()
methods.
the initState() method is called exactly once and then never again.
if you want to have the option of reloading the API in response to an
InheritedWidget changing, put the call into the
didChangeDependencies() method.
see state for more details.
<code_start>
class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  // ···
}
<code_end>
this future is used in the next step.
<topic_end>
<topic_start>
5. display the data
to display the data on screen, use the
FutureBuilder widget.
the FutureBuilder widget comes with flutter and
makes it easy to work with asynchronous data sources.
you must provide two parameters:
note that snapshot.hasData only returns true
when the snapshot contains a non-null data value.
because fetchAlbum can only return non-null values,
the function should throw an exception
even in the case of a “404 not found” server response.
throwing an exception sets the snapshot.hasError to true
which can be used to display an error message.
otherwise, the spinner will be displayed.
<code_start>
FutureBuilder<Album>(
  future: futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasdata) {
      return text(snapshot.data!.title);
    } else if (snapshot.haserror) {
      return text('${snapshot.error}');
    }
    // by default, show a loading spinner.
    return const CircularProgressIndicator();
  },
)
<code_end>
<topic_end>
<topic_start>
why is fetchAlbum() called in initState()?
although it’s convenient,
it’s not recommended to put an API call in a build() method.
flutter calls the build() method every time it needs
to change anything in the view,
and this happens surprisingly often.
the fetchAlbum() method, if placed inside build(), is repeatedly 
called on each rebuild causing the app to slow down.
storing the fetchAlbum() result in a state variable ensures that
the future is executed only once and then cached for subsequent
rebuilds.
<topic_end>
<topic_start>
testing
for information on how to test this functionality,
see the following recipes:
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
  final response = await http
      .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
class album {
  final int userId;
  final int id;
  final string title;
  const album({
    required this.userId,
    required this.id,
    required this.title,
  });
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'userid': int userId,
        'id': int id,
        'title': string title,
      } =>
        album(
          userId: userId,
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  late Future<Album> futureAlbum;
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'fetch data example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: scaffold(
        appBar: AppBar(
          title: const Text('Fetch data example'),
        ),
        body: center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasdata) {
                return text(snapshot.data!.title);
              } else if (snapshot.haserror) {
                return text('${snapshot.error}');
              }
              // by default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
make authenticated requests
to fetch data from most web services, you need to provide
authorization. there are many ways to do this,
but perhaps the most common uses the authorization HTTP header.
<topic_end>
<topic_start>
add authorization headers
the http package provides a
convenient way to add headers to your requests.
alternatively, use the HttpHeaders
class from the dart:io library.
<code_start>
final response = await http.get(
  uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  // send authorization headers to the backend.
  headers: {
    HttpHeaders.authorizationHeader: 'basic your_api_token_here',
  },
);
<code_end>
<topic_end>
<topic_start>
complete example
this example builds upon the
fetching data from the internet recipe.
<code_start>
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
  final response = await http.get(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    // send authorization headers to the backend.
    headers: {
      HttpHeaders.authorizationHeader: 'basic your_api_token_here',
    },
  );
  final responseJson = jsonDecode(response.body) as Map<String, dynamic>;
  return Album.fromJson(responseJson);
}
class album {
  final int userId;
  final int id;
  final string title;
  const album({
    required this.userId,
    required this.id,
    required this.title,
  });
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'userid': int userId,
        'id': int id,
        'title': string title,
      } =>
        album(
          userId: userId,
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
<code_end>
<topic_end>
<topic_start>
send data to the internet
sending data to the internet is necessary for most apps.
the http package has got that covered, too.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the http package
to add the http package as a dependency,
run flutter pub add:
import the http package.
<code_start>
import 'package:http/http.dart' as http;
<code_end>
if you develop for android, 
add the following permission inside the manifest tag
in the AndroidManifest.xml file located at android/app/src/main.
<topic_end>
<topic_start>
2. sending data to server
this recipe covers how to create an album
by sending an album title to the
JSONPlaceholder using the
http.post() method.
import dart:convert for access to jsonEncode to encode the data:
<code_start>
import 'dart:convert';
<code_end>
use the http.post() method to send the encoded data:
<code_start>
Future<http.Response> createAlbum(String title) {
  return http.post(
    uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, string>{
      'title': title,
    }),
  );
}
<code_end>
the http.post() method returns a future that contains a response.
<topic_end>
<topic_start>
3. convert the http.Response to a custom dart object
while it’s easy to make a network request,
working with a raw Future<http.Response>
isn’t very convenient.  to make your life easier,
convert the http.Response into a dart object.
<topic_end>
<topic_start>
create an album class
first, create an album class that contains
the data from the network request.
it includes a factory constructor that
creates an album from JSON.
converting JSON with pattern matching is only one option.
for more information, see the full article on
JSON and serialization.
<code_start>
class album {
  final int id;
  final string title;
  const album({required this.id, required this.title});
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': string title,
      } =>
        album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
<code_end>
<topic_end>
<topic_start>
convert the http.Response to an album
use the following steps to update the createAlbum()
function to return a Future<Album>:
<code_start>
Future<Album> createAlbum(String title) async {
  final response = await http.post(
    uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, string>{
      'title': title,
    }),
  );
  if (response.statuscode == 201) {
    // if the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}
<code_end>
hooray! now you’ve got a function that sends the title to a
server to create an album.
<topic_end>
<topic_start>
4. get a title from user input
next, create a TextField to enter a title and
a ElevatedButton to send data to server.
also define a TextEditingController to read the
user input from a TextField.
when the ElevatedButton is pressed, the _futureAlbum
is set to the value returned by createAlbum() method.
<code_start>
column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <widget>[
    TextField(
      controller: _controller,
      decoration: const InputDecoration(hintText: 'enter title'),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          _futureAlbum = createAlbum(_controller.text);
        });
      },
      child: const Text('Create data'),
    ),
  ],
)
<code_end>
on pressing the create data button, make the network request,
which sends the data in the TextField to the server
as a POST request.
the future, _futureAlbum, is used in the next step.
<topic_end>
<topic_start>
5. display the response on screen
to display the data on screen, use the
FutureBuilder widget.
the FutureBuilder widget comes with flutter and
makes it easy to work with asynchronous data sources.
you must provide two parameters:
note that snapshot.hasData only returns true when
the snapshot contains a non-null data value.
this is why the createAlbum() function should throw an exception
even in the case of a “404 not found” server response.
if createAlbum() returns null, then
CircularProgressIndicator displays indefinitely.
<code_start>
FutureBuilder<Album>(
  future: _futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasdata) {
      return text(snapshot.data!.title);
    } else if (snapshot.haserror) {
      return text('${snapshot.error}');
    }
    return const CircularProgressIndicator();
  },
)
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> createAlbum(String title) async {
  final response = await http.post(
    uri.parse('https://jsonplaceholder.typicode.com/albums'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, string>{
      'title': title,
    }),
  );
  if (response.statuscode == 201) {
    // if the server did return a 201 CREATED response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 201 CREATED response,
    // then throw an exception.
    throw Exception('Failed to create album.');
  }
}
class album {
  final int id;
  final string title;
  const album({required this.id, required this.title});
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': string title,
      } =>
        album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
void main() {
  runApp(const MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}
class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController();
  Future<Album>? _futureAlbum;
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'create data example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: scaffold(
        appBar: AppBar(
          title: const Text('Create data example'),
        ),
        body: container(
          alignment: alignment.center,
          padding: const EdgeInsets.all(8),
          child: (_futurealbum == null) ? buildColumn() : buildFutureBuilder(),
        ),
      ),
    );
  }
  column buildColumn() {
    return column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <widget>[
        TextField(
          controller: _controller,
          decoration: const InputDecoration(hintText: 'enter title'),
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              _futureAlbum = createAlbum(_controller.text);
            });
          },
          child: const Text('Create data'),
        ),
      ],
    );
  }
  FutureBuilder<Album> buildFutureBuilder() {
    return FutureBuilder<Album>(
      future: _futureAlbum,
      builder: (context, snapshot) {
        if (snapshot.hasdata) {
          return text(snapshot.data!.title);
        } else if (snapshot.haserror) {
          return text('${snapshot.error}');
        }
        return const CircularProgressIndicator();
      },
    );
  }
}
<code_end>
<topic_end>
<topic_start>
update data over the internet
updating data over the internet is necessary for most apps.
the http package has got that covered!
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the http package
to add the http package as a dependency,
run flutter pub add:
import the http package.
<code_start>
import 'package:http/http.dart' as http;
<code_end>
<topic_end>
<topic_start>
2. updating data over the internet using the http package
this recipe covers how to update an album title to the
JSONPlaceholder using the http.put() method.
<code_start>
Future<http.Response> updateAlbum(String title) {
  return http.put(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, string>{
      'title': title,
    }),
  );
}
<code_end>
the http.put() method returns a future that contains a response.
<topic_end>
<topic_start>
3. convert the http.Response to a custom dart object
while it’s easy to make a network request,
working with a raw Future<http.Response>
isn’t very convenient. to make your life easier,
convert the http.Response into a dart object.
<topic_end>
<topic_start>
create an album class
first, create an album class that contains the data from the
network request. it includes a factory constructor that
creates an album from JSON.
converting JSON with pattern matching is only one option.
for more information, see the full article on
JSON and serialization.
<code_start>
class album {
  final int id;
  final string title;
  const album({required this.id, required this.title});
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': string title,
      } =>
        album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
<code_end>
<topic_end>
<topic_start>
convert the http.Response to an album
now, use the following steps to update the updateAlbum()
function to return a Future<Album>:
<code_start>
Future<Album> updateAlbum(String title) async {
  final response = await http.put(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, string>{
      'title': title,
    }),
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to update album.');
  }
}
<code_end>
hooray!
now you’ve got a function that updates the title of an album.
<topic_end>
<topic_start>
4. get the data from the internet
get the data from internet before you can update it.
for a complete example, see the fetch data recipe.
<code_start>
Future<Album> fetchAlbum() async {
  final response = await http.get(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
<code_end>
ideally, you will use this method to set
_futureAlbum during initState to fetch
the data from the internet.
<topic_end>
<topic_start>
5. update the existing title from user input
create a TextField to enter a title and a ElevatedButton
to update the data on server.
also define a TextEditingController to
read the user input from a TextField.
when the ElevatedButton is pressed,
the _futureAlbum is set to the value returned by
updateAlbum() method.
<code_start>
column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <widget>[
    padding(
      padding: const EdgeInsets.all(8),
      child: TextField(
        controller: _controller,
        decoration: const InputDecoration(hintText: 'enter title'),
      ),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          _futureAlbum = updateAlbum(_controller.text);
        });
      },
      child: const Text('Update data'),
    ),
  ],
);
<code_end>
on pressing the update data button, a network request
sends the data in the TextField to the server as a PUT request.
the _futureAlbum variable is used in the next step.
<topic_end>
<topic_start>
5. display the response on screen
to display the data on screen, use the
FutureBuilder widget.
the FutureBuilder widget comes with flutter and
makes it easy to work with async data sources.
you must provide two parameters:
note that snapshot.hasData only returns true when
the snapshot contains a non-null data value.
this is why the updateAlbum function should throw an exception
even in the case of a “404 not found” server response.
if updateAlbum returns null then
CircularProgressIndicator will display indefinitely.
<code_start>
FutureBuilder<Album>(
  future: _futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasdata) {
      return text(snapshot.data!.title);
    } else if (snapshot.haserror) {
      return text('${snapshot.error}');
    }
    return const CircularProgressIndicator();
  },
);
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
  final response = await http.get(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
Future<Album> updateAlbum(String title) async {
  final response = await http.put(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, string>{
      'title': title,
    }),
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to update album.');
  }
}
class album {
  final int id;
  final string title;
  const album({required this.id, required this.title});
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': string title,
      } =>
        album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
void main() {
  runApp(const MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}
class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController();
  late Future<Album> _futureAlbum;
  @override
  void initState() {
    super.initState();
    _futureAlbum = fetchAlbum();
  }
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'update data example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: scaffold(
        appBar: AppBar(
          title: const Text('Update data example'),
        ),
        body: container(
          alignment: alignment.center,
          padding: const EdgeInsets.all(8),
          child: FutureBuilder<Album>(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.connectionstate == ConnectionState.done) {
                if (snapshot.hasdata) {
                  return column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <widget>[
                      text(snapshot.data!.title),
                      TextField(
                        controller: _controller,
                        decoration: const InputDecoration(
                          hintText: 'enter title',
                        ),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          setState(() {
                            _futureAlbum = updateAlbum(_controller.text);
                          });
                        },
                        child: const Text('Update data'),
                      ),
                    ],
                  );
                } else if (snapshot.haserror) {
                  return text('${snapshot.error}');
                }
              }
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
delete data on the internet
this recipe covers how to delete data over
the internet using the http package.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the http package
to add the http package as a dependency,
run flutter pub add:
import the http package.
<code_start>
import 'package:http/http.dart' as http;
<code_end>
<topic_end>
<topic_start>
2. delete data on the server
this recipe covers how to delete an album from the
JSONPlaceholder using the http.delete() method.
note that this requires the id of the album that
you want to delete. for this example,
use something you already know, for example id = 1.
<code_start>
Future<http.Response> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
  );
  return response;
}
<code_end>
the http.delete() method returns a future that contains a response.
<topic_end>
<topic_start>
3. update the screen
in order to check whether the data has been deleted or not,
first fetch the data from the JSONPlaceholder
using the http.get() method, and display it in the screen.
(see the fetch data recipe for a complete example.)
you should now have a delete data button that,
when pressed, calls the deleteAlbum() method.
<code_start>
column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <widget>[
    text(snapshot.data?.title ?? 'deleted'),
    ElevatedButton(
      child: const Text('Delete data'),
      onPressed: () {
        setState(() {
          _futureAlbum =
              deleteAlbum(snapshot.data!.id.toString());
        });
      },
    ),
  ],
);
<code_end>
now, when you click on the delete data button,
the deleteAlbum() method is called and the id
you are passing is the id of the data that you retrieved
from the internet. this means you are going to delete
the same data that you fetched from the internet.
<topic_end>
<topic_start>
returning a response from the deleteAlbum() method
once the delete request has been made,
you can return a response from the deleteAlbum()
method to notify our screen that the data has been deleted.
<code_start>
Future<Album> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON. after deleting,
    // you'll get an empty JSON `{}` response.
    // don't return `null`, otherwise `snapshot.hasdata`
    // will always return false on `futurebuilder`.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a "200 OK response",
    // then throw an exception.
    throw Exception('Failed to delete album.');
  }
}
<code_end>
FutureBuilder() now rebuilds when it receives a response.
since the response won’t have any data in its body
if the request was successful,
the Album.fromJson() method creates an instance of the
album object with a default value (null in our case).
this behavior can be altered in any way you wish.
that’s all!
now you’ve got a function that deletes the data from the internet.
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
  final response = await http.get(
    uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response, then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load album');
  }
}
Future<Album> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
    headers: <string, string>{
      'content-type': 'application/json; charset=UTF-8',
    },
  );
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON. after deleting,
    // you'll get an empty JSON `{}` response.
    // don't return `null`, otherwise `snapshot.hasdata`
    // will always return false on `futurebuilder`.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a "200 OK response",
    // then throw an exception.
    throw Exception('Failed to delete album.');
  }
}
class album {
  final int id;
  final string title;
  const album({required this.id, required this.title});
  factory Album.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'title': string title,
      } =>
        album(
          id: id,
          title: title,
        ),
      _ => throw const FormatException('Failed to load album.'),
    };
  }
}
void main() {
  runApp(const MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}
class _MyAppState extends State<MyApp> {
  late Future<Album> _futureAlbum;
  @override
  void initState() {
    super.initState();
    _futureAlbum = fetchAlbum();
  }
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'delete data example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: scaffold(
        appBar: AppBar(
          title: const Text('Delete data example'),
        ),
        body: center(
          child: FutureBuilder<Album>(
            future: _futureAlbum,
            builder: (context, snapshot) {
              // if the connection is done,
              // check for response data or an error.
              if (snapshot.connectionstate == ConnectionState.done) {
                if (snapshot.hasdata) {
                  return column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <widget>[
                      text(snapshot.data?.title ?? 'deleted'),
                      ElevatedButton(
                        child: const Text('Delete data'),
                        onPressed: () {
                          setState(() {
                            _futureAlbum =
                                deleteAlbum(snapshot.data!.id.toString());
                          });
                        },
                      ),
                    ],
                  );
                } else if (snapshot.haserror) {
                  return text('${snapshot.error}');
                }
              }
              // by default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
communicate with WebSockets
in addition to normal HTTP requests,
you can connect to servers using WebSockets.
WebSockets allow for two-way communication with a server
without polling.
in this example, connect to a
test WebSocket server sponsored by lob.com.
the server sends back the same message you send to it.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. connect to a WebSocket server
the web_socket_channel package provides the
tools you need to connect to a WebSocket server.
the package provides a WebSocketChannel
that allows you to both listen for messages
from the server and push messages to the server.
in flutter, use the following line to
create a WebSocketChannel that connects to a server:
<code_start>
final channel = WebSocketChannel.connect(
  uri.parse('wss://echo.websocket.events'),
);
<code_end>
<topic_end>
<topic_start>
2. listen for messages from the server
now that you’ve established a connection,
listen to messages from the server.
after sending a message to the test server,
it sends the same message back.
in this example, use a StreamBuilder
widget to listen for new messages, and a
text widget to display them.
<code_start>
StreamBuilder(
  stream: channel.stream,
  builder: (context, snapshot) {
    return Text(snapshot.hasData ? '${snapshot.data}' : '');
  },
)
<code_end>
<topic_end>
<topic_start>
how this works
the WebSocketChannel provides a
stream of messages from the server.
the stream class is a fundamental part of the dart:async package.
it provides a way to listen to async events from a data source.
unlike future, which returns a single async response,
the stream class can deliver many events over time.
the StreamBuilder widget connects to a stream
and asks flutter to rebuild every time it
receives an event using the given builder() function.
<topic_end>
<topic_start>
3. send data to the server
to send data to the server,
add() messages to the sink provided
by the WebSocketChannel.
<code_start>
channel.sink.add('Hello!');
<code_end>
<topic_end>
<topic_start>
how this works
the WebSocketChannel provides a
StreamSink to push messages to the server.
the StreamSink class provides a general way to add sync or async
events to a data source.
<topic_end>
<topic_start>
4. close the WebSocket connection
after you’re done using the WebSocket, close the connection:
<code_start>
channel.sink.close();
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const title = 'websocket demo';
    return const MaterialApp(
      title: title,
      home: MyHomePage(
        title: title,
      ),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({
    super.key,
    required this.title,
  });
  final string title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  final _channel = WebSocketChannel.connect(
    uri.parse('wss://echo.websocket.events'),
  );
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(widget.title),
      ),
      body: padding(
        padding: const EdgeInsets.all(20),
        child: column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            form(
              child: TextFormField(
                controller: _controller,
                decoration: const InputDecoration(labelText: 'send a message'),
              ),
            ),
            const SizedBox(height: 24),
            StreamBuilder(
              stream: _channel.stream,
              builder: (context, snapshot) {
                return Text(snapshot.hasData ? '${snapshot.data}' : '');
              },
            )
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'send message',
        child: const Icon(Icons.send),
      ), // this trailing comma makes auto-formatting nicer for build methods.
    );
  }
  void _sendMessage() {
    if (_controller.text.isnotempty) {
      _channel.sink.add(_controller.text);
    }
  }
  @override
  void dispose() {
    _channel.sink.close();
    _controller.dispose();
    super.dispose();
  }
}
<code_end>
<topic_end>
<topic_start>
serialization
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
JSON and serialization
it is hard to think of a mobile app that doesn’t need to communicate with a
web server or easily store structured data at some point. when making
network-connected apps, the chances are that it needs to consume some good old
JSON, sooner or later.
this guide looks into ways of using JSON with flutter.
it covers which JSON solution to use in different scenarios, and why.
info
terminology: encoding and serialization are the same
  thing—turning a data structure into a string.
  decoding and deserialization are the
  opposite process—turning a string into a data structure.
  however, serialization also commonly refers to the entire process of
  translating data structures to and from a more easily readable format.
to avoid confusion, this doc uses “serialization” when referring to the
  overall process, and “encoding” and “decoding” when specifically
  referring to those processes.
<topic_end>
<topic_start>
which JSON serialization method is right for me?
this article covers two general strategies for working with JSON:
different projects come with different complexities and use cases.
for smaller proof-of-concept projects or quick prototypes,
using code generators might be overkill.
for apps with several JSON models with more complexity,
encoding by hand can quickly become tedious, repetitive,
and lend itself to many small errors.
<topic_end>
<topic_start>
use manual serialization for smaller projects
manual JSON decoding refers to using the built-in JSON decoder in
dart:convert. it involves passing the raw JSON string to the jsonDecode()
function, and then looking up the values you need in the resulting
Map<String, dynamic>.
it has no external dependencies or particular setup process,
and it’s good for a quick proof of concept.
manual decoding does not perform well when your project becomes bigger.
writing decoding logic by hand can become hard to manage and error-prone.
if you have a typo when accessing a nonexistent JSON
field, your code throws an error during runtime.
if you do not have many JSON models in your project and are
looking to test a concept quickly,
manual serialization might be the way you want to start.
for an example of manual encoding, see
serializing JSON manually using dart:convert.
lightbulb tip
  for hands-on practice deserializing JSON and
  taking advantage of dart 3’s new features,
  check out the dive into dart’s patterns and records codelab.
<topic_end>
<topic_start>
use code generation for medium to large projects
JSON serialization with code generation means having an external library
generate the encoding boilerplate for you. after some initial setup,
you run a file watcher that generates the code from your model classes.
for example, json_serializable and built_value are these
kinds of libraries.
this approach scales well for a larger project. no hand-written
boilerplate is needed, and typos when accessing JSON fields are caught at
compile-time. the downside with code generation is that it requires some
initial setup. also, the generated source files might produce visual clutter
in your project navigator.
you might want to use generated code for JSON serialization when you have a
medium or a larger project. to see an example of code generation based JSON
encoding, see serializing JSON using code generation libraries.
<topic_end>
<topic_start>
is there a GSON/Jackson/Moshi equivalent in flutter?
the simple answer is no.
such a library would require using runtime reflection, which is disabled in
flutter. runtime reflection interferes with tree shaking, which dart has
supported for quite a long time. with tree shaking, you can “shake off” unused
code from your release builds. this optimizes the app’s size significantly.
since reflection makes all code implicitly used by default, it makes tree
shaking difficult. the tools cannot know what parts are unused at runtime, so
the redundant code is hard to strip away. app sizes cannot be easily optimized
when using reflection.
although you cannot use runtime reflection with flutter,
some libraries give you similarly easy-to-use APIs but are
based on code generation instead. this
approach is covered in more detail in the
code generation libraries section.
<topic_end>
<topic_start>
serializing JSON manually using dart:convert
basic JSON serialization in flutter is very simple. flutter has a built-in
dart:convert library that includes a straightforward JSON encoder and
decoder.
the following sample JSON implements a simple user model.
<code_start>
{
  "name": "john smith",
  "email": "john@example.com"
}
<code_end>
with dart:convert,
you can serialize this JSON model in two ways.
<topic_end>
<topic_start>
serializing JSON inline
by looking at the dart:convert documentation,
you’ll see that you can decode the JSON by calling the
jsonDecode() function, with the JSON string as the method argument.
<code_start>
final user = jsonDecode(jsonString) as Map<String, dynamic>;
print('Howdy, ${user['name']}!');
print('We sent the verification link to ${user['email']}.');
<code_end>
unfortunately, jsonDecode() returns a dynamic, meaning
that you do not know the types of the values until runtime. with this approach,
you lose most of the statically typed language features: type safety,
autocompletion and most importantly, compile-time exceptions. your code will
become instantly more error-prone.
for example, whenever you access the name or email fields, you could quickly
introduce a typo. a typo that the compiler doesn’t know about since the
JSON lives in a map structure.
<topic_end>
<topic_start>
serializing JSON inside model classes
combat the previously mentioned problems by introducing a plain model
class, called user in this example. inside the user class, you’ll find:
with this approach, the calling code can have type safety,
autocompletion for the name and email fields, and compile-time exceptions.
if you make typos or treat the fields as ints instead of strings,
the app won’t compile, instead of crashing at runtime.
user.dart
<code_start>
class user {
  final string name;
  final string email;
  user(this.name, this.email);
  User.fromJson(Map<String, dynamic> json)
      : name = json['name'] as string,
        email = json['email'] as string;
  Map<String, dynamic> toJson() => {
        'name': name,
        'email': email,
      };
}
<code_end>
the responsibility of the decoding logic is now moved inside the model
itself. with this new approach, you can decode a user easily.
<code_start>
final userMap = jsonDecode(jsonString) as Map<String, dynamic>;
final user = User.fromJson(userMap);
print('Howdy, ${user.name}!');
print('We sent the verification link to ${user.email}.');
<code_end>
to encode a user, pass the user object to the jsonEncode() function.
you don’t need to call the toJson() method, since jsonEncode()
already does it for you.
<code_start>
string json = jsonEncode(user);
<code_end>
with this approach, the calling code doesn’t have to worry about JSON
serialization at all. however, the model class still definitely has to.
in a production app, you would want to ensure that the serialization
works properly. in practice, the User.fromJson() and User.toJson()
methods both need to have unit tests in place to verify correct behavior.
info
  the cookbook contains a more comprehensive worked example of using
  JSON model classes, using an isolate to parse
  the JSON file on a background thread. this approach is ideal if you
  need your app to remain responsive while the JSON file is being
  decoded.
however, real-world scenarios are not always that simple.
sometimes JSON API responses are more complex, for example since they 
contain nested JSON objects that must be parsed through their own model
class.
it would be nice if there were something that handled the JSON encoding
and decoding for you.  luckily, there is!
<topic_end>
<topic_start>
serializing JSON using code generation libraries
although there are other libraries available, this guide uses
json_serializable, an automated source code generator that
generates the JSON serialization boilerplate for you.
info
choosing a library:
  you might have noticed two flutter favorite packages
  on pub.dev that generate JSON serialization code,
  json_serializable and built_value.
  how do you choose between these packages?
  the json_serializable package allows you to make regular
  classes serializable by using annotations, 
  whereas the built_value package provides a higher-level way
  of defining immutable value classes that can also be
  serialized to JSON.
since the serialization code is not handwritten or maintained manually
anymore, you minimize the risk of having JSON serialization exceptions at
runtime.
<topic_end>
<topic_start>
setting up json_serializable in a project
to include json_serializable in your project, you need one regular
dependency, and two dev dependencies. in short, dev dependencies
are dependencies that are not included in our app source code—they
are only used in the development environment.
to add the dependencies, run flutter pub add:
run flutter pub get inside your project root folder
(or click packages get in your editor)
to make these new dependencies available in your project.
<topic_end>
<topic_start>
creating model classes the json_serializable way
the following shows how to convert the user class to a
json_serializable class. for the sake of simplicity,
this code uses the simplified JSON model
from the previous samples.
user.dart
<code_start>
import 'package:json_annotation/json_annotation.dart';
/// this allows the `user` class to access private members in
/// the generated file. the value for this is *.g.dart, where
/// the star denotes the source file name.
part 'user.g.dart';
/// an annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@jsonserializable()
class user {
  user(this.name, this.email);
  string name;
  string email;
  /// a necessary factory constructor for creating a new user instance
  /// from a map. pass the map to the generated `_$userfromjson()` constructor.
  /// the constructor is named after the source class, in this case, user.
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  /// `tojson` is the convention for a class to declare support for serialization
  /// to JSON. the implementation simply calls the private, generated
  /// helper method `_$usertojson`.
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
<code_end>
with this setup, the source code generator generates code for encoding
and decoding the name and email fields from JSON.
if needed, it is also easy to customize the naming strategy.
for example, if the API returns objects with snake_case,
and you want to use lowerCamelCase in your models,
you can use the @jsonkey annotation with a name parameter:
it’s best if both server and client follow the same naming strategy.
@jsonserializable() provides fieldRename enum for totally converting dart 
fields into JSON keys.
modifying @jsonserializable(fieldrename: FieldRename.snake) is equivalent to
adding @jsonkey(name: '<snake_case>') to each field.
sometimes server data is uncertain, so it is necessary to verify and protect data
 on client.
other commonly used @jsonkey annotations include:
<topic_end>
<topic_start>
running the code generation utility
when creating json_serializable classes the first time,
you’ll get errors similar to what is shown in the image below.
these errors are entirely normal and are simply because the generated code for
the model class does not exist yet. to resolve this, run the code
generator that generates the serialization boilerplate.
there are two ways of running the code generator.
<topic_end>
<topic_start>
one-time code generation
by running dart run build_runner build --delete-conflicting-outputs in the project root,
you generate JSON serialization code for your models whenever they are needed.
this triggers a one-time build that goes through the source files, picks the
relevant ones, and generates the necessary serialization code for them.
while this is convenient, it would be nice if you did not have to run the
build manually every time you make changes in your model classes.
<topic_end>
<topic_start>
generating code continuously
a watcher makes our source code generation process more convenient. it
watches changes in our project files and automatically builds the necessary
files when needed. start the watcher by running
dart run build_runner watch --delete-conflicting-outputs in the project root.
it is safe to start the watcher once and leave it running in the background.
<topic_end>
<topic_start>
consuming json_serializable models
to decode a JSON string the json_serializable way,
you do not have actually to make any changes to our previous code.
<code_start>
final userMap = jsonDecode(jsonString) as Map<String, dynamic>;
final user = User.fromJson(userMap);
<code_end>
the same goes for encoding. the calling API is the same as before.
<code_start>
string json = jsonEncode(user);
<code_end>
with json_serializable,
you can forget any manual JSON serialization in the user class.
the source code generator creates a file called user.g.dart,
that has all the necessary serialization logic.
you no longer have to write automated tests to ensure
that the serialization works—it’s now
the library’s responsibility to make sure the serialization works
appropriately.
<topic_end>
<topic_start>
generating code for nested classes
you might have code that has nested classes within a class.
if that is the case, and you have tried to pass the class in JSON format
as an argument to a service (such as firebase, for example),
you might have experienced an invalid argument error.
consider the following address class:
<code_start>
import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';
@jsonserializable()
class address {
  string street;
  string city;
  address(this.street, this.city);
  factory Address.fromJson(Map<String, dynamic> json) =>
      _$AddressFromJson(json);
  Map<String, dynamic> toJson() => _$AddressToJson(this);
}
<code_end>
the address class is nested inside the user class:
<code_start>
import 'package:json_annotation/json_annotation.dart';
import 'address.dart';
part 'user.g.dart';
@jsonserializable()
class user {
  user(this.name, this.address);
  string name;
  address address;
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
<code_end>
running 
dart run build_runner build --delete-conflicting-outputs
in the terminal creates
the *.g.dart file, but the private _$UserToJson() function
looks something like the following:
all looks fine now, but if you do a print() on the user object:
<code_start>
address address = Address('My st.', 'new york');
user user = User('John', address);
print(user.toJson());
<code_end>
the result is:
when what you probably want is output like the following:
to make this work, pass explicitToJson: true in the @jsonserializable()
annotation over the class declaration. the user class now looks as follows:
<code_start>
import 'package:json_annotation/json_annotation.dart';
import 'address.dart';
part 'user.g.dart';
@jsonserializable(explicittojson: true)
class user {
  user(this.name, this.address);
  string name;
  address address;
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
<code_end>
for more information, see explicitToJson in the
JsonSerializable class for the json_annotation package.
<topic_end>
<topic_start>
further references
for more information, see the following resources:
<topic_end>
<topic_start>
parse JSON in the background
by default, dart apps do all of their work on a single thread.
in many cases, this model simplifies coding and is fast enough
that it does not result in poor app performance or stuttering animations,
often called “jank.”
however, you might need to perform an expensive computation,
such as parsing a very large JSON document.
if this work takes more than 16 milliseconds,
your users experience jank.
to avoid jank, you need to perform expensive computations
like this in the background.
on android, this means scheduling work on a different thread.
in flutter, you can use a separate isolate.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the http package
first, add the http package to your project.
the http package makes it easier to perform network
requests, such as fetching data from a JSON endpoint.
to add the http package as a dependency,
run flutter pub add:
<topic_end>
<topic_start>
2. make a network request
this example covers how to fetch a large JSON document
that contains a list of 5000 photo objects from the
JSONPlaceholder REST API,
using the http.get() method.
<code_start>
Future<http.Response> fetchPhotos(http.Client client) async {
  return client.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
}
<code_end>
info note
  you’re providing an http.Client to the function in this example.
  this makes the function easier to test and use in different environments.
<topic_end>
<topic_start>
3. parse and convert the JSON into a list of photos
next, following the guidance from the
fetch data from the internet recipe,
convert the http.Response into a list of dart objects.
this makes the data easier to work with.
<topic_end>
<topic_start>
create a photo class
first, create a photo class that contains data about a photo.
include a fromJson() factory method to make it easy to create a
photo starting with a JSON object.
<code_start>
class photo {
  final int albumId;
  final int id;
  final string title;
  final string url;
  final string thumbnailUrl;
  const photo({
    required this.albumId,
    required this.id,
    required this.title,
    required this.url,
    required this.thumbnailUrl,
  });
  factory Photo.fromJson(Map<String, dynamic> json) {
    return photo(
      albumId: json['albumId'] as int,
      id: json['id'] as int,
      title: json['title'] as string,
      url: json['url'] as string,
      thumbnailUrl: json['thumbnailUrl'] as string,
    );
  }
}
<code_end>
<topic_end>
<topic_start>
convert the response into a list of photos
now, use the following instructions to update the
fetchPhotos() function so that it returns a
Future<List<Photo>>:
<code_start>
// a function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
  final parsed =
      (jsondecode(responsebody) as List).cast<Map<String, dynamic>>();
  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client
      .get(uri.parse('https://jsonplaceholder.typicode.com/photos'));
  // synchronously run parsePhotos in the main isolate.
  return parsePhotos(response.body);
}
<code_end>
<topic_end>
<topic_start>
4. move this work to a separate isolate
if you run the fetchPhotos() function on a slower device,
you might notice the app freezes for a brief moment as it parses and
converts the JSON. this is jank, and you want to get rid of it.
you can remove the jank by moving the parsing and conversion
to a background isolate using the compute()
function provided by flutter. the compute() function runs expensive
functions in a background isolate and returns the result. in this case,
run the parsePhotos() function in the background.
<code_start>
Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client
      .get(uri.parse('https://jsonplaceholder.typicode.com/photos'));
  // use the compute function to run parsePhotos in a separate isolate.
  return compute(parsePhotos, response.body);
}
<code_end>
<topic_end>
<topic_start>
notes on working with isolates
isolates communicate by passing messages back and forth. these messages can
be primitive values, such as null, num, bool, double, or string, or
simple objects such as the List<Photo> in this example.
you might experience errors if you try to pass more complex objects,
such as a future or http.Response between isolates.
as an alternate solution, check out the worker_manager or
workmanager packages for background processing.
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
  final response = await client
      .get(uri.parse('https://jsonplaceholder.typicode.com/photos'));
  // use the compute function to run parsePhotos in a separate isolate.
  return compute(parsePhotos, response.body);
}
// a function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
  final parsed =
      (jsondecode(responsebody) as List).cast<Map<String, dynamic>>();
  return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
class photo {
  final int albumId;
  final int id;
  final string title;
  final string url;
  final string thumbnailUrl;
  const photo({
    required this.albumId,
    required this.id,
    required this.title,
    required this.url,
    required this.thumbnailUrl,
  });
  factory Photo.fromJson(Map<String, dynamic> json) {
    return photo(
      albumId: json['albumId'] as int,
      id: json['id'] as int,
      title: json['title'] as string,
      url: json['url'] as string,
      thumbnailUrl: json['thumbnailUrl'] as string,
    );
  }
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    const appTitle = 'isolate demo';
    return const MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}
class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});
  final string title;
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(title),
      ),
      body: FutureBuilder<List<Photo>>(
        future: fetchPhotos(http.Client()),
        builder: (context, snapshot) {
          if (snapshot.haserror) {
            return const center(
              child: Text('An error has occurred!'),
            );
          } else if (snapshot.hasdata) {
            return PhotosList(photos: snapshot.data!);
          } else {
            return const center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}
class PhotosList extends StatelessWidget {
  const PhotosList({super.key, required this.photos});
  final List<Photo> photos;
  @override
  widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemCount: photos.length,
      itemBuilder: (context, index) {
        return Image.network(photos[index].thumbnailUrl);
      },
    );
  }
}
<code_end>
<topic_end>
<topic_start>
persistence
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
store key-value data on disk
if you have a relatively small collection of key-values
to save, you can use the shared_preferences plugin.
normally, you would have to
write native platform integrations for storing data on each platform.
fortunately, the shared_preferences plugin can be used to
persist key-value data to disk on each platform flutter supports.
this recipe uses the following steps:
info note
  to learn more, watch this short package of the week video
  on the shared_preferences package:
<topic_end>
<topic_start>
1. add the dependency
before starting, add the shared_preferences package as a dependency.
to add the shared_preferences package as a dependency,
run flutter pub add:
<topic_end>
<topic_start>
2. save data
to persist data, use the setter methods provided by the
SharedPreferences class. setter methods are available for
various primitive types, such as setInt, setBool, and setString.
setter methods do two things: first, synchronously update the
key-value pair in memory. then, persist the data to disk.
<code_start>
// load and obtain the shared preferences for this app.
final prefs = await SharedPreferences.getInstance();
// save the counter value to persistent storage under the 'counter' key.
await prefs.setInt('counter', counter);
<code_end>
<topic_end>
<topic_start>
3. read data
to read data, use the appropriate getter method provided by the
SharedPreferences class. for each setter there is a corresponding getter.
for example, you can use the getInt, getBool, and getString methods.
<code_start>
final prefs = await SharedPreferences.getInstance();
// try reading the counter value from persistent storage.
// if not present, null is returned, so default to 0.
final counter = prefs.getInt('counter') ?? 0;
<code_end>
note that the getter methods throw an exception if the persisted value
has a different type than the getter method expects.
<topic_end>
<topic_start>
4. remove data
to delete data, use the remove() method.
<code_start>
final prefs = await SharedPreferences.getInstance();
// remove the counter key-value pair from persistent storage.
await prefs.remove('counter');
<code_end>
<topic_end>
<topic_start>
supported types
although the key-value storage provided by shared_preferences is
easy and convenient to use, it has limitations:
<topic_end>
<topic_start>
testing support
it’s a good idea to test code that persists data using shared_preferences.
to enable this, the package provides an
in-memory mock implementation of the preference store.
to set up your tests to use the mock implementation,
call the setMockInitialValues static method in
a setUpAll() method in your test files.
pass in a map of key-value pairs to use as the initial values.
<code_start>
SharedPreferences.setMockInitialValues(<String, object>{
  'counter': 2,
});
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'shared preferences demo',
      home: MyHomePage(title: 'shared preferences demo'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final string title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  @override
  void initState() {
    super.initState();
    _loadCounter();
  }
  /// load the initial counter value from persistent storage on start,
  /// or fallback to 0 if it doesn't exist.
  future<void> _loadCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = prefs.getInt('counter') ?? 0;
    });
  }
  /// after a click, increment the counter state and
  /// asynchronously save it to persistent storage.
  future<void> _incrementCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getint('counter') ?? 0) + 1;
      prefs.setInt('counter', _counter);
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(widget.title),
      ),
      body: center(
        child: column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const text(
              'you have pushed the button this many times: ',
            ),
            text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
read and write files
in some cases, you need to read and write files to disk.
for example, you might need to persist data across app launches,
or download data from the internet and save it for later offline use.
to save files to disk on mobile or desktop apps,
combine the path_provider plugin with the dart:io library.
this recipe uses the following steps:
to learn more, watch this package of the week video
on the path_provider package:
info note
  this recipe doesn’t work with web apps at this time.
  to follow the discussion on this issue,
  check out flutter/flutter issue #45296.
<topic_end>
<topic_start>
1. find the correct local path
this example displays a counter. when the counter changes,
write data on disk so you can read it again when the app loads.
where should you store this data?
the path_provider package
provides a platform-agnostic way to access commonly used locations on the
device’s file system. the plugin currently supports access to
two file system locations:
this example stores information in the documents directory.
you can find the path to the documents directory as follows:
<code_start>
Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}
<code_end>
<topic_end>
<topic_start>
2. create a reference to the file location
once you know where to store the file, create a reference to the
file’s full location. you can use the file
class from the dart:io library to achieve this.
<code_start>
Future<File> get _localFile async {
  final path = await _localPath;
  return file('$path/counter.txt');
}
<code_end>
<topic_end>
<topic_start>
3. write data to the file
now that you have a file to work with,
use it to read and write data.
first, write some data to the file.
the counter is an integer, but is written to the
file as a string using the '$counter' syntax.
<code_start>
Future<File> writeCounter(int counter) async {
  final file = await _localFile;
  // write the file
  return file.writeAsString('$counter');
}
<code_end>
<topic_end>
<topic_start>
4. read data from the file
now that you have some data on disk, you can read it.
once again, use the file class.
<code_start>
future<int> readCounter() async {
  try {
    final file = await _localFile;
    // read the file
    final contents = await file.readAsString();
    return int.parse(contents);
  } catch (e) {
    // if encountering an error, return 0
    return 0;
  }
}
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
  runApp(
    MaterialApp(
      title: 'reading and writing files',
      home: FlutterDemo(storage: CounterStorage()),
    ),
  );
}
class CounterStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
  Future<File> get _localFile async {
    final path = await _localPath;
    return file('$path/counter.txt');
  }
  future<int> readCounter() async {
    try {
      final file = await _localFile;
      // read the file
      final contents = await file.readAsString();
      return int.parse(contents);
    } catch (e) {
      // if encountering an error, return 0
      return 0;
    }
  }
  Future<File> writeCounter(int counter) async {
    final file = await _localFile;
    // write the file
    return file.writeAsString('$counter');
  }
}
class FlutterDemo extends StatefulWidget {
  const FlutterDemo({super.key, required this.storage});
  final CounterStorage storage;
  @override
  State<FlutterDemo> createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
  int _counter = 0;
  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((value) {
      setState(() {
        _counter = value;
      });
    });
  }
  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });
    // write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('Reading and writing files'),
      ),
      body: center(
        child: text(
          'button tapped $_counter time${_counter == 1 ? '' : 's'}.',
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
persist data with SQLite
info note
  this guide uses the sqflite package.
  this package only supports apps that run on
  macOS, iOS, or android.
if you are writing an app that needs to persist and query large amounts of data on
the local device, consider using a database instead of a local file or
key-value store. in general, databases provide faster inserts, updates,
and queries compared to other local persistence solutions.
flutter apps can make use of the SQLite databases via the
sqflite plugin available on pub.dev.
this recipe demonstrates the basics of using sqflite
to insert, read, update, and remove data about various dogs.
if you are new to SQLite and SQL statements, review the
SQLite tutorial to learn the basics before
completing this recipe.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. add the dependencies
to work with SQLite databases, import the sqflite and
path packages.
to add the packages as a dependency,
run flutter pub add:
make sure to import the packages in the file you’ll be working in.
<code_start>
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
<code_end>
<topic_end>
<topic_start>
2. define the dog data model
before creating the table to store information on dogs, take a few moments to
define the data that needs to be stored. for this example, define a dog class
that contains three pieces of data:
a unique id, the name, and the age of each dog.
<code_start>
class dog {
  final int id;
  final string name;
  final int age;
  const dog({
    required this.id,
    required this.name,
    required this.age,
  });
}
<code_end>
<topic_end>
<topic_start>
3. open the database
before reading and writing data to the database, open a connection
to the database. this involves two steps:
info note
  in order to use the keyword await, the code must be placed
  inside an async function. you should place all the following
  table functions inside void main() async {}.
<code_start>
// avoid errors caused by flutter upgrade.
// importing 'package:flutter/widgets.dart' is required.
WidgetsFlutterBinding.ensureInitialized();
// open the database and store the reference.
final database = openDatabase(
  // set the path to the database. note: using the `join` function from the
  // `path` package is best practice to ensure the path is correctly
  // constructed for each platform.
  join(await getDatabasesPath(), 'doggie_database.db'),
);
<code_end>
<topic_end>
<topic_start>
4. create the dogs table
next, create a table to store information about various dogs.
for this example, create a table called dogs that defines the data
that can be stored. each dog contains an id, name, and age.
therefore, these are represented as three columns in the dogs table.
for more information about the available datatypes that can be stored in a
SQLite database, see the official SQLite datatypes documentation.
<code_start>
final database = openDatabase(
  // set the path to the database. note: using the `join` function from the
  // `path` package is best practice to ensure the path is correctly
  // constructed for each platform.
  join(await getDatabasesPath(), 'doggie_database.db'),
  // when the database is first created, create a table to store dogs.
  onCreate: (db, version) {
    // run the CREATE TABLE statement on the database.
    return db.execute(
      'create TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
    );
  },
  // set the version. this executes the onCreate function and provides a
  // path to perform database upgrades and downgrades.
  version: 1,
);
<code_end>
<topic_end>
<topic_start>
5. insert a dog into the database
now that you have a database with a table suitable for storing information
about various dogs, it’s time to read and write data.
first, insert a dog into the dogs table. this involves two steps:
<code_start>
class dog {
  final int id;
  final string name;
  final int age;
  dog({
    required this.id,
    required this.name,
    required this.age,
  });
  // convert a dog into a map. the keys must correspond to the names of the
  // columns in the database.
  Map<String, object?> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
    };
  }
  // implement toString to make it easier to see information about
  // each dog when using the print statement.
  @override
  string toString() {
    return 'dog{id: $id, name: $name, age: $age}';
  }
}
<code_end>
<code_start>
// define a function that inserts dogs into the database
future<void> insertDog(Dog dog) async {
  // get a reference to the database.
  final db = await database;
  // insert the dog into the correct table. you might also specify the
  // `conflictalgorithm` to use in case the same dog is inserted twice.
  //
  // in this case, replace any previous data.
  await db.insert(
    'dogs',
    dog.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}
<code_end>
<code_start>
// create a dog and add it to the dogs table
var fido = dog(
  id: 0,
  name: 'fido',
  age: 35,
);
await insertDog(fido);
<code_end>
<topic_end>
<topic_start>
6. retrieve the list of dogs
now that a dog is stored in the database, query the database
for a specific dog or a list of all dogs. this involves two steps:
<code_start>
// a method that retrieves all the dogs from the dogs table.
Future<List<Dog>> dogs() async {
  // get a reference to the database.
  final db = await database;
  // query the table for all the dogs.
  final List<Map<String, object?>> dogMaps = await db.query('dogs');
  // convert the list of each dog's fields into a list of `dog` objects.
  return [
    for (final {
          'id': id as int,
          'name': name as string,
          'age': age as int,
        } in dogMaps)
      dog(id: id, name: name, age: age),
  ];
}
<code_end>
<code_start>
// now, use the method above to retrieve all the dogs.
print(await dogs()); // prints a list that include fido.
<code_end>
<topic_end>
<topic_start>
7. update a dog in the database
after inserting information into the database,
you might want to update that information at a later time.
you can do this by using the update()
method from the sqflite library.
this involves two steps:
<code_start>
future<void> updateDog(Dog dog) async {
  // get a reference to the database.
  final db = await database;
  // update the given dog.
  await db.update(
    'dogs',
    dog.toMap(),
    // ensure that the dog has a matching id.
    where: 'id = ?',
    // pass the dog's id as a whereArg to prevent SQL injection.
    whereArgs: [dog.id],
  );
}
<code_end>
<code_start>
// update fido's age and save it to the database.
fido = dog(
  id: fido.id,
  name: fido.name,
  age: fido.age + 7,
);
await updateDog(fido);
// print the updated results.
print(await dogs()); // prints fido with age 42.
<code_end>
warning warning
  always use whereArgs to pass arguments to a where statement.
  this helps safeguard against SQL injection attacks.
do not use string interpolation, such as where: "id = ${dog.id}"!
<topic_end>
<topic_start>
8. delete a dog from the database
in addition to inserting and updating information about dogs,
you can also remove dogs from the database. to delete data,
use the delete() method from the sqflite library.
in this section, create a function that takes an id and deletes the dog with
a matching id from the database. to make this work, you must provide a where
clause to limit the records being deleted.
<code_start>
future<void> deleteDog(int id) async {
  // get a reference to the database.
  final db = await database;
  // remove the dog from the database.
  await db.delete(
    'dogs',
    // use a `where` clause to delete a specific dog.
    where: 'id = ?',
    // pass the dog's id as a whereArg to prevent SQL injection.
    whereArgs: [id],
  );
}
<code_end>
<topic_end>
<topic_start>
example
to run the example:
<code_start>
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
void main() async {
  // avoid errors caused by flutter upgrade.
  // importing 'package:flutter/widgets.dart' is required.
  WidgetsFlutterBinding.ensureInitialized();
  // open the database and store the reference.
  final database = openDatabase(
    // set the path to the database. note: using the `join` function from the
    // `path` package is best practice to ensure the path is correctly
    // constructed for each platform.
    join(await getDatabasesPath(), 'doggie_database.db'),
    // when the database is first created, create a table to store dogs.
    onCreate: (db, version) {
      // run the CREATE TABLE statement on the database.
      return db.execute(
        'create TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
      );
    },
    // set the version. this executes the onCreate function and provides a
    // path to perform database upgrades and downgrades.
    version: 1,
  );
  // define a function that inserts dogs into the database
  future<void> insertDog(Dog dog) async {
    // get a reference to the database.
    final db = await database;
    // insert the dog into the correct table. you might also specify the
    // `conflictalgorithm` to use in case the same dog is inserted twice.
    //
    // in this case, replace any previous data.
    await db.insert(
      'dogs',
      dog.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }
  // a method that retrieves all the dogs from the dogs table.
  Future<List<Dog>> dogs() async {
    // get a reference to the database.
    final db = await database;
    // query the table for all the dogs.
    final List<Map<String, object?>> dogMaps = await db.query('dogs');
    // convert the list of each dog's fields into a list of `dog` objects.
    return [
      for (final {
            'id': id as int,
            'name': name as string,
            'age': age as int,
          } in dogMaps)
        dog(id: id, name: name, age: age),
    ];
  }
  future<void> updateDog(Dog dog) async {
    // get a reference to the database.
    final db = await database;
    // update the given dog.
    await db.update(
      'dogs',
      dog.toMap(),
      // ensure that the dog has a matching id.
      where: 'id = ?',
      // pass the dog's id as a whereArg to prevent SQL injection.
      whereArgs: [dog.id],
    );
  }
  future<void> deleteDog(int id) async {
    // get a reference to the database.
    final db = await database;
    // remove the dog from the database.
    await db.delete(
      'dogs',
      // use a `where` clause to delete a specific dog.
      where: 'id = ?',
      // pass the dog's id as a whereArg to prevent SQL injection.
      whereArgs: [id],
    );
  }
  // create a dog and add it to the dogs table
  var fido = dog(
    id: 0,
    name: 'fido',
    age: 35,
  );
  await insertDog(fido);
  // now, use the method above to retrieve all the dogs.
  print(await dogs()); // prints a list that include fido.
  // update fido's age and save it to the database.
  fido = dog(
    id: fido.id,
    name: fido.name,
    age: fido.age + 7,
  );
  await updateDog(fido);
  // print the updated results.
  print(await dogs()); // prints fido with age 42.
  // delete fido from the database.
  await deleteDog(fido.id);
  // print the list of dogs (empty).
  print(await dogs());
}
class dog {
  final int id;
  final string name;
  final int age;
  dog({
    required this.id,
    required this.name,
    required this.age,
  });
  // convert a dog into a map. the keys must correspond to the names of the
  // columns in the database.
  Map<String, object?> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
    };
  }
  // implement toString to make it easier to see information about
  // each dog when using the print statement.
  @override
  string toString() {
    return 'dog{id: $id, name: $name, age: $age}';
  }
}
<code_end>
<topic_end>
<topic_start>
firebase
<topic_end>
<topic_start>
introduction
firebase is a Backend-as-a-Service (baas) app development platform
that provides hosted backend services such as a realtime database,
cloud storage, authentication, crash reporting, machine learning,
remote configuration, and hosting for your static files.
<topic_end>
<topic_start>
flutter and firebase resources
firebase supports flutter. to learn more,
check out the following resources.
<topic_end>
<topic_start>
documentation
<topic_end>
<topic_start>
blog posts
use firebase to host your flutter app on the web
<topic_end>
<topic_start>
tutorials
get to know firebase for flutter
<topic_end>
<topic_start>
flutter and firebase community resources
the flutter community created the following useful resources.
<topic_end>
<topic_start>
blog posts
building chat app with flutter and firebase
<topic_end>
<topic_start>
videos
<topic_end>
<topic_start>
google APIs
the google APIs package exposes dozens of google
services that you can use from dart projects.
this page describes how to use APIs that interact with
end-user data by using google authentication.
examples of user-data APIs include
calendar, gmail, YouTube, and firebase.
info 
  the only APIs you should use directly from your flutter
  project are those that access user data using google authentication.
APIs that require service accounts should not
  be used directly from a flutter application.
  doing so requires shipping service credentials as part
  of your application, which is not secure.
  to use these APIs,
  we recommend creating an intermediate service.
to add authentication to firebase explicitly, check out the
add a user authentication flow to a flutter app using FirebaseUI
codelab and the
get started with firebase authentication on flutter docs.
<topic_end>
<topic_start>
overview
to use google APIs, follow these steps:
<topic_end>
<topic_start>
1. pick the desired API
the documentation for package:googleapis lists
each API as a separate dart library&emdash;in a
name_version format.
check out youtube_v3 as an example.
each library might provide many types,
but there is one root class that ends in api.
for YouTube, it’s YouTubeApi.
not only is the api class the one you need to
instantiate (see step 3), but it also
exposes the scopes that represent the permissions
needed to use the API. for example,
the constants section of the
YouTubeApi class lists the available scopes.
to request access to read (but not write) an end-users
YouTube data, authenticate the user with
youtubeReadonlyScope.
<code_start>
/// provides the `youtubeapi` class.
import 'package:googleapis/youtube/v3.dart';
<code_end>
<topic_end>
<topic_start>
2. enable the API
to use google APIs you must have a google account
and a google project. you also
need to enable your desired API.
this example enables YouTube data API v3.
for details, see the getting started instructions.
<topic_end>
<topic_start>
3. authenticate the user with the required scopes
use the google_sign_in package to
authenticate users with their google identity.
configure signin for each platform you want to support.
<code_start>
/// provides the `googlesignin` class
import 'package:google_sign_in/google_sign_in.dart';
<code_end>
when instantiating the GoogleSignIn class,
provide the desired scopes as discussed
in the previous section.
<code_start>
final _googleSignIn = GoogleSignIn(
  scopes: <string>[youtubeapi.youtubereadonlyscope],
);
<code_end>
follow the instructions provided by
package:google_sign_in
to allow a user to authenticate.
once authenticated,
you must obtain an authenticated HTTP client.
<topic_end>
<topic_start>
4. obtain an authenticated HTTP client
the extension_google_sign_in_as_googleapis_auth
package provides an extension method on GoogleSignIn
called authenticatedClient.
<code_start>
import 'package:extension_google_sign_in_as_googleapis_auth/extension_google_sign_in_as_googleapis_auth.dart';
<code_end>
add a listener to onCurrentUserChanged
and when the event value isn’t null,
you can create an authenticated client.
<code_start>
var httpClient = (await _googleSignIn.authenticatedClient())!;
<code_end>
this client instance includes the necessary
credentials when invoking google API classes.
<topic_end>
<topic_start>
5. create and use the desired API class
use the API to create the desired API type and call methods.
for instance:
<code_start>
var youTubeApi = YouTubeApi(httpClient);
var favorites = await youTubeApi.playlistItems.list(
  ['snippet'],
  playlistId: 'll', // liked list
);
<code_end>
<topic_end>
<topic_start>
more information
you might want to check out the following:
<topic_end>
<topic_start>
supported deployment platforms
as of flutter 3.19.0,
flutter supports deploying apps the following combinations of
hardware architectures and operating system versions.
these combinations are called platforms.
flutter supports platforms in three tiers:
based on these tiers, flutter supports deploying to the following platforms.
android supports IA32 (x86) in software emulation only.
<topic_end>
<topic_start>
desktop support for flutter
flutter provides support for compiling
a native windows, macOS, or linux desktop app.
flutter’s desktop support also extends to plugins—you
can install existing plugins that support the windows,
macOS, or linux platforms, or you can create your own.
info note
  this page covers developing apps for all desktop
  platforms. once you’ve read this, you can dive into
  specific platform information at the following links:
<topic_end>
<topic_start>
requirements
to compile a desktop application,
you must build it on the targeted
platform: build a windows application on windows,
a macOS application on macOS,
and a linux application on linux.
to create a flutter application with desktop support,
you need the following software:
<topic_end>
<topic_start>
additional windows requirements
for windows desktop development,
you need the following in addition to the flutter SDK:
info note
visual studio is different than visual studio code.
<topic_end>
<topic_start>
additional macOS requirements
for macOS desktop development,
you need the following in addition to the flutter SDK:
<topic_end>
<topic_start>
additional linux requirements
for linux desktop development,
you need the following in addition to the flutter SDK:
one easy way to install the flutter SDK along with the necessary
dependencies is by using snapd.
for more information, see installing snapd.
once you have snapd, you can install flutter
using the snap store, or at the command line:
alternatively, if you prefer not to use snapd,
you can use the following command:
<topic_end>
<topic_start>
create a new project
you can use the following steps
to create a new project with desktop support.
<topic_end>
<topic_start>
set up
you might run flutter doctor to see if
there are any unresolved issues.
you should see a checkmark for each successfully
configured area. it should look something like
the following on windows,
with an entry for “develop for windows”:
on macOS, look for a line like this:
on linux, look for a line like this:
if flutter doctor finds problems or missing components
for a platform that you don’t want to develop for,
you can ignore those warnings. or you can disable the
platform altogether using the flutter config command,
for example:
other available flags:
after enabling desktop support,
restart your IDE so that it can detect the new device.
<topic_end>
<topic_start>
create and run
creating a new project with desktop support is no different
than creating a new flutter project for other platforms.
once you’ve configured your environment for desktop
support, you can create and run a desktop application
either in the IDE or from the command line.
<topic_end>
<topic_start>
using an IDE
after you’ve configured your environment to support
desktop, make sure you restart the IDE if it was
already running.
create a new application in your IDE and it automatically
creates iOS, android, web, and desktop versions of your app.
from the device pulldown, select windows (desktop),
macOS (desktop), or linux (desktop)
and run your application to see it launch on the desktop.
<topic_end>
<topic_start>
from the command line
to create a new application that includes desktop support
(in addition to mobile and web support), run the following commands,
substituting my_app with the name of your project:
to launch your application from the command line,
enter one of the following commands from the top
of the package:
info note
  if you do not supply the -d flag, flutter run lists
  the available targets to choose from.
<topic_end>
<topic_start>
build a release app
to generate a release build,
run one of the following commands:
<topic_end>
<topic_start>
add desktop support to an existing flutter app
to add desktop support to an existing flutter project,
run the following command in a terminal from the
root project directory:
this adds the necessary desktop files and directories
to your existing flutter project.
to add only specific desktop platforms,
change the platforms list to include only
the platform(s) you want to add.
<topic_end>
<topic_start>
plugin support
flutter on the desktop supports using and creating plugins.
to use a plugin that supports desktop,
follow the steps for plugins in using packages.
flutter automatically adds the necessary native code
to your project, as with any other platform.
<topic_end>
<topic_start>
writing a plugin
when you start building your own plugins,
you’ll want to keep federation in mind.
federation is the ability to define several
different packages, each targeted at a
different set of platforms, brought together
into a single plugin for ease of use by developers.
for example, the windows implementation of the
url_launcher is really url_launcher_windows,
but a flutter developer can simply add the
url_launcher package to their pubspec.yaml
as a dependency and the build process pulls in
the correct implementation based on the target platform.
federation is handy because different teams with
different expertise can build plugin implementations
for different platforms.
you can add a new platform implementation to any
endorsed federated plugin on pub.dev,
so long as you coordinate this effort with the
original plugin author.
for more information, including information
about endorsed plugins, see the following resources:
<topic_end>
<topic_start>
samples and codelabs
you can run the following samples as desktop apps,
as well as download and inspect the source code to
learn more about flutter desktop support.
<topic_end>
<topic_start>
writing custom platform-specific code
this guide describes how to write custom platform-specific code.
some platform-specific functionality is available
through existing packages;
see using packages.
info note
  the information in this page is valid for most platforms,
  but platform-specific code for the web generally uses
  JS interoperability or the dart:html library instead.
flutter uses a flexible system that allows you to call
platform-specific APIs in a language that works directly
with those APIs:
flutter’s builtin platform-specific API support
doesn’t rely on code generation,
but rather on a flexible message passing style.
alternatively, you can use the pigeon
package for sending structured typesafe messages
with code generation:
the flutter portion of the app sends messages to its host,
the non-Dart portion of the app, over a platform channel.
the host listens on the platform channel, and receives the message.
it then calls into any number of platform-specific APIs—using
the native programming language—and sends a response back to the
client, the flutter portion of the app.
info note
  this guide addresses using the platform channel mechanism
  if you need to use the platform’s APIs in a non-Dart language.
  but you can also write platform-specific dart code
  in your flutter app by inspecting the
  defaultTargetPlatform property.
  platform adaptations lists some
  platform-specific adaptations that flutter
  automatically performs for you in the framework.
<topic_end>
<topic_start>
architectural overview: platform channels
messages are passed between the client (ui)
and host (platform) using platform
channels as illustrated in this diagram:
messages and responses are passed asynchronously,
to ensure the user interface remains responsive.
info note
  even though flutter sends messages to and from dart asynchronously,
  whenever you invoke a channel method, you must invoke that method on the
  platform’s main thread. see the section on threading
  for more information.
on the client side, MethodChannel enables sending
messages that correspond to method calls. on the platform side,
MethodChannel on android (methodchannelandroid) and
FlutterMethodChannel on iOS (methodchannelios)
enable receiving method calls and sending back a
result. these classes allow you to develop a platform plugin
with very little ‘boilerplate’ code.
info note
  if desired, method calls can also be sent in the reverse direction,
  with the platform acting as client to methods implemented in dart.
  for a concrete example, check out the quick_actions plugin.
<topic_end>
<topic_start>
platform channel data types support and codecs
the standard platform channels use a standard message codec that supports
efficient binary serialization of simple JSON-like values, such as booleans,
numbers, strings, byte buffers, and lists and maps of these
(see StandardMessageCodec for details).
the serialization and deserialization of these values to and from
messages happens automatically when you send and receive values.
the following table shows how dart values are received on the
platform side and vice versa:
<topic_end>
<topic_start>
example: calling platform-specific code using platform channels
the following code demonstrates how to call
a platform-specific API to retrieve and display
the current battery level.  it uses
the android BatteryManager API,
the iOS device.batteryLevel API,
the windows GetSystemPowerStatus API,
and the linux UPower API with a single
platform message, getBatteryLevel().
the example adds the platform-specific code inside
the main app itself.  if you want to reuse the
platform-specific code for multiple apps,
the project creation step is slightly different
(see developing packages),
but the platform channel code
is still written in the same way.
info note
  the full, runnable source-code for this example is
  available in /examples/platform_channel/
  for android with java, iOS with Objective-C,
  windows with c++, and linux with c.
  for iOS with swift,
  see /examples/platform_channel_swift/.
<topic_end>
<topic_start>
step 1: create a new app project
start by creating a new app:
by default, our template supports writing android code using kotlin,
or iOS code using swift. to use java or Objective-C,
use the -i and/or -a flags:
<topic_end>
<topic_start>
step 2: create the flutter platform client
the app’s state class holds the current app state.
extend that to hold the current battery state.
first, construct the channel. use a MethodChannel with a single
platform method that returns the battery level.
the client and host sides of a channel are connected through
a channel name passed in the channel constructor.
all channel names used in a single app must
be unique; prefix the channel name with a unique ‘domain
prefix’, for example: samples.flutter.dev/battery.
<code_start>
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
<code_end>
<code_start>
class _MyHomePageState extends State<MyHomePage> {
  static const platform = MethodChannel('samples.flutter.dev/battery');
  // get battery level.
<code_end>
next, invoke a method on the method channel,
specifying the concrete method to call using
the string identifier getBatteryLevel.
the call might fail—for example,
if the platform doesn’t support the
platform API (such as when running in a simulator),
so wrap the invokeMethod call in a try-catch statement.
use the returned result to update the user interface state in _batteryLevel
inside setState.
<code_start>
// get battery level.
string _batteryLevel = 'unknown battery level.';
future<void> _getBatteryLevel() async {
  string batteryLevel;
  try {
    final result = await platform.invokeMethod<int>('getBatteryLevel');
    batteryLevel = 'battery level at $result % .';
  } on PlatformException catch (e) {
    batteryLevel = "failed to get battery level: '${e.message}'.";
  }
  setState(() {
    _batteryLevel = batteryLevel;
  });
}
<code_end>
finally, replace the build method from the template to
contain a small user interface that displays the battery
state in a string, and a button for refreshing the value.
<code_start>
@override
widget build(BuildContext context) {
  return material(
    child: center(
      child: column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          ElevatedButton(
            onPressed: _getBatteryLevel,
            child: const Text('Get battery level'),
          ),
          Text(_batteryLevel),
        ],
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
step 3: add an android platform-specific implementation
start by opening the android host portion of your flutter app
in android studio:
start android studio
select the menu item file > open…
navigate to the directory holding your flutter app,
and select the android folder inside it. click OK.
open the file MainActivity.kt located in the kotlin folder in the
project view.
inside the configureFlutterEngine() method, create a MethodChannel and call
setMethodCallHandler(). make sure to use the same channel name as
was used on the flutter client side.
<code_start>
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
  private val CHANNEL = "samples.flutter.dev/battery"
  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
      call, result ->
      // this method is invoked on the main thread.
      // TODO
    }
  }
}
<code_end>
add the android kotlin code that uses the android battery APIs to
retrieve the battery level. this code is exactly the same as you
would write in a native android app.
first, add the needed imports at the top of the file:
<code_start>
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
<code_end>
next, add the following method in the MainActivity class,
below the configureFlutterEngine() method:
<code_start>
private fun getBatteryLevel(): int {
  val batteryLevel: int
  if (version.sdk_int >= VERSION_CODES.LOLLIPOP) {
    val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
    batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
  } else {
    val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
    batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
  }
  return batteryLevel
}
<code_end>
finally, complete the setMethodCallHandler() method added earlier.
you need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument.
the implementation of this platform method calls the
android code written in the previous step, and returns a response for both
the success and error cases using the result argument.
if an unknown method is called, report that instead.
remove the following code:
<code_start>
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
  call, result ->
  // this method is invoked on the main thread.
  // TODO
}
<code_end>
and replace with the following:
<code_start>
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
  // this method is invoked on the main thread.
  call, result ->
  if (call.method == "getbatterylevel") {
    val batteryLevel = getBatteryLevel()
    if (batterylevel != -1) {
      result.success(batteryLevel)
    } else {
      result.error("UNAVAILABLE", "battery level not available.", null)
    }
  } else {
    result.notImplemented()
  }
}
<code_end>
start by opening the android host portion of your flutter app
in android studio:
start android studio
select the menu item file > open…
navigate to the directory holding your flutter app,
and select the android folder inside it. click OK.
open the MainActivity.java file located in the java folder in the
project view.
next, create a MethodChannel and set a MethodCallHandler
inside the configureFlutterEngine() method.
make sure to use the same channel name as was used on the
flutter client side.
<code_start>
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
  private static final string CHANNEL = "samples.flutter.dev/battery";
  @override
  public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
  super.configureFlutterEngine(flutterEngine);
    new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
        .setmethodcallhandler(
          (call, result) -> {
            // this method is invoked on the main thread.
            // TODO
          }
        );
  }
}
<code_end>
add the android java code that uses the android battery APIs to
retrieve the battery level. this code is exactly the same as you
would write in a native android app.
first, add the needed imports at the top of the file:
<code_start>
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
<code_end>
then add the following as a new method in the activity class,
below the configureFlutterEngine() method:
<code_start>
private int getBatteryLevel() {
  int batteryLevel = -1;
  if (version.sdk_int >= VERSION_CODES.LOLLIPOP) {
    BatteryManager batteryManager = (batterymanager) getSystemService(BATTERY_SERVICE);
    batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
  } else {
    intent intent = new ContextWrapper(getApplicationContext()).
        registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    batteryLevel = (intent.getintextra(batterymanager.extra_level, -1) * 100) /
        intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
  }
  return batteryLevel;
}
<code_end>
finally, complete the setMethodCallHandler() method added earlier.
you need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument. the implementation of
this platform method calls the android code written
in the previous step, and returns a response for both
the success and error cases using the result argument.
if an unknown method is called, report that instead.
remove the following code:
<code_start>
(call, result) -> {
  // this method is invoked on the main thread.
  // TODO
}
<code_end>
and replace with the following:
<code_start>
(call, result) -> {
  // this method is invoked on the main thread.
  if (call.method.equals("getbatterylevel")) {
    int batteryLevel = getBatteryLevel();
    if (batterylevel != -1) {
      result.success(batteryLevel);
    } else {
      result.error("UNAVAILABLE", "battery level not available.", null);
    }
  } else {
    result.notImplemented();
  }
}
<code_end>
you should now be able to run the app on android. if using the android
emulator, set the battery level in the extended controls panel
accessible from the … button in the toolbar.
<topic_end>
<topic_start>
step 4: add an iOS platform-specific implementation
start by opening the iOS host portion of your flutter app in xcode:
start xcode.
select the menu item file > open….
navigate to the directory holding your flutter app, and select the ios
folder inside it. click OK.
add support for swift in the standard template setup that uses Objective-C:
expand runner > runner in the project navigator.
open the file AppDelegate.swift located under runner > runner
in the project navigator.
override the application:didFinishLaunchingWithOptions: function and create
a FlutterMethodChannel tied to the channel name
samples.flutter.dev/battery:
<code_start>
@uiapplicationmain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [uiapplication.launchoptionskey: any]?) -> bool {
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",
                                              binaryMessenger: controller.binaryMessenger)
    batteryChannel.setMethodCallHandler({
      (call: FlutterMethodCall, result: @escaping FlutterResult) -> void in
      // this method is invoked on the UI thread.
      // handle battery messages.
    })
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
<code_end>
next, add the iOS swift code that uses the iOS battery APIs to retrieve
the battery level. this code is exactly the same as you
would write in a native iOS app.
add the following as a new method at the bottom of AppDelegate.swift:
<code_start>
private func receiveBatteryLevel(result: FlutterResult) {
  let device = UIDevice.current
  device.isBatteryMonitoringEnabled = true
  if device.batteryState == UIDevice.BatteryState.unknown {
    result(FlutterError(code: "unavailable",
                        message: "battery level not available.",
                        details: nil))
  } else {
    result(Int(device.batteryLevel * 100))
  }
}
<code_end>
finally, complete the setMethodCallHandler() method added earlier.
you need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument.
the implementation of this platform method calls
the iOS code written in the previous step. if an unknown method
is called, report that instead.
<code_start>
batteryChannel.setMethodCallHandler({
  [weak self] (call: FlutterMethodCall, result: FlutterResult) -> void in
  // this method is invoked on the UI thread.
  guard call.method == "getbatterylevel" else {
    result(FlutterMethodNotImplemented)
    return
  }
  self?.receiveBatteryLevel(result: result)
})
<code_end>
start by opening the iOS host portion of the flutter app in xcode:
start xcode.
select the menu item file > open….
navigate to the directory holding your flutter app,
and select the ios folder inside it. click OK.
make sure the xcode projects builds without errors.
open the file AppDelegate.m, located under runner > runner
in the project navigator.
create a FlutterMethodChannel and add a handler inside the application
didFinishLaunchingWithOptions: method.
make sure to use the same channel name
as was used on the flutter client side.
<code_start>
#import <flutter/flutter.h>
#import "generatedpluginregistrant.h"
@implementation AppDelegate
- (bool)application:(uiapplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  FlutterViewController* controller = (flutterviewcontroller*)self.window.rootviewcontroller;
  FlutterMethodChannel* batteryChannel = [fluttermethodchannel
                                          methodChannelWithName:@"samples.flutter.dev/battery"
                                          binaryMessenger:controller.binaryMessenger];
  [batterychannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
    // this method is invoked on the UI thread.
    // TODO
  }];
  [generatedpluginregistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
<code_end>
next, add the iOS ObjectiveC code that uses the iOS battery APIs to
retrieve the battery level. this code is exactly the same as you
would write in a native iOS app.
add the following method in the AppDelegate class, just before @end:
<code_start>
- (int)getbatterylevel {
  UIDevice* device = UIDevice.currentDevice;
  device.batteryMonitoringEnabled = YES;
  if (device.batterystate == UIDeviceBatteryStateUnknown) {
    return -1;
  } else {
    return (int)(device.batterylevel * 100);
  }
}
<code_end>
finally, complete the setMethodCallHandler() method added earlier.
you need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument. the implementation of
this platform method calls the iOS code written in the previous step,
and returns a response for both the success and error cases using
the result argument. if an unknown method is called, report that instead.
<code_start>
__weak typeof(self) weakSelf = self;
[batterychannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
  // this method is invoked on the UI thread.
  if ([@"getbatterylevel" isEqualToString:call.method]) {
    int batteryLevel = [weakself getBatteryLevel];
    if (batterylevel == -1) {
      result([FlutterError errorWithCode:@"UNAVAILABLE"
                                 message:@"Battery level not available."
                                 details:nil]);
    } else {
      result(@(batteryLevel));
    }
  } else {
    result(FlutterMethodNotImplemented);
  }
}];
<code_end>
you should now be able to run the app on iOS.
if using the iOS simulator,
note that it doesn’t support battery APIs,
and the app displays ‘battery level not available’.
<topic_end>
<topic_start>
step 5: add a windows platform-specific implementation
start by opening the windows host portion of your flutter app in visual studio:
run flutter build windows in your project directory once to generate
the visual studio solution file.
start visual studio.
select open a project or solution.
navigate to the directory holding your flutter app, then into the build
folder, then the windows folder, then select the batterylevel.sln file.
click open.
add the c++ implementation of the platform channel method:
expand batterylevel > source files in the solution explorer.
open the file flutter_window.cpp.
first, add the necessary includes to the top of the file, just
after #include "flutter_window.h":
<code_start>
#include <flutter/event_channel.h>
#include <flutter/event_sink.h>
#include <flutter/event_stream_handler_functions.h>
#include <flutter/method_channel.h>
#include <flutter/standard_method_codec.h>
#include <windows.h>
#include <memory>
<code_end>
edit the FlutterWindow::OnCreate method and create
a flutter::MethodChannel tied to the channel name
samples.flutter.dev/battery:
<code_start>
bool FlutterWindow::OnCreate() {
  // ...
  RegisterPlugins(flutter_controller_->engine());
  flutter::MethodChannel<> channel(
      flutter_controller_->engine()->messenger(), "samples.flutter.dev/battery",
      &flutter::standardmethodcodec::getinstance());
  channel.SetMethodCallHandler(
      [](const flutter::MethodCall<>& call,
         std::unique_ptr<flutter::MethodResult<>> result) {
        // TODO
      });
  SetChildContent(flutter_controller_->view()->GetNativeWindow());
  return true;
}
<code_end>
next, add the c++ code that uses the windows battery APIs to
retrieve the battery level. this code is exactly the same as
you would write in a native windows application.
add the following as a new function at the top of
flutter_window.cpp just after the #include section:
<code_start>
static int GetBatteryLevel() {
  SYSTEM_POWER_STATUS status;
  if (getsystempowerstatus(&status) == 0 || status.BatteryLifePercent == 255) {
    return -1;
  }
  return status.BatteryLifePercent;
}
<code_end>
finally, complete the setMethodCallHandler() method added earlier.
you need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument.
the implementation of this platform method calls
the windows code written in the previous step. if an unknown method
is called, report that instead.
remove the following code:
<code_start>
channel.SetMethodCallHandler(
    [](const flutter::MethodCall<>& call,
       std::unique_ptr<flutter::MethodResult<>> result) {
      // TODO
    });
<code_end>
and replace with the following:
<code_start>
channel.SetMethodCallHandler(
    [](const flutter::MethodCall<>& call,
       std::unique_ptr<flutter::MethodResult<>> result) {
      if (call.method_name() == "getbatterylevel") {
        int battery_level = GetBatteryLevel();
        if (battery_level != -1) {
          result->Success(battery_level);
        } else {
          result->Error("UNAVAILABLE", "battery level not available.");
        }
      } else {
        result->NotImplemented();
      }
    });
<code_end>
you should now be able to run the application on windows.
if your device doesn’t have a battery,
it displays ‘battery level not available’.
<topic_end>
<topic_start>
step 6: add a macOS platform-specific implementation
start by opening the macOS host portion of your flutter app in xcode:
start xcode.
select the menu item file > open….
navigate to the directory holding your flutter app, and select the macos
folder inside it. click OK.
add the swift implementation of the platform channel method:
expand runner > runner in the project navigator.
open the file MainFlutterWindow.swift located under runner > runner
in the project navigator.
first, add the necessary import to the top of the file, just after
import FlutterMacOS:
<code_start>
import IOKit.ps
<code_end>
create a FlutterMethodChannel tied to the channel name
samples.flutter.dev/battery in the awakeFromNib method:
<code_start>
  override func awakeFromNib() {
    // ...
    self.setFrame(windowFrame, display: true)
    let batteryChannel = FlutterMethodChannel(
      name: "samples.flutter.dev/battery",
      binaryMessenger: flutterViewController.engine.binaryMessenger)
    batteryChannel.setMethodCallHandler { (call, result) in
      // this method is invoked on the UI thread.
      // handle battery messages.
    }
    RegisterGeneratedPlugins(registry: flutterViewController)
    super.awakeFromNib()
  }
}
<code_end>
next, add the macOS swift code that uses the IOKit battery APIs to retrieve
the battery level. this code is exactly the same as you
would write in a native macOS app.
add the following as a new method at the bottom of MainFlutterWindow.swift:
<code_start>
private func getBatteryLevel() -> int? {
  let info = IOPSCopyPowerSourcesInfo().takeRetainedValue()
  let sources: Array<CFTypeRef> = IOPSCopyPowerSourcesList(info).takeRetainedValue() as array
  if let source = sources.first {
    let description =
      IOPSGetPowerSourceDescription(info, source).takeUnretainedValue() as! [string: AnyObject]
    if let level = description[kIOPSCurrentCapacityKey] as? int {
      return level
    }
  }
  return nil
}
<code_end>
finally, complete the setMethodCallHandler method added earlier.
you need to handle a single platform method, getBatteryLevel(),
so test for that in the call argument.
the implementation of this platform method calls
the macOS code written in the previous step. if an unknown method
is called, report that instead.
<code_start>
batteryChannel.setMethodCallHandler { (call, result) in
  switch call.method {
  case "getbatterylevel":
    guard let level = getBatteryLevel() else {
      result(
        FlutterError(
          code: "unavailable",
          message: "battery level not available",
          details: nil))
     return
    }
    result(level)
  default:
    result(FlutterMethodNotImplemented)
  }
}
<code_end>
you should now be able to run the application on macOS.
if your device doesn’t have a battery,
it displays ‘battery level not available’.
<topic_end>
<topic_start>
step 7: add a linux platform-specific implementation
for this example you need to install the upower developer headers.
this is likely available from your distribution, for example with:
start by opening the linux host portion of your flutter app in the editor
of your choice. the instructions below are for visual studio code with the
“c/c++” and “cmake” extensions installed, but can be adjusted for other IDEs.
launch visual studio code.
open the linux directory inside your project.
choose yes in the prompt asking: would you like to configure project "linux"?.
this enables c++ autocomplete.
open the file my_application.cc.
first, add the necessary includes to the top of the file, just
after #include <flutter_linux/flutter_linux.h:
<code_start>
#include <math.h>
#include <upower.h>
<code_end>
add an FlMethodChannel to the _MyApplication struct:
<code_start>
struct _MyApplication {
  GtkApplication parent_instance;
  char** dart_entrypoint_arguments;
  FlMethodChannel* battery_channel;
};
<code_end>
make sure to clean it up in my_application_dispose:
<code_start>
static void my_application_dispose(GObject* object) {
  MyApplication* self = MY_APPLICATION(object);
  g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
  g_clear_object(&self->battery_channel);
  G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
<code_end>
edit the my_application_activate method and initialize
battery_channel using the channel name
samples.flutter.dev/battery, just after the call to
fl_register_plugins:
<code_start>
static void my_application_activate(GApplication* application) {
  // ...
  fl_register_plugins(FL_PLUGIN_REGISTRY(self->view));
  g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
  self->battery_channel = fl_method_channel_new(
      fl_engine_get_binary_messenger(fl_view_get_engine(view)),
      "samples.flutter.dev/battery", FL_METHOD_CODEC(codec));
  fl_method_channel_set_method_call_handler(
      self->battery_channel, battery_method_call_handler, self, nullptr);
  gtk_widget_grab_focus(GTK_WIDGET(self->view));
}
<code_end>
next, add the c code that uses the linux battery APIs to
retrieve the battery level. this code is exactly the same as
you would write in a native linux application.
add the following as a new function at the top of
my_application.cc just after the G_DEFINE_TYPE line:
<code_start>
static FlMethodResponse* get_battery_level() {
  // find the first available battery and report that.
  g_autoptr(UpClient) up_client = up_client_new();
  g_autoptr(GPtrArray) devices = up_client_get_devices2(up_client);
  if (devices->len == 0) {
    return FL_METHOD_RESPONSE(fl_method_error_response_new(
        "unavailable", "device does not have a battery.", nullptr));
  }
  UpDevice* device = (updevice*)(g_ptr_array_index(devices, 0));
  double percentage = 0;
  g_object_get(device, "percentage", &percentage, nullptr);
  g_autoptr(FlValue) result =
      fl_value_new_int(static_cast<int64_t>(round(percentage)));
  return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
}
<code_end>
finally, add the battery_method_call_handler function referenced
in the earlier call to fl_method_channel_set_method_call_handler.
you need to handle a single platform method, getBatteryLevel,
so test for that in the method_call argument.
the implementation of this function calls
the linux code written in the previous step. if an unknown method
is called, report that instead.
add the following code after the get_battery_level function:
<code_start>
static void battery_method_call_handler(FlMethodChannel* channel,
                                        FlMethodCall* method_call,
                                        gpointer user_data) {
  g_autoptr(FlMethodResponse) response = nullptr;
  if (strcmp(fl_method_call_get_name(method_call), "getbatterylevel") == 0) {
    response = get_battery_level();
  } else {
    response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
  }
  g_autoptr(GError) error = nullptr;
  if (!fl_method_call_respond(method_call, response, &error)) {
    g_warning("Failed to send response: %s", error->message);
  }
}
<code_end>
you should now be able to run the application on linux.
if your device doesn’t have a battery,
it displays ‘battery level not available’.
<topic_end>
<topic_start>
typesafe platform channels using pigeon
the previous example uses MethodChannel
to communicate between the host and client,
which isn’t typesafe. calling and receiving
messages depends on the host and client declaring
the same arguments and datatypes in order for messages to work.
you can use the pigeon package as
an alternative to MethodChannel
to generate code that sends messages in a
structured, typesafe manner.
with pigeon, the messaging protocol is defined
in a subset of dart that then generates messaging
code for android, iOS, macOS, or windows. you can find a more complete
example and more information on the pigeon
page on pub.dev.
using pigeon eliminates the need to match
strings between host and client
for the names and datatypes of messages.
it supports: nested classes, grouping
messages into APIs, generation of
asynchronous wrapper code and sending messages
in either direction. the generated code is readable
and guarantees there are no conflicts between
multiple clients of different versions.
supported languages are Objective-C, java, kotlin, c++,
and swift (with Objective-C interop).
<topic_end>
<topic_start>
pigeon example
pigeon file:
<code_start>
import 'package:pigeon/pigeon.dart';
class SearchRequest {
  final string query;
  SearchRequest({required this.query});
}
class SearchReply {
  final string result;
  SearchReply({required this.result});
}
@hostapi()
abstract class api {
  @async
  SearchReply search(SearchRequest request);
}
<code_end>
dart usage:
<code_start>
import 'generated_pigeon.dart';
future<void> onClick() async {
  SearchRequest request = SearchRequest(query: 'test');
  api api = SomeApi();
  SearchReply reply = await api.search(request);
  print('reply: ${reply.result}');
}
<code_end>
<topic_end>
<topic_start>
separate platform-specific code from UI code
if you expect to use your platform-specific code
in multiple flutter apps, you might consider
separating the code into a platform plugin located
in a directory outside your main application.
see developing packages for details.
<topic_end>
<topic_start>
publish platform-specific code as a package
to share your platform-specific code with other developers
in the flutter ecosystem, see publishing packages.
<topic_end>
<topic_start>
custom channels and codecs
besides the above mentioned MethodChannel,
you can also use the more basic
BasicMessageChannel, which supports basic,
asynchronous message passing using a custom message codec.
you can also use the specialized BinaryCodec,
StringCodec, and JSONMessageCodec
classes, or create your own codec.
you might also check out an example of a custom codec
in the cloud_firestore plugin,
which is able to serialize and deserialize many more
types than the default types.
<topic_end>
<topic_start>
channels and platform threading
when invoking channels on the platform side destined for flutter,
invoke them on the platform’s main thread.
when invoking channels in flutter destined for the platform side,
either invoke them from any isolate that is the root
isolate, or that is registered as a background isolate.
the handlers for the platform side can execute on the platform’s main thread
or they can execute on a background thread if using a task queue.
you can invoke the platform side handlers asynchronously
and on any thread.
info note
  on android, the platform’s main thread is sometimes
  called the “main thread”, but it is technically defined
  as the UI thread. annotate methods that need
  to be run on the UI thread with @uithread.
  on iOS, this thread is officially
  referred to as the main thread.
<topic_end>
<topic_start>
using plugins and channels from background isolates
plugins and channels can be used by any isolate, but that isolate has to be
a root isolate (the one created by flutter) or registered as a background
isolate for a root isolate.
the following example shows how to register a background isolate in order to
use a plugin from a background isolate.
<topic_end>
<topic_start>
executing channel handlers on background threads
in order for a channel’s platform side handler to
execute on a background thread, you must use the
task queue API. currently this feature is only
supported on iOS and android.
in java:
in kotlin:
in swift:
info note
  in release 2.10, the task queue API is only available on the master channel
  for iOS.
in Objective-C:
info note
  in release 2.10, the task queue API is only available on the master channel
  for iOS.
<topic_end>
<topic_start>
jumping to the UI thread in android
to comply with channels’ UI thread requirement,
you might need to jump from a background thread
to android’s UI thread to execute a channel method.
in android, you can accomplish this by post()ing a
runnable to android’s UI thread looper,
which causes the runnable to execute on the
main thread at the next opportunity.
in java:
in kotlin:
<topic_end>
<topic_start>
jumping to the main thread in iOS
to comply with channel’s main thread requirement,
you might need to jump from a background thread to
iOS’s main thread to execute a channel method.
you can accomplish this in iOS by executing a
block on the main dispatch queue:
in Objective-C:
in swift:
<topic_end>
<topic_start>
automatic platform adaptations
info note
  as of the flutter 3.16 release, material 3
  replaces material 2 as the default theme
  on all flutter apps that use material.
<topic_end>
<topic_start>
adaptation philosophy
in general, two cases of platform adaptiveness exist:
this article mainly covers the automatic adaptations
provided by flutter in case 1 on android and iOS.
for case 2, flutter bundles the means to produce the
appropriate effects of the platform conventions but doesn’t
adapt automatically when app design choices are needed.
for a discussion, see issue #8410 and the
Material/Cupertino adaptive widget problem definition.
for an example of an app using different information
architecture structures on android and iOS but sharing
the same content code, see the platform_design code samples.
info
preliminary guides addressing case 2 
are being added to the UI components section. 
you can request additional guides by commenting on issue #8427.
<topic_end>
<topic_start>
page navigation
flutter provides the navigation patterns seen on android
and iOS and also automatically adapts the navigation animation
to the current platform.
<topic_end>
<topic_start>
navigation transitions
on android, the default navigator.push() transition
is modeled after startActivity(),
which generally has one bottom-up animation variant.
on iOS:
<topic_end>
<topic_start>
platform-specific transition details
on android, flutter uses the ZoomPageTransitionsBuilder animation.
when the user taps on an item, the UI zooms in to a screen that features that item.
when the user taps to go back, the UI zooms out to the previous screen.
on iOS when the push style transition is used,
flutter’s bundled CupertinoNavigationBar
and CupertinoSliverNavigationBar nav bars
automatically animate each subcomponent to its corresponding
subcomponent on the next or previous page’s
CupertinoNavigationBar or CupertinoSliverNavigationBar.
<topic_end>
<topic_start>
back navigation
on android,
the OS back button, by default, is sent to flutter
and pops the top route of the WidgetsApp’s navigator.
on iOS,
an edge swipe gesture can be used to pop the top route.
<topic_end>
<topic_start>
scrolling
scrolling is an important part of the platform’s
look and feel, and flutter automatically adjusts
the scrolling behavior to match the current platform.
<topic_end>
<topic_start>
physics simulation
android and iOS both have complex scrolling physics
simulations that are difficult to describe verbally.
generally, iOS’s scrollable has more weight and
dynamic friction but android has more static friction.
therefore iOS gains high speed more gradually but stops
less abruptly and is more slippery at slow speeds.
<topic_end>
<topic_start>
overscroll behavior
on android,
scrolling past the edge of a scrollable shows an
overscroll glow indicator (based on the color
of the current material theme).
on iOS, scrolling past the edge of a scrollable
overscrolls with increasing resistance and snaps back.
<topic_end>
<topic_start>
momentum
on iOS,
repeated flings in the same direction stacks momentum
and builds more speed with each successive fling.
there is no equivalent behavior on android.
<topic_end>
<topic_start>
return to top
on iOS,
tapping the OS status bar scrolls the primary
scroll controller to the top position.
there is no equivalent behavior on android.
<topic_end>
<topic_start>
typography
when using the material package,
the typography automatically defaults to the
font family appropriate for the platform.
android uses the roboto font.
iOS uses the san francisco font.
when using the cupertino package, the default theme
uses the san francisco font.
the san francisco font license limits its usage to
software running on iOS, macOS, or tvOS only.
therefore a fallback font is used when running on android
if the platform is debug-overridden to iOS or the
default cupertino theme is used.
you might choose to adapt the text styling of material 
widgets to match the default text styling on iOS. 
you can see widget-specific examples in the 
UI component section.
<topic_end>
<topic_start>
iconography
when using the material package,
certain icons automatically show different
graphics depending on the platform.
for instance, the overflow button’s three dots
are horizontal on iOS and vertical on android.
the back button is a simple chevron on iOS and
has a stem/shaft on android.
the material library also provides a set of platform-adaptive icons through icons.adaptive.
<topic_end>
<topic_start>
haptic feedback
the material and cupertino packages automatically
trigger the platform appropriate haptic feedback in
certain scenarios.
for instance,
a word selection via text field long-press triggers a ‘buzz’
vibrate on android and not on iOS.
scrolling through picker items on iOS triggers a
‘light impact’ knock and no feedback on android.
<topic_end>
<topic_start>
text editing
flutter also makes the below adaptations while editing
the content of text fields to match the current platform.
<topic_end>
<topic_start>
keyboard gesture navigation
on android,
horizontal swipes can be made on the soft keyboard’s space key
to move the cursor in material and cupertino text fields.
on iOS devices with 3d touch capabilities,
a force-press-drag gesture could be made on the soft
keyboard to move the cursor in 2d via a floating cursor.
this works on both material and cupertino text fields.
<topic_end>
<topic_start>
text selection toolbar
with material on android,
the android style selection toolbar is shown when
a text selection is made in a text field.
with material on iOS or when using cupertino,
the iOS style selection toolbar is shown when a text
selection is made in a text field.
<topic_end>
<topic_start>
single tap gesture
with material on android,
a single tap in a text field puts the cursor at the
location of the tap.
a collapsed text selection also shows a draggable
handle to subsequently move the cursor.
with material on iOS or when using cupertino,
a single tap in a text field puts the cursor at the
nearest edge of the word tapped.
collapsed text selections don’t have draggable handles on iOS.
<topic_end>
<topic_start>
long-press gesture
with material on android,
a long press selects the word under the long press.
the selection toolbar is shown upon release.
with material on iOS or when using cupertino,
a long press places the cursor at the location of the
long press. the selection toolbar is shown upon release.
<topic_end>
<topic_start>
long-press drag gesture
with material on android,
dragging while holding the long press expands the words selected.
with material on iOS or when using cupertino,
dragging while holding the long press moves the cursor.
<topic_end>
<topic_start>
double tap gesture
on both android and iOS,
a double tap selects the word receiving the
double tap and shows the selection toolbar.
<topic_end>
<topic_start>
UI components
this section includes preliminary recommendations on how to adapt 
material widgets to deliver a natural and compelling experience on iOS. 
your feedback is welcomed on issue #8427.
<topic_end>
<topic_start>
widgets with .adaptive() constructors
several widgets support .adaptive() constructors. 
the following table lists these widgets.
adaptive constructors substitute the corresponding cupertino components 
when the app is run on an iOS device.
widgets in the following table are used primarily for input, 
selection, and to display system information. 
because these controls are tightly integrated with the operating system,
users have been trained to recognize and respond to them.
therefore, we recommend that you follow platform conventions.
<topic_end>
<topic_start>
top app bar and navigation bar
since android 12, the default UI for top app 
bars follows the design guidelines defined in material 3. 
on iOS, an equivalent component called “navigation bars” 
is defined in apple’s human interface guidelines (hig).
certain properties of app bars in flutter apps should be adapted, 
like system icons and page transitions. 
these are already automatically adapted when using 
the material AppBar and SliverAppBar widgets. 
you can also further customize the properties of these widgets to better 
match iOS platform styles, as shown below.
but, because app bars are displayed alongside 
other content in your page, it’s only recommended to adapt the styling 
so long as its cohesive with the rest of your application. you can see 
additional code samples and a further explanation in 
the GitHub discussion on app bar adaptations.
<topic_end>
<topic_start>
bottom navigation bars
since android 12, the default UI for bottom navigation 
bars follow the design guidelines defined in material 3. 
on iOS, an equivalent component called “tab bars” 
is defined in apple’s human interface guidelines (hig).
since tab bars are persistent across your app, they should match your
own branding. however, if you choose to use material’s default 
styling on android, you might consider adapting to the default iOS
tab bars.
to implement platform-specific bottom navigation bars, 
you can use flutter’s NavigationBar widget on android 
and the CupertinoTabBar widget on iOS. 
below is a code snippet you can 
adapt to show a platform-specific navigation bars.
<topic_end>
<topic_start>
text fields
since android 12, text fields follow the
material 3 (m3) design guidelines. 
on iOS, apple’s human interface guidelines (hig) define
an equivalent component.
since text fields require user input,
their design should follow platform conventions.
to implement a platform-specific TextField 
in flutter, you can adapt the styling of the 
material TextField.
to learn more about adapting text fields, check out 
the GitHub discussion on text fields.
you can leave feedback or ask questions in the discussion.
<topic_end>
<topic_start>
alert dialog
since android 12, the default UI of alert dialogs 
(also known as a “basic dialog”) follows the design guidelines 
defined in material 3 (m3). 
on iOS, an equivalent component called “alert” is defined in apple’s 
human interface guidelines (hig).
since alert dialogs are often tightly integrated with the operating system, 
their design generally needs to follow the platform conventions. 
this is especially important when a dialog is used to request user input 
about security, privacy, and destructive operations (e.g., deleting files 
permanently). as an exception, a branded alert dialog design can be used on 
non-critical user flows to highlight specific information or messages.
to implement platform-specific alert dialogs, 
you can use flutter’s AlertDialog widget on android 
and the CupertinoAlertDialog widget on iOS. below is a code snippet you can 
adapt to show a platform-specific alert dialog.
to learn more about adapting alert dialogs, check out 
the GitHub discussion on dialog adaptations.
you can leave feedback or ask questions in the discussion.
<topic_end>
<topic_start>
android
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
add android devtools for flutter
to choose the guide to add android studio to your flutter configuration,
click the getting started path you followed.
<topic_end>
<topic_start>
adding a splash screen to your android app
splash screens (also known as launch screens) provide 
a simple initial experience while your android app loads. 
they set the stage for your application, 
while allowing time for the app engine 
to load and your app to initialize.
<topic_end>
<topic_start>
overview
warning warning
  if you are experiencing a crash from implementing a splash screen, you
  might need to migrate your code. see detailed instructions in the
  deprecated splash screen API migration guide.
in android, there are two separate screens that you can control:
a launch screen shown while your android app initializes,
and a splash screen that displays while the flutter experience
initializes.
info note
  as of flutter 2.5, the launch and splash screens have been
  consolidated—Flutter now only implements the android launch screen,
  which is displayed until the framework draws the first frame.
  this launch screen can act as both an android launch screen and an
  android splash screen via customization, and thus, is referred to
  as both terms. for example of such customization, check out the
  android splash screen sample app.
if, prior to 2.5, you used flutter create to create an app,
  and you run the app on 2.5 or later, the app might crash.
  for more info, see the deprecated splash screen API migration guide.
info note
  for apps that embed one or more flutter screens within an
  existing android app, consider
  pre-warming a FlutterEngine and reusing the
  same engine throughout your app to minimize wait
  time associated with initialization of the flutter engine.
<topic_end>
<topic_start>
initializing the app
every android app requires initialization time while the
operating system sets up the app’s process.
android provides the concept of a launch screen to
display a drawable while the app is initializing.
a drawable is an android graphic.
to learn how to add a drawable to your
flutter project in android studio,
check out import drawables into your project
in the android developer documentation.
the default flutter project template includes a definition
of a launch theme and a launch background. you can customize
this by editing styles.xml, where you can define a theme
whose windowBackground is set to the
drawable that should be displayed as the launch screen.
in addition, styles.xml defines a normal theme
to be applied to FlutterActivity after the launch
screen is gone. the normal theme background only shows
for a very brief moment after the splash screen disappears,
and during orientation change and activity restoration.
therefore, it’s recommended that the normal theme use a
solid background color that looks similar to the primary
background color of the flutter UI.
<topic_end>
<topic_start>
set up the FlutterActivity in AndroidManifest.xml
in AndroidManifest.xml, set the theme of
FlutterActivity to the launch theme. then,
add a metadata element to the desired FlutterActivity
to instruct flutter to switch from the launch theme
to the normal theme at the appropriate time.
the android app now displays the desired launch screen
while the app initializes.
<topic_end>
<topic_start>
android 12
to configure your launch screen on android 12,
check out android splash screens.
as of android 12, you must use the new splash screen
API in your styles.xml file.
consider creating an alternate resource file for android 12 and higher.
also make sure that your background image is in line with
the icon guidelines;
check out android splash screens for more details.
make sure that
io.flutter.embedding.android.SplashScreenDrawable is
not set in your manifest, and that provideSplashScreen
is not implemented, as these APIs are deprecated.
doing so causes the android launch screen to fade smoothly
into the flutter when the
app is launched and the app might crash.
some apps might want to continue showing the last frame of
the android launch screen in flutter. for example,
this preserves the illusion of a single frame
while additional loading continues in dart.
to achieve this, the following
android APIs might be helpful:
<code_start>
import android.os.Build;
import android.os.Bundle;
import android.window.SplashScreenView;
import androidx.core.view.WindowCompat;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
    @override
    protected void onCreate(Bundle savedInstanceState) {
        // aligns the flutter view vertically with the window.
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        if (build.version.sdk_int >= Build.VERSION_CODES.S) {
            // disable the android splash screen fade out animation to avoid
            // a flicker before the similar frame is drawn in flutter.
            getSplashScreen()
                .setonexitanimationlistener(
                    (splashscreenview splashScreenView) -> {
                        splashScreenView.remove();
                    });
        }
        super.onCreate(savedInstanceState);
    }
}
<code_end>
<code_start>
import android.os.Build
import android.os.Bundle
import androidx.core.view.WindowCompat
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
  override fun onCreate(savedInstanceState: bundle?) {
    // aligns the flutter view vertically with the window.
    WindowCompat.setDecorFitsSystemWindows(getWindow(), false)
    if (build.version.sdk_int >= Build.VERSION_CODES.S) {
      // disable the android splash screen fade out animation to avoid
      // a flicker before the similar frame is drawn in flutter.
      splashScreen.setOnExitAnimationListener { splashScreenView -> splashScreenView.remove() }
    }
    super.onCreate(savedInstanceState)
  }
}
<code_end>
then, you can reimplement the first frame in flutter
that shows elements of your android launch screen in
the same positions on screen.
for an example of this, check out the
android splash screen sample app.
<topic_end>
<topic_start>
binding to native android code using dart:ffi
flutter mobile and desktop apps can use the
dart:ffi library to call native c APIs.
FFI stands for foreign function interface.
other terms for similar functionality include
native interface and language bindings.
info note
  this page describes using the dart:ffi library
  in android apps. for information on iOS, see
  binding to native iOS code using dart:ffi.
  for information in macOS, see
  binding to native macOS code using dart:ffi.
  this feature is not yet supported for web plugins.
before your library or program can use the FFI library
to bind to native code, you must ensure that the
native code is loaded and its symbols are visible to dart.
this page focuses on compiling, packaging,
and loading android native code within a flutter plugin or app.
this tutorial demonstrates how to bundle C/C++
sources in a flutter plugin and bind to them using
the dart FFI library on both android and iOS.
in this walkthrough, you’ll create a c function
that implements 32-bit addition and then
exposes it through a dart plugin named “native_add”.
<topic_end>
<topic_start>
dynamic vs static linking
a native library can be linked into an app either
dynamically or statically. a statically linked library
is embedded into the app’s executable image,
and is loaded when the app starts.
symbols from a statically linked library can be
loaded using DynamicLibrary.executable or
DynamicLibrary.process.
a dynamically linked library, by contrast, is distributed
in a separate file or folder within the app,
and loaded on-demand. on android, a dynamically
linked library is distributed as a set of .so (elf)
files, one for each architecture.
a dynamically linked library can be loaded into
dart via DynamicLibrary.open.
API documentation is available from the dart dev channel:
dart API reference documentation.
on android, only dynamic libraries are supported
(because the main executable is the JVM,
which we don’t link to statically).
<topic_end>
<topic_start>
create an FFI plugin
to create an FFI plugin called “native_add”,
do the following:
info note
  you can exclude platforms from --platforms that you don’t want
  to build to. however, you need to include the platform of 
  the device you are testing on.
this will create a plugin with C/C++ sources in native_add/src.
these sources are built by the native build files in the various
os build folders.
the FFI library can only bind against c symbols,
so in c++ these symbols are marked extern "c".
you should also add attributes to indicate that the
symbols are referenced from dart,
to prevent the linker from discarding the symbols
during link-time optimization.
__attribute__((visibility("default"))) __attribute__((used)).
on android, the native_add/android/build.gradle links the code.
the native code is invoked from dart in lib/native_add_bindings_generated.dart.
the bindings are generated with package:ffigen.
<topic_end>
<topic_start>
other use cases
<topic_end>
<topic_start>
platform library
to link against a platform library,
use the following instructions:
load the library using DynamicLibrary.open.
for example, to load OpenGL ES (v3):
you might need to update the android manifest
file of the app or plugin if indicated by
the documentation.
<topic_end>
<topic_start>
first-party library
the process for including native code in source
code or binary form is the same for an app or
plugin.
<topic_end>
<topic_start>
open-source third-party
follow the add c and c++ code to your project
instructions in the android docs to
add native code and support for the native
code toolchain (either CMake or ndk-build).
<topic_end>
<topic_start>
closed-source third-party library
to create a flutter plugin that includes dart
source code, but distribute the C/C++ library
in binary form, use the following instructions:
<topic_end>
<topic_start>
android APK size (shared object compression)
android guidelines in general recommend
distributing native shared objects uncompressed
because that actually saves on device space.
shared objects can be directly loaded from the APK
instead of unpacking them on device into a
temporary location and then loading.
APKs are additionally packed in transit—that’s
why you should be looking at download size.
flutter APKs by default don’t follow these guidelines
and compress libflutter.so and libapp.so—this
leads to smaller APK size but larger on device size.
shared objects from third parties can change this default
setting with android:extractNativeLibs="true" in their
AndroidManifest.xml and stop the compression of libflutter.so,
libapp.so, and any user-added shared objects.
to re-enable compression, override the setting in
your_app_name/android/app/src/main/AndroidManifest.xml
in the following way.
<topic_end>
<topic_start>
other resources
to learn more about c interoperability, check out these videos:
<topic_end>
<topic_start>
hosting native android views in your flutter app with platform views
platform views allow you to embed native views in a flutter app,
so you can apply transforms, clips, and opacity to the native view
from dart.
this allows you, for example, to use the native
google maps from the android SDK
directly inside your flutter app.
info note
  this page discusses how to host your own native android views
  within a flutter app.
  if you’d like to embed native iOS views in your flutter app,
  see hosting native iOS views.
flutter supports two modes:
hybrid composition and virtual displays.
which one to use depends on the use case.
let’s take a look:
hybrid composition
appends the native android.view.View to the view hierarchy. 
therefore, keyboard handling, and accessibility work out of the box.
prior to android 10, this mode might significantly
reduce the frame throughput (fps) of the flutter UI.
for more context, see performance.
virtual displays
render the android.view.View instance to a texture, 
so it’s not embedded within the android activity’s view hierarchy.
certain platform interactions such as keyboard handling
and accessibility features might not work.
to create a platform view on android,
use the following steps:
<topic_end>
<topic_start>
on the dart side
on the dart side, create a widget
and add one of the following build implementations.
<topic_end>
<topic_start>
hybrid composition
in your dart file,
for example native_view_example.dart,
use the following instructions:
add the following imports:
<code_start>
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
<code_end>
implement a build() method:
<code_start>
widget build(BuildContext context) {
  // this is used in the platform side to register the view.
  const string viewType = '<platform-view-type>';
  // pass parameters to the platform side.
  const Map<String, dynamic> creationParams = <string, dynamic>{};
  return PlatformViewLink(
    viewType: viewType,
    surfaceFactory: (context, controller) {
      return AndroidViewSurface(
        controller: controller as AndroidViewController,
        gestureRecognizers: const <factory<onesequencegesturerecognizer>>{},
        hitTestBehavior: PlatformViewHitTestBehavior.opaque,
      );
    },
    onCreatePlatformView: (params) {
      return PlatformViewsService.initSurfaceAndroidView(
        id: params.id,
        viewType: viewType,
        layoutDirection: TextDirection.ltr,
        creationParams: creationParams,
        creationParamsCodec: const StandardMessageCodec(),
        onFocus: () {
          params.onFocusChanged(true);
        },
      )
        ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
        ..create();
    },
  );
}
<code_end>
for more information, see the API docs for:
<topic_end>
<topic_start>
virtual display
in your dart file,
for example native_view_example.dart,
use the following instructions:
add the following imports:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
<code_end>
implement a build() method:
<code_start>
widget build(BuildContext context) {
  // this is used in the platform side to register the view.
  const string viewType = '<platform-view-type>';
  // pass parameters to the platform side.
  final Map<String, dynamic> creationParams = <string, dynamic>{};
  return AndroidView(
    viewType: viewType,
    layoutDirection: TextDirection.ltr,
    creationParams: creationParams,
    creationParamsCodec: const StandardMessageCodec(),
  );
}
<code_end>
for more information, see the API docs for:
<topic_end>
<topic_start>
on the platform side
on the platform side, use the standard
io.flutter.plugin.platform package
in either java or kotlin:
in your native code, implement the following:
extend io.flutter.plugin.platform.PlatformView
to provide a reference to the android.view.View
(for example, NativeView.kt):
create a factory class that creates an instance of the
NativeView created earlier
(for example, NativeViewFactory.kt):
finally, register the platform view.
you can do this in an app or a plugin.
for app registration,
modify the app’s main activity
(for example, MainActivity.kt):
for plugin registration,
modify the plugin’s main class
(for example, PlatformViewPlugin.kt):
in your native code, implement the following:
extend io.flutter.plugin.platform.PlatformView
to provide a reference to the android.view.View
(for example, NativeView.java):
create a factory class that creates an
instance of the NativeView created earlier
(for example, NativeViewFactory.java):
finally, register the platform view.
you can do this in an app or a plugin.
for app registration,
modify the app’s main activity
(for example, MainActivity.java):
for plugin registration,
modify the plugin’s main file
(for example, PlatformViewPlugin.java):
for more information, see the API docs for:
finally, modify your build.gradle file
to require one of the minimal android SDK versions:
<topic_end>
<topic_start>
manual view invalidation
certain android views do not invalidate themselves when their content changes.
some example views include SurfaceView and SurfaceTexture.
when your platform view includes these views you are required to
manually invalidate the view after they have been drawn to
(or more specifically: after the swap chain is flipped).
manual view invalidation is done by calling invalidate on the view 
or one of its parent views.
<topic_end>
<topic_start>
performance
platform views in flutter come with performance trade-offs.
for example, in a typical flutter app, the flutter UI is composed
on a dedicated raster thread. this allows flutter apps to be fast,
as the main platform thread is rarely blocked.
while a platform view is rendered with hybrid composition,
the flutter UI is composed from the platform thread,
which competes with other tasks like handling OS or plugin messages.
prior to android 10, hybrid composition copied each flutter frame
out of the graphic memory into main memory, and then copied it back
to a GPU texture. as this copy happens per frame, the performance of
the entire flutter UI might be impacted. in android 10 or above, the
graphics memory is copied only once.
virtual display, on the other hand,
makes each pixel of the native view
flow through additional intermediate graphic buffers,
which cost graphic memory and drawing performance.
for complex cases, there are some techniques that
can be used to mitigate these issues.
for example, you could use a placeholder texture
while an animation is happening in dart.
in other words, if an animation is slow while a
platform view is rendered,
then consider taking a screenshot of the
native view and rendering it as a texture.
for more information, see:
<topic_end>
<topic_start>
restore state on android
when a user runs a mobile app and then selects another
app to run, the first app is moved to the background,
or backgrounded. the operating system (both iOS and android)
might kill the backgrounded app to release memory and
improve performance for the app running in the foreground.
when the user selects the app again, bringing it
back to the foreground, the OS relaunches it.
but, unless you’ve set up a way to save the
state of the app before it was killed,
you’ve lost the state and the app starts from scratch.
the user has lost the continuity they expect,
which is clearly not ideal.
(imagine filling out a lengthy form and being interrupted
by a phone call before clicking submit.)
so, how can you restore the state of the app so that
it looks like it did before it was sent to the
background?
flutter has a solution for this with the
RestorationManager (and related classes)
in the services library.
with the RestorationManager, the flutter framework
provides the state data to the engine as the state
changes, so that the app is ready when the OS signals
that it’s about to kill the app, giving the app only
moments to prepare.
instance state vs long-lived state
  when should you use the RestorationManager and
  when should you save state to long term storage?
  instance state
  (also called short-term or ephemeral state),
  includes unsubmitted form field values, the currently
  selected tab, and so on. on android, this is
  limited to 1 MB and, if the app exceeds this,
  it crashes with a TransactionTooLargeException
  error in the native code.
<topic_end>
<topic_start>
overview
you can enable state restoration with just a few tasks:
define a restorationId or a restorationScopeId
for all widgets that support it,
such as TextField and ScrollView.
this automatically enables built-in state restoration
for those widgets.
for custom widgets,
you must decide what state you want to restore
and hold that state in a RestorableProperty.
(the flutter API provides various subclasses for
different data types.)
define those RestorableProperty widgets 
in a state class that uses the RestorationMixin.
register those widgets with the mixin in a
restoreState method.
if you use any navigator API (like push, pushNamed, and so on)
migrate to the API that has “restorable” in the name
(restorablepush, resstorablePushNamed, and so on)
to restore the navigation stack.
other considerations:
providing a restorationId to
MaterialApp, CupertinoApp, or WidgetsApp
automatically enables state restoration by
injecting a RootRestorationScope.
if you need to restore state above the app class,
inject a RootRestorationScope manually.
the difference between a restorationId and
a restorationScopeId: widgets that take a
restorationScopeID create a new restorationScope
(a new RestorationBucket) into which all children
store their state. a restorationId means the widget
(and its children) store the data in the surrounding bucket.
<topic_end>
<topic_start>
restoring navigation state
if you want your app to return to a particular route
that the user was most recently viewing
(the shopping cart, for example), then you must implement
restoration state for navigation, as well.
if you use the navigator API directly,
migrate the standard methods to restorable
methods (that have “restorable” in the name).
for example, replace push with restorablePush.
the VeggieSeasons example (listed under “other resources” below)
implements navigation with the go_router package.
setting the restorationId
values occur in the lib/screens classes.
<topic_end>
<topic_start>
testing state restoration
to test state restoration, set up your mobile device so that
it doesn’t save state once an app is backgrounded.
to learn how to do this for both iOS and android,
check out testing state restoration on the
RestorationManager page.
warning warning
  don’t forget to reenable
  storing state on your device once you are
  finished with testing!
<topic_end>
<topic_start>
other resources
for further information on state restoration,
check out the following resources:
to learn more about short term and long term state,
check out differentiate between ephemeral state
and app state.
you might want to check out packages on pub.dev that
perform state restoration, such as statePersistence.
<topic_end>
<topic_start>
targeting ChromeOS with android
this page discusses considerations unique to building
android apps that support ChromeOS with flutter.
<topic_end>
<topic_start>
flutter & ChromeOS tips & tricks
for the current versions of ChromeOS, only certain ports from
linux are exposed to the rest of the environment.
here’s an example of how to launch
flutter DevTools for an android app with ports
that will work:
then, navigate to http://127.0.0.1:8000/#
in your chrome browser and enter the URL to your
application. the last flutter run command you
just ran should output a URL similar to the format
of http://127.0.0.1:8080/auth_code=/. use this URL
and select “connect” to start the flutter DevTools
for your android app.
<topic_end>
<topic_start>
flutter ChromeOS lint analysis
flutter has ChromeOS-specific lint analysis checks
to make sure that the app that you’re building
works well on ChromeOS. it looks for things
like required hardware in your android manifest
that aren’t available on ChromeOS devices,
permissions that imply requests for unsupported
hardware, as well as other properties or code
that would bring a lesser experience on these devices.
to activate these,
you need to create a new analysis_options.yaml
file in your project folder to include these options.
(if you have an existing analysis_options.yaml file,
you can update it)
to run these from the command line, use the following command:
sample output for this command might look like:
<topic_end>
<topic_start>
iOS
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
add iOS devtools for flutter
to choose the guide to add iOS devtools to your flutter configuration,
click the getting started path you followed.
<topic_end>
<topic_start>
leveraging apple's system APIs and frameworks
when you come from iOS development, you might need to find
flutter plugins that offer the same abilities as apple’s system
libraries. this might include accessing device hardware or interacting
with specific frameworks like HealthKit or MapKit.
for an overview of how the SwiftUI framework compares to flutter,
see flutter for SwiftUI developers.
<topic_end>
<topic_start>
introducing flutter plugins
dart calls libraries that contain platform-specific code plugins.
when developing an app with flutter, you use plugins to interact
with system libraries.
in your dart code, you use the plugin’s dart API to call the native
code from the system library being used. this means that you can write
the code to call the dart API. the API then makes it work for all
platforms that the plugin supports.
to learn more about plugins, see using packages.
though this page links to some popular plugins,
you can find thousands more, along with examples,
on pub.dev. the following table does not endorse any particular plugin.
if you can’t find a package that meets your need,
you can create your own or use platform channels directly in your project.
to learn more, see writing platform-specific code.
<topic_end>
<topic_start>
adding a plugin to your project
to use an apple framework within your native project,
import it into your swift or Objective-C file.
to add a flutter plugin, run flutter pub add package_name
from the root of your project.
this adds the dependency to your pubspec.yaml file.
after you add the dependency, add an import statement for the package
in your dart file.
you might need to change app settings or initialization logic.
if that’s needed, the package’s “readme” page on pub.dev
should provide details.
<topic_end>
<topic_start>
flutter plugins and apple frameworks
supports both google play store on android and apple app store on iOS. ↩
adds google pay payments on android and apple pay payments on iOS. ↩
uses firebase cloud messaging and integrates with APNs. ↩
includes sensors like accelerometer, gyroscope, etc. ↩
uses google’s ML kit and supports various features like text recognition, face detection, image labeling, landmark recognition, and barcode scanning. you can also create a custom model with firebase. to learn more, see use a custom TensorFlow lite model with flutter. ↩ ↩2
uses the OpenWeatherMap API. other packages exist that can pull from different weather APIs. ↩
<topic_end>
<topic_start>
adding a launch screen to your iOS app
launch screens provide a simple initial experience while your iOS app loads.
they set the stage for your application, while allowing time for the app engine
to load and your app to initialize.
all apps submitted to the apple app store
must provide a launch screen
with an xcode storyboard.
<topic_end>
<topic_start>
customize the launch screen
the default flutter template includes an xcode
storyboard named LaunchScreen.storyboard
that can be customized your own assets.
by default, the storyboard displays a blank image,
but you can change this. to do so,
open the flutter app’s xcode project
by typing open ios/Runner.xcworkspace
from the root of your app directory.
then select Runner/Assets.xcassets
from the project navigator and
drop in the desired images to the LaunchImage image set.
apple provides detailed guidance for launch screens as
part of the human interface guidelines.
<topic_end>
<topic_start>
adding an iOS app clip target
error important
  targeting iOS 16 increases the uncompressed IPA payload size limit
  to 15mb. depending on the size of your app, you might hit the limit. (#71098).
this guide describes how to manually add another
flutter-rendering iOS app clip target to your
existing flutter project or add-to-app project.
warning warning
  this is an advanced guide and is best intended
  for audience with a working knowledge of iOS development.
to see a working sample, see the app clip sample on GitHub.
<topic_end>
<topic_start>
step 1 - open project
open your iOS xcode project, such as
ios/Runner.xcworkspace for full-Flutter apps.
<topic_end>
<topic_start>
step 2 - add an app clip target
2.1
click on your project in the project navigator to show
the project settings.
press + at the bottom of the target list to add a new target.
2.2
select the app clip type for your new target.
2.3
enter your new target detail in the dialog.
select storyboard for interface.
select the same language as your original target for language.
(in other words, to simplify the setup,
don’t create a swift app clip target for
an Objective-C main target, and vice versa.)
2.4
in the following dialog,
activate the new scheme for the new target.
2.5
back in the project settings, open the build phases tab.
drag embedded app clips to above thin binary.
<topic_end>
<topic_start>
step 3 - remove unneeded files
3.1
in the project navigator, in the newly created app clip group,
delete everything except info.plist and
<app clip target>.entitlements.
lightbulb tip
  for add-to-app users, it’s up to the reader to decide
  how much of this template to keep to invoke
  FlutterViewController or FlutterEngine APIs
  from this code later.
move files to trash.
3.2
if you don’t use the SceneDelegate.swift file,
remove the reference to it in the info.plist.
open the info.plist file in the app clip group.
delete the entire dictionary entry for
application scene manifest.
<topic_end>
<topic_start>
step 4 - share build configurations
this step isn’t necessary for add-to-app projects
since add-to-app projects have their custom build
configurations and versions.
4.1
back in the project settings,
select the project entry now rather than any targets.
in the info tab, under the configurations
expandable group, expand the
debug, profile, and release entries.
for each, select the same value from the drop-down menu
for the app clip target as the entry selected for the
normal app target.
this gives your app clip target access to flutter’s
required build settings.
set iOS deployment target to at least 16.0 to take advantage of the
15mb size limit.
4.2
in the app clip group’s info.plist file, set:
<topic_end>
<topic_start>
step 5 - share code and assets
<topic_end>
<topic_start>
option 1 - share everything
assuming the intent is to show the same flutter UI
in the standard app as in the app clip,
share the same code and assets.
for each of the following: main.storyboard, assets.xcassets,
LaunchScreen.storyboard, GeneratedPluginRegistrant.m, and
AppDelegate.swift (and supporting files/main.m if using Objective-C),
select the file, then in the first tab of the inspector,
also include the app clip target in the target membership
checkbox group.
<topic_end>
<topic_start>
option 2 - customize flutter launch for app clip
in this case,
do not delete everything listed in step 3.
instead, use the scaffolding and the iOS add-to-app APIs
to perform a custom launch of flutter.
for example to show a custom flutter route.
<topic_end>
<topic_start>
step 6 - add app clip associated domains
this is a standard step for app clip development.
see the official apple documentation.
6.1
open the <app clip target>.entitlements file.
add an associated domains array type.
add a row to the array with appclips:<your bundle id>.
6.2
the same associated domains entitlement needs to be added
to your main app, as well.
copy the <app clip target>.entitlements file from your
app clip group to your main app group and rename it to
the same name as your main target
such as runner.entitlements.
open the file and delete the
parent application identifiers
entry for the main app’s entitlement file
(leave that entry for the app clip’s entitlement file).
6.3
back in the project settings, select the main app’s target,
open the build settings tab.
set the code signing entitlements setting to the
relative path of the second entitlements file
created for the main app.
<topic_end>
<topic_start>
step 7 - integrate flutter
these steps are not necessary for add-to-app.
7.1
for the swift target,
set the Objective-C bridging header
build setting to Runner/Runner-Bridging-Header.h
in other words,
the same as the main app target’s build settings.
7.2
now open the build phases tab. press the + sign
and select new run script phase.
drag that new phase to below the dependencies phase.
expand the new phase and add this line to the script content:
uncheck based on dependency analysis.
in other words,
the same as the main app target’s build phases.
this ensures that your flutter dart code is compiled
when running the app clip target.
7.3
press the + sign and select new run script phase again.
leave it as the last phase.
this time, add:
uncheck based on dependency analysis.
in other words,
the same as the main app target’s build phases.
this ensures that your flutter app and engine are embedded
into the app clip bundle.
<topic_end>
<topic_start>
step 8 - integrate plugins
8.1
open the podfile for your flutter project
or add-to-app host project.
for full-Flutter apps, replace the following section:
with:
at the top of the file,
also uncomment platform :ios, '12.0' and set the
version to the lowest of the two target’s iOS
deployment target.
for add-to-app, add to:
with:
8.2
from the command line,
enter your flutter project directory
and then install the pod:
<topic_end>
<topic_start>
run
you can now run your app clip target from xcode by
selecting your app clip target from the scheme drop-down,
selecting an iOS 16 or higher device and pressing run.
to test launching an app clip from the beginning,
also consult apple’s doc on
testing your app clip’s launch experience.
<topic_end>
<topic_start>
debugging, hot reload
unfortunately flutter attach cannot auto-discover
the flutter session in an app clip due to
networking permission restrictions.
in order to debug your app clip and use functionalities
like hot reload, you must look for the observatory URI
from the console output in xcode after running.
you must then copy and paste it back into the
flutter attach command to connect.
for example:
<topic_end>
<topic_start>
adding iOS app extensions
iOS app extensions allow you to expand functionality
outside your app. your app could appear as a home screen widget,
or you can make portions of your app available within other apps.
to learn more about app extensions, check out
apple’s documentation.
info note
  if you experience a build error when building an
  iOS app that includes an app extension, be
  aware that there is an open bug. the workaround
  involves changing the order of the build process.
  for more information, check out
  issue #9690 and issue #135056.
<topic_end>
<topic_start>
how do you add an app extension to your flutter app?
to add an app extension to your flutter app,
add the extension point target to your xcode project.
in xcode, select file -> new -> target from the menu bar.
to learn how to add a home screen widget to your iOS device,
check out the 
adding a home screen widget to your flutter app
codelab.
<topic_end>
<topic_start>
how do flutter apps interact with app extensions?
flutter apps interact with app extensions using the same
techniques as UIKit or SwiftUI apps.
the containing app and the app extension don’t communicate directly.
the containing app might not be running while the device user
interacts with the extension.
the app and your extension can read and write to
shared resources or use higher-level APIs
to communicate with each other.
<topic_end>
<topic_start>
using higher-level APIs
some extensions have APIs. for example, 
the core spotlight framework indexes your app,
allowing users to search from spotlight and safari.
the WidgetKit framework can trigger an update
of your home screen widget.
to simplify how your app communicates with extensions,
flutter plugins wrap these APIs.
to find plugins that wrap extension APIs,
check out leveraging apple’s system APIs and frameworks
or search pub.dev.
<topic_end>
<topic_start>
sharing resources
to share resources between your flutter app
and your app extension, put the runner app target
and the extension target in the same app group.
info note
  you must be signed in to your apple developer account.
to add a target to an app group:
choose which app group you want to add the target from
one of two options:
when two targets belong to the same app group,
they can read from and write to the same source.
choose one of the following sources for your data.
<topic_end>
<topic_start>
background updates
background tasks provide a means to update your extension
through code regardless of the status of your app.
to schedule background work from your flutter app,
use the workmanager plugin.
<topic_end>
<topic_start>
deep linking
you might want to direct users from an
app extension to a specific page in your flutter app.
to open a specific route in your app,
you can use deep linking.
<topic_end>
<topic_start>
creating app extension UIs with flutter
some app extensions display a user interface.
for example, share extensions allow users to conveniently
share content with other apps,
such as sharing a picture to create
a new post on a social media app.
as of the 3.16 release, you can build
flutter UI for an app extension,
though you must use an extension-safe
flutter.xcframework and embed the
FlutterViewController as described in
the following section.
info note
  due to the memory limitations of app extensions,
  use flutter to build an app extension UI for extension
  types that have memory limits larger than 100mb.
  for example, share extensions have a 120mb memory limit.
in addition, flutter uses extra memory in debug mode.
  therefore, flutter doesn’t fully support running
  app extensions in debug mode on physical devices
  when used to build extension UI; it might run out of memory.
  as an alternative,
  use an iOS simulator to test your extension in debug mode.
locate the extension-safe flutter.xcframework file,
at <path_to_flutter_sdk>/bin/cache/artifacts/engine/ios/extension_safe/flutter.xcframework.
drag and drop the flutter.xcframework file into your
share extension’s frameworks and libraries list.
make sure the embed column says “embed & sign”.
open the flutter app project settings in xcode
to share build configurations.
(optional) replace any storyboard files with an extension class, if needed.
embed the FlutterViewController as described in
adding a flutter screen. for example, you can display a
specific route in your flutter app within a share extension.
<topic_end>
<topic_start>
test extensions
testing extensions on simulators and physical devices
have slightly different procedures.
<topic_end>
<topic_start>
test on a simulator
<topic_end>
<topic_start>
test on a physical device
you can use the following procedure or the
testing on simulators instructions
to test on physical devices.
<topic_end>
<topic_start>
tutorials
for step-by-step instruction for using app
extensions with your flutter iOS app, check out the
adding a home screen widget to your flutter app
codelab.
<topic_end>
<topic_start>
binding to native iOS code using dart:ffi
flutter mobile and desktop apps can use the
dart:ffi library to call native c APIs.
FFI stands for foreign function interface.
other terms for similar functionality include
native interface and language bindings.
info note
  this page describes using the dart:ffi library
  in iOS apps. for information on android, see
  binding to native android code using dart:ffi.
  for information in macOS, see
  binding to native macOS code using dart:ffi.
  this feature is not yet supported for web plugins.
before your library or program can use the FFI library
to bind to native code, you must ensure that the
native code is loaded and its symbols are visible to dart.
this page focuses on compiling, packaging,
and loading iOS native code within a flutter plugin or app.
this tutorial demonstrates how to bundle C/C++
sources in a flutter plugin and bind to them using
the dart FFI library on iOS.
in this walkthrough, you’ll create a c function
that implements 32-bit addition and then
exposes it through a dart plugin named “native_add”.
<topic_end>
<topic_start>
dynamic vs static linking
a native library can be linked into an app either
dynamically or statically. a statically linked library
is embedded into the app’s executable image,
and is loaded when the app starts.
symbols from a statically linked library can be
loaded using DynamicLibrary.executable or
DynamicLibrary.process.
a dynamically linked library, by contrast, is distributed
in a separate file or folder within the app,
and loaded on-demand. on iOS, the dynamically linked
library is distributed as a .framework folder.
a dynamically linked library can be loaded into
dart using DynamicLibrary.open.
API documentation is available from the dart dev channel:
dart API reference documentation.
<topic_end>
<topic_start>
create an FFI plugin
to create an FFI plugin called “native_add”,
do the following:
info note
  you can exclude platforms from --platforms that you don’t want
  to build to. however, you need to include the platform of 
  the device you are testing on.
this will create a plugin with C/C++ sources in native_add/src.
these sources are built by the native build files in the various
os build folders.
the FFI library can only bind against c symbols,
so in c++ these symbols are marked extern "c".
you should also add attributes to indicate that the
symbols are referenced from dart,
to prevent the linker from discarding the symbols
during link-time optimization.
__attribute__((visibility("default"))) __attribute__((used)).
on iOS, the native_add/ios/native_add.podspec links the code.
the native code is invoked from dart in lib/native_add_bindings_generated.dart.
the bindings are generated with package:ffigen.
<topic_end>
<topic_start>
other use cases
<topic_end>
<topic_start>
iOS and macOS
dynamically linked libraries are automatically loaded by
the dynamic linker when the app starts. their constituent
symbols can be resolved using DynamicLibrary.process.
you can also get a handle to the library with
DynamicLibrary.open to restrict the scope of
symbol resolution, but it’s unclear how apple’s
review process handles this.
symbols statically linked into the application binary
can be resolved using DynamicLibrary.executable or
DynamicLibrary.process.
<topic_end>
<topic_start>
platform library
to link against a platform library,
use the following instructions:
<topic_end>
<topic_start>
first-party library
a first-party native library can be included either
as source or as a (signed) .framework file.
it’s probably possible to include statically linked
archives as well, but it requires testing.
<topic_end>
<topic_start>
source code
to link directly to source code,
use the following instructions:
add the following prefix to the
exported symbol declarations to ensure they
are visible to dart:
C/C++/Objective-C
swift
<topic_end>
<topic_start>
compiled (dynamic) library
to link to a compiled dynamic library,
use the following instructions:
<topic_end>
<topic_start>
open-source third-party library
to create a flutter plugin that includes both
C/C++/Objective-C and dart code,
use the following instructions:
the native code is then statically linked into
the application binary of any app that uses
this plugin.
<topic_end>
<topic_start>
closed-source third-party library
to create a flutter plugin that includes dart
source code, but distribute the C/C++ library
in binary form, use the following instructions:
warning warning
do not upload this plugin
  (or any plugin containing binary code) to pub.dev.
  instead, this plugin should be downloaded
  from a trusted third-party,
  as shown in the CocoaPods example.
<topic_end>
<topic_start>
stripping iOS symbols
when creating a release archive (ipa),
the symbols are stripped by xcode.
<topic_end>
<topic_start>
other resources
to learn more about c interoperability, check out these videos:
<topic_end>
<topic_start>
hosting native iOS views in your flutter app with platform views
platform views allow you to embed native views in a flutter app,
so you can apply transforms, clips, and opacity to the native view
from dart.
this allows you, for example, to use the native
google maps from the android and iOS SDKs
directly inside your flutter app.
info note
  this page discusses how to host your own native iOS views
  within a flutter app.
  if you’d like to embed native android views
  in your flutter app,
  see hosting native android views.
iOS only uses hybrid composition,
which means that the native
UIView is appended to the view hierarchy.
to create a platform view on iOS,
use the following instructions:
<topic_end>
<topic_start>
on the dart side
on the dart side, create a widget
and add the build implementation,
as shown in the following steps.
in the dart widget file, make changes similar to those 
shown in native_view_example.dart:
add the following imports:
<code_start>
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
<code_end>
implement a build() method:
<code_start>
widget build(BuildContext context) {
  // this is used in the platform side to register the view.
  const string viewType = '<platform-view-type>';
  // pass parameters to the platform side.
  final Map<String, dynamic> creationParams = <string, dynamic>{};
  return UiKitView(
    viewType: viewType,
    layoutDirection: TextDirection.ltr,
    creationParams: creationParams,
    creationParamsCodec: const StandardMessageCodec(),
  );
}
<code_end>
for more information, see the API docs for:
UIKitView.
<topic_end>
<topic_start>
on the platform side
on the platform side, use either swift or Objective-C:
implement the factory and the platform view.
the FLNativeViewFactory creates the platform view,
and the platform view provides a reference to the UIView.
for example, FLNativeView.swift:
finally, register the platform view.
this can be done in an app or a plugin.
for app registration,
modify the app’s AppDelegate.swift:
for plugin registration,
modify the plugin’s main file
(for example, FLPlugin.swift):
in Objective-C, add the headers for the factory and the platform view.
for example, as shown in FLNativeView.h:
implement the factory and the platform view.
the FLNativeViewFactory creates the platform view,
and the platform view provides a reference to the
UIView. for example, FLNativeView.m:
finally, register the platform view.
this can be done in an app or a plugin.
for app registration,
modify the app’s AppDelegate.m:
for plugin registration,
modify the main plugin file
(for example, FLPlugin.m):
for more information, see the API docs for:
<topic_end>
<topic_start>
putting it together
when implementing the build() method in dart,
you can use defaultTargetPlatform
to detect the platform, and decide which widget to use:
<code_start>
widget build(BuildContext context) {
  // this is used in the platform side to register the view.
  const string viewType = '<platform-view-type>';
  // pass parameters to the platform side.
  final Map<String, dynamic> creationParams = <string, dynamic>{};
  switch (defaulttargetplatform) {
    case TargetPlatform.android:
    // return widget on android.
    case TargetPlatform.iOS:
    // return widget on iOS.
    default:
      throw UnsupportedError('Unsupported platform view');
  }
}
<code_end>
<topic_end>
<topic_start>
performance
platform views in flutter come with performance trade-offs.
for example, in a typical flutter app, the flutter UI is 
composed on a dedicated raster thread. 
this allows flutter apps to be fast, 
as the main platform thread is rarely blocked.
when a platform view is rendered with hybrid composition, 
the flutter UI is composed from the platform thread. 
the platform thread competes with other tasks 
like handling OS or plugin messages.
when an iOS PlatformView is on screen, the screen refresh rate is 
capped at 80fps to avoid rendering janks.
for complex cases, there are some techniques that can be used 
to mitigate performance issues.
for example, you could use a placeholder texture while an 
animation is happening in dart. 
in other words, if an animation is slow while a platform view is rendered, 
then consider taking a screenshot of the native view and rendering it as a texture.
<topic_end>
<topic_start>
composition limitations
there are some limitations when composing iOS platform views.
<topic_end>
<topic_start>
iOS debugging
due to security around
local network permissions in iOS 14 or later,
you must accept a permission dialog box to enable
flutter debugging functionalities such as hot-reload
and DevTools.
this affects debug and profile builds only and won’t
appear in release builds. you can also allow this
permission by enabling
settings > privacy > local network > your app.
<topic_end>
<topic_start>
restore state on iOS
when a user runs a mobile app and then selects another
app to run, the first app is moved to the background,
or backgrounded. the operating system (both iOS and android)
often kill the backgrounded app to release memory or
improve performance for the app running in the foreground.
you can use the RestorationManager (and related)
classes to handle state restoration. 
an iOS app requires a bit of extra setup in xcode,
but the restoration classes otherwise work the same on
both iOS and android.
for more information, check out state restoration on android
and the VeggieSeasons code sample.
<topic_end>
<topic_start>
linux
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
building linux apps with flutter
this page discusses considerations unique to building
linux apps with flutter, including shell integration
and preparation of apps for distribution.
<topic_end>
<topic_start>
integrating with linux
the linux programming interface,
comprising library functions and system calls,
is designed around the c language and ABI.
fortunately, dart provides dart:ffi,
which is designed to enable dart programs
to efficiently call into c libraries.
FFI provides flutter apps with the ability to
allocate native memory with malloc or calloc,
support for pointers, structs and callbacks,
and ABI types like long and size_t.
for more information about calling c libraries
from flutter, see c interop using dart:ffi.
many apps will benefit from using a package that
wraps the underlying library
calls in a more convenient, idiomatic dart API.
canonical has built a series of packages
with a focus on enabling dart and flutter on linux,
including support for desktop notifications,
dbus, network management, and bluetooth.
more generally, many other packages support linux,
including common packages such as url_launcher,
shared_preferences, file_selector, and
path_provider.
<topic_end>
<topic_start>
preparing linux apps for distribution
the executable binary can be found in your project under
build/linux/<build mode>/bundle/. alongside your
executable binary in the bundle directory there are
two directories:
in addition to these files, your application also
relies on various operating system libraries that
it’s been compiled against.
you can see the full list by running ldd
against your application. for example,
assuming you have a flutter desktop application
called linux_desktop_test, you could inspect
the system libraries it depends upon as follows:
to wrap up this application for distribution
you need to include everything in the bundle directory,
and make sure the linux system you are installing
it on has all of the system libraries required.
this could be as simple as:
for information on publishing a linux application
to the snap store, see
build and release a linux application to the snap store.
<topic_end>
<topic_start>
macOS
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
add macOS devtools for flutter
to choose the guide to add macOS devtools to your flutter configuration,
click the getting started path you followed.
<topic_end>
<topic_start>
building macOS apps with flutter
this page discusses considerations unique to building
macOS apps with flutter, including shell integration
and distribution of macOS apps through the apple store.
<topic_end>
<topic_start>
integrating with macOS look and feel
while you can use any visual style or theme you choose
to build a macOS app, you might want to adapt your app
to more fully align with the macOS look and feel.
flutter includes the cupertino widget set,
which provides a set of widgets for
the current iOS design language.
many of these widgets, including sliders,
switches and segmented controls,
are also appropriate for use on macOS.
alternatively, you might find the macos_ui
package a good fit for your needs.
this package provides widgets and themes that
implement the macOS design language,
including a MacosWindow frame and scaffold,
toolbars, pulldown and
pop-up buttons, and modal dialogs.
<topic_end>
<topic_start>
building macOS apps
to distribute your macOS application, you can either
distribute it through the macOS app store,
or you can distribute the .app itself,
perhaps from your own website.
as of macOS 10.14.5, you need to notarize
your macOS application before distributing
it outside of the macOS app store.
the first step in both of the above processes
involves working with your application inside of xcode.
to be able to compile your application from inside of
xcode you first need to build the application for release
using the flutter build command, then open the
flutter macOS runner application.
once inside of xcode, follow either apple’s
documentation on notarizing macOS applications, or
on distributing an application through the app store.
you should also read through the
macOS-specific support
section below to understand how entitlements,
the app sandbox, and the hardened runtime
impact your distributable application.
build and release a macOS app provides a more detailed
step-by-step walkthrough of releasing a flutter app to the
app store.
<topic_end>
<topic_start>
entitlements and the app sandbox
macOS builds are configured by default to be signed,
and sandboxed with app sandbox.
this means that if you want to confer specific
capabilities or services on your macOS app,
such as the following:
then you must set up specific entitlements in xcode.
the following section tells you how to do this.
<topic_end>
<topic_start>
setting up entitlements
managing sandbox settings is done in the
macos/Runner/*.entitlements files. when editing
these files, you shouldn’t remove the original
Runner-DebugProfile.entitlements exceptions
(that support incoming network connections and JIT),
as they’re necessary for the debug and profile
modes to function correctly.
if you’re used to managing entitlement files through
the xcode capabilities UI, be aware that the capabilities
editor updates only one of the two files or,
in some cases, it creates a whole new entitlements
file and switches the project to use it for all configurations.
either scenario causes issues. we recommend that you
edit the files directly. unless you have a very specific
reason, you should always make identical changes to both files.
if you keep the app sandbox enabled (which is required if you
plan to distribute your application in the app store),
you need to manage entitlements for your application
when you add certain plugins or other native functionality.
for instance, using the file_chooser plugin
requires adding either the
com.apple.security.files.user-selected.read-only or
com.apple.security.files.user-selected.read-write entitlement.
another common entitlement is
com.apple.security.network.client,
which you must add if you make any network requests.
without the com.apple.security.network.client entitlement,
for example, network requests fail with a message such as:
important: the com.apple.security.network.server
  entitlement, which allows incoming network connections,
  is enabled by default only for debug and profile
  builds to enable communications between flutter tools
  and a running app. if you need to allow incoming
  network requests in your application,
  you must add the com.apple.security.network.server
  entitlement to Runner-Release.entitlements as well,
  otherwise your application will work correctly for debug or
  profile testing, but will fail with release builds.
for more information on these topics,
see app sandbox and entitlements
on the apple developer site.
<topic_end>
<topic_start>
hardened runtime
if you choose to distribute your application outside
of the app store, you need to notarize your application
for compatibility with macOS 10.15+.
this requires enabling the hardened runtime option.
once you have enabled it, you need a valid signing
certificate in order to build.
by default, the entitlements file allows JIT for
debug builds but, as with app sandbox, you might
need to manage other entitlements.
if you have both app sandbox and hardened
runtime enabled, you might need to add multiple
entitlements for the same resource.
for instance, microphone access would require both
com.apple.security.device.audio-input (for hardened runtime)
and com.apple.security.device.microphone (for app sandbox).
for more information on this topic,
see hardened runtime on the apple developer site.
<topic_end>
<topic_start>
binding to native macOS code using dart:ffi
flutter mobile and desktop apps can use the
dart:ffi library to call native c APIs.
FFI stands for foreign function interface.
other terms for similar functionality include
native interface and language bindings.
info note
  this page describes using the dart:ffi library
  in macOS desktop apps.
  for information on android, see
  binding to native android code using dart:ffi.
  for information on iOS, see
  binding to native iOS code using dart:ffi.
  this feature is not yet supported for web plugins.
before your library or program can use the FFI library
to bind to native code, you must ensure that the
native code is loaded and its symbols are visible to dart.
this page focuses on compiling, packaging,
and loading macOS native code within a flutter plugin or app.
this tutorial demonstrates how to bundle C/C++
sources in a flutter plugin and bind to them using
the dart FFI library on macOS.
in this walkthrough, you’ll create a c function
that implements 32-bit addition and then
exposes it through a dart plugin named “native_add”.
<topic_end>
<topic_start>
dynamic vs static linking
a native library can be linked into an app either
dynamically or statically. a statically linked library
is embedded into the app’s executable image,
and is loaded when the app starts.
symbols from a statically linked library can be
loaded using DynamicLibrary.executable or
DynamicLibrary.process.
a dynamically linked library, by contrast, is distributed
in a separate file or folder within the app,
and loaded on-demand. on macOS, the dynamically linked
library is distributed as a .framework folder.
a dynamically linked library can be loaded into
dart using DynamicLibrary.open.
API documentation is available from the dart dev channel:
dart API reference documentation.
<topic_end>
<topic_start>
create an FFI plugin
if you already have a plugin, skip this step.
to create a plugin called “native_add”,
do the following:
info note
  you can exclude platforms from --platforms that you don’t want
  to build to. however, you need to include the platform of 
  the device you are testing on.
this will create a plugin with C/C++ sources in native_add/src.
these sources are built by the native build files in the various
os build folders.
the FFI library can only bind against c symbols,
so in c++ these symbols are marked extern "c".
you should also add attributes to indicate that the
symbols are referenced from dart,
to prevent the linker from discarding the symbols
during link-time optimization.
__attribute__((visibility("default"))) __attribute__((used)).
on iOS, the native_add/macos/native_add.podspec links the code.
the native code is invoked from dart in lib/native_add_bindings_generated.dart.
the bindings are generated with package:ffigen.
<topic_end>
<topic_start>
other use cases
<topic_end>
<topic_start>
iOS and macOS
dynamically linked libraries are automatically loaded by
the dynamic linker when the app starts. their constituent
symbols can be resolved using DynamicLibrary.process.
you can also get a handle to the library with
DynamicLibrary.open to restrict the scope of
symbol resolution, but it’s unclear how apple’s
review process handles this.
symbols statically linked into the application binary
can be resolved using DynamicLibrary.executable or
DynamicLibrary.process.
<topic_end>
<topic_start>
platform library
to link against a platform library,
use the following instructions:
<topic_end>
<topic_start>
first-party library
a first-party native library can be included either
as source or as a (signed) .framework file.
it’s probably possible to include statically linked
archives as well, but it requires testing.
<topic_end>
<topic_start>
source code
to link directly to source code,
use the following instructions:
add the following prefix to the
exported symbol declarations to ensure they
are visible to dart:
C/C++/Objective-C
swift
<topic_end>
<topic_start>
compiled (dynamic) library
to link to a compiled dynamic library,
use the following instructions:
<topic_end>
<topic_start>
compiled (dynamic) library (macos)
to add a closed source library to a
flutter macOS desktop app,
use the following instructions:
<topic_end>
<topic_start>
other resources
to learn more about c interoperability, check out these videos:
<topic_end>
<topic_start>
web support for flutter
flutter’s web support delivers the same experiences on the web as on mobile.
building on the portability of dart, the power of the web platform and the
flexibility of the flutter framework, you can now build apps for iOS, android,
and the browser from the same codebase. you can compile existing flutter code
written in dart into a web experience because it is exactly the same flutter
framework and web is just another device target for your app.
adding web support to flutter involved implementing flutter’s
core drawing layer on top of standard browser APIs, in addition
to compiling dart to JavaScript, instead of the ARM machine code that
is used for mobile applications. using a combination of DOM, canvas,
and WebAssembly, flutter can provide a portable, high-quality,
and performant user experience across modern browsers.
we implemented the core drawing layer completely in dart
and used dart’s optimized JavaScript compiler to compile the
flutter core and framework along with your application
into a single, minified source file that can be deployed to
any web server.
while you can do a lot on the web,
flutter’s web support is most valuable in the
following scenarios:
not every HTML scenario is ideally suited for flutter at this time.
for example, text-rich, flow-based, static content such as blog articles
benefit from the document-centric model that the web is built around,
rather than the app-centric services that a UI framework like flutter
can deliver. however, you can use flutter to embed interactive
experiences into these websites.
for a glimpse into how to migrate your mobile app to web, see
the following video:
<topic_end>
<topic_start>
resources
the following resources can help you get started:
<topic_end>
<topic_start>
add web devtools for flutter
to choose the guide to add web devtools to your flutter configuration,
click the getting started path you followed.
<topic_end>
<topic_start>
building a web application with flutter
this page covers the following steps for getting started with web support:
<topic_end>
<topic_start>
requirements
to create a flutter app with web support,
you need the following software:
for more information, see the web FAQ.
<topic_end>
<topic_start>
create a new project with web support
you can use the following steps
to create a new project with web support.
<topic_end>
<topic_start>
set up
run the following commands to use the latest version of the flutter SDK:
warning warning
  running flutter channel stable replaces your current version of flutter
  with the stable version and can take time if your connection is slow.
  after this, running flutter upgrade upgrades your install to the latest
 stable.  returning to another channel (beta or master) requires calling
 flutter channel <channel> explicitly.
if chrome is installed,
the flutter devices command outputs a chrome device
that opens the chrome browser with your app running,
and a web server that provides the URL serving the app.
in your IDE, you should see chrome (web) in the device pulldown.
<topic_end>
<topic_start>
create and run
creating a new project with web support is no different
than creating a new flutter project for other platforms.
<topic_end>
<topic_start>
IDE
create a new app in your IDE and it automatically
creates iOS, android, desktop, and web versions of your app.
from the device pulldown, select chrome (web)
and run your app to see it launch in chrome.
<topic_end>
<topic_start>
command line
to create a new app that includes web support
(in addition to mobile support), run the following commands,
substituting my_app with the name of your project:
to serve your app from localhost in chrome,
enter the following from the top of the package:
info note
  if there aren’t any other connected devices,
  the -d chrome is optional.
the flutter run command launches the application using the
development compiler in a chrome browser.
warning warning
hot reload is not supported in a web browser
  currently, flutter supports hot restart,
  but not hot reload in a web browser.
<topic_end>
<topic_start>
build
run the following command to generate a release build:
a release build uses dart2js
(instead of the development compiler)
to produce a single JavaScript file main.dart.js.
you can create a release build using release mode
(flutter run --release) or by using flutter build web.
this populates a build/web directory
with built files, including an assets directory,
which need to be served together.
you can also include --web-renderer html  or --web-renderer canvaskit to
select between the HTML or CanvasKit renderers, respectively. for more
information, see web renderers.
for more information, see
build and release a web app.
<topic_end>
<topic_start>
add web support to an existing app
to add web support to an existing project
created using a previous version of flutter,
run the following command
from your project’s top-level directory:
<topic_end>
<topic_start>
web FAQ
<topic_end>
<topic_start>
what scenarios are ideal for flutter on the web?
not every web page makes sense in flutter, but we think flutter is particularly
suited for app-centric experiences:
at this time, flutter is not suitable for static websites with text-rich
flow-based content. for example, blog articles benefit from the document-centric
model that the web is built around, rather than the app-centric services that a
UI framework like flutter can deliver. however, you can use flutter to embed
interactive experiences into these websites.
for more information on how you can use flutter on the web,
see web support for flutter.
<topic_end>
<topic_start>
search engine optimization (seo)
in general, flutter is geared towards dynamic application experiences. flutter’s
web support is no exception. flutter web prioritizes performance, fidelity, and
consistency. this means application output does not align with what search
engines need to properly index. for web content that is static or document-like,
we recommend using HTML—just like we do on flutter.dev,
dart.dev, and pub.dev. you should also
consider separating your primary application experience—created in flutter—from
your landing page, marketing content, and help content—created using
search-engine optimized HTML.
<topic_end>
<topic_start>
how do i create an app that also runs on the web?
see building a web app with flutter.
<topic_end>
<topic_start>
does hot reload work with a web app?
no, but you can use hot restart. hot restart is a fast way of seeing your
changes without having to relaunch your web app and wait for it to compile and
load. this works similarly to the hot reload feature for flutter mobile
development. the only difference is that hot reload remembers your state and hot
restart doesn’t.
<topic_end>
<topic_start>
how do i restart the app running in the browser?
you can either use the browser’s refresh button,
or you can enter “r” in the console where
“flutter run -d chrome” is running.
<topic_end>
<topic_start>
which web browsers are supported by flutter?
flutter web apps can run on the following browsers:
during development, chrome (on macOS, windows, and linux) and edge (on windows)
are supported as the default browsers for debugging your app.
<topic_end>
<topic_start>
can i build, run, and deploy web apps in any of the IDEs?
you can select chrome or edge as the target device in
android Studio/IntelliJ and VS code.
the device pulldown should now include the chrome (web)
option for all channels.
<topic_end>
<topic_start>
how do i build a responsive app for the web?
see creating responsive apps.
<topic_end>
<topic_start>
can i use dart:io with a web app?
no. the file system is not accessible from the browser.
for network functionality, use the http
package. note that security works somewhat
differently because the browser (and not the app)
controls the headers on an HTTP request.
<topic_end>
<topic_start>
how do i handle web-specific imports?
some plugins require platform-specific imports, particularly if they use the
file system, which is not accessible from the browser. to use these plugins
in your app, see the documentation for conditional imports
on dart.dev.
<topic_end>
<topic_start>
does flutter web support concurrency?
dart’s concurrency support via isolates
is not currently supported in flutter web.
flutter web apps can potentially work around this
by using web workers,
although no such support is built in.
<topic_end>
<topic_start>
how do i embed a flutter web app in a web page?
you can embed a flutter web app,
as you would embed other content,
in an iframe tag of an HTML file.
in the following example, replace “url”
with the location of your hosted HTML page:
if you encounter problems, please file an issue.
<topic_end>
<topic_start>
how do i debug a web app?
use flutter DevTools for the following tasks:
use chrome DevTools for the following tasks:
<topic_end>
<topic_start>
how do i test a web app?
use widget tests or integration tests. to learn more about
running integration tests in a browser, see the integration testing page.
<topic_end>
<topic_start>
how do i deploy a web app?
see preparing a web app for release.
<topic_end>
<topic_start>
does platform.is work on the web?
not currently.
<topic_end>
<topic_start>
web renderers
when running and building apps for the web, you can choose between two different
renderers. this page describes both renderers and how to choose the best one for
your needs. the two renderers are:
<topic_end>
<topic_start>
command line options
the --web-renderer command line option takes one of three values, auto,
html, or canvaskit.
this flag can be used with the run or build subcommands. for example:
this flag is ignored when a non-browser (mobile or desktop) device
target is selected.
<topic_end>
<topic_start>
runtime configuration
to override the web renderer at runtime:
the web renderer can’t be changed after the flutter engine startup process
begins in main.dart.js.
info note
  as of flutter 3.7.0,  setting a window.flutterWebRenderer
  (an approach used in previous releases) displays a
  deprecation notice in the JS console. for more information,
  check out customizing web app initialization.
<topic_end>
<topic_start>
choosing which option to use
choose the auto option (default) if you are optimizing for download size on
mobile browsers and optimizing for performance on desktop browsers.
choose the html option if you are optimizing download size over performance on
both desktop and mobile browsers.
choose the canvaskit option if you are prioritizing performance and
pixel-perfect consistency on both desktop and mobile browsers.
<topic_end>
<topic_start>
examples
run in chrome using the default renderer option (auto):
build your app in release mode, using the default (auto) option:
build your app in release mode, using just the CanvasKit renderer:
run  your app in profile mode using the HTML renderer:
<topic_end>
<topic_start>
customizing web app initialization
you can customize how a flutter app is initialized on the web
using the _flutter.loader JavaScript API provided by flutter.js.
this API can be used to display a loading indicator in CSS,
prevent the app from loading based on a condition,
or wait until the user presses a button before showing the app.
the initialization process is split into the following stages:
this page shows how to customize the behavior
at each stage of the initialization process.
<topic_end>
<topic_start>
getting started
by default, the index.html file
generated by the flutter create command
contains a script tag
that calls loadEntrypoint from the flutter.js file:
info note
  in flutter 2.10 or earlier,
  this script doesn’t support customization.
  to upgrade your index.html file to the latest version,
  see upgrading an older project.
the loadEntrypoint function calls the onEntrypointLoaded callback
once the service worker is initialized, and the main.dart.js entrypoint
has been downloaded and run by the browser. flutter also calls
onEntrypointLoaded on every hot restart during development.
the onEntrypointLoaded callback receives an engine initializer object as
its only parameter. use the engine initializer to set the run-time
configuration, and start the flutter web engine.
the initializeEngine() function returns a promise
that resolves with an app runner object. the app runner has a
single method, runApp(), that runs the flutter app.
<topic_end>
<topic_start>
customizing web app initialization
in this section,
learn how to customize each stage of your app’s initialization.
<topic_end>
<topic_start>
loading the entrypoint
the loadEntrypoint method accepts these parameters:
the serviceWorker JavaScript object accepts the following properties:
<topic_end>
<topic_start>
initializing the engine
as of flutter 3.7.0, you can use the initializeEngine method to
configure several run-time options of the flutter web engine through a
plain JavaScript object.
you can add any of the following optional parameters:
info note
  some of the parameters described above might have been overridden
  in previous releases by using properties in the window object.
  that approach is still supported, but displays a deprecation
  notice in the JS console, as of flutter 3.7.0.
<topic_end>
<topic_start>
engine configuration example
the initializeEngine method lets you pass any of the configuration
parameters described above to your flutter app.
consider the following example.
your flutter app should target an HTML element with id="flutter_app" and
use the canvaskit renderer. the resulting JavaScript code would resemble
the following:
for a more detailed explanation of each parameter, take a look at the
“runtime parameters” documentation section of the configuration.dart
file of the web engine.
<topic_end>
<topic_start>
skipping this step
instead of calling initializeEngine() on the engine initializer (and then
runApp() on the application runner), you can call autoStart() to
initialize the engine with its default configuration, and then start the app
immediately after the initialization is complete:
<topic_end>
<topic_start>
example: display a progress indicator
to give the user of your application feedback
during the initialization process,
use the hooks provided for each stage to update the DOM:
for a more practical example using CSS animations,
see the initialization code for the flutter gallery.
<topic_end>
<topic_start>
upgrading an older project
if your project was created in flutter 2.10 or earlier,
you can create a new index.html file
with the latest initialization template by running
flutter create as follows.
first, remove the files from your /web directory.
then, from your project directory, run the following:
<topic_end>
<topic_start>
displaying images on the web
the web supports the standard image widget to display images.
however, because web browsers are built to run untrusted code safely,
there are certain limitations in what you can do with images compared
to mobile and desktop platforms. this page explains these limitations
and offers ways to work around them.
<topic_end>
<topic_start>
background
this section summarizes the technologies available
across flutter and the web,
on which the solutions below are based on.
<topic_end>
<topic_start>
images in flutter
flutter offers the image widget as well as the low-level
dart:ui/Image class for rendering images.
the image widget has enough functionality for most use-cases.
the dart:ui/Image class can be used in
advanced situations where fine-grained control
of the image is needed.
<topic_end>
<topic_start>
images on the web
the web offers several methods for displaying images.
below are some of the common ones:
each option has its own benefits and drawbacks.
for example, the built-in elements fit nicely among
other HTML elements, and they automatically take
advantage of browser caching, and built-in image
optimization and memory management.
they allow you to safely display images from arbitrary sources
(more on than in the CORS section below).
drawImage is great when the image must fit within
other content rendered using the <canvas> element.
you also gain control over image sizing and,
when the CORS policy allows it, read the pixels
of the image back for further processing.
finally, WebGL gives you the highest degree of
control over the image. not only can you read the pixels and
apply custom image algorithms, but you can also use GLSL for
hardware-acceleration.
<topic_end>
<topic_start>
Cross-Origin resource sharing (cors)
CORS is a mechanism that browsers use to control
how one site accesses the resources of another site.
it is designed such that, by default, one web-site
is not allowed to make HTTP requests to another site
using XHR or fetch.
this prevents scripts on another site from acting on behalf
of the user and from gaining access to another
site’s resources without permission.
when using <img>, <picture>, or <canvas>,
the browser automatically blocks access to pixels
when it knows that an image is coming from another site
and the CORS policy disallows access to data.
WebGL requires access to the image data in order
to be able to render the image. therefore,
images to be rendered using WebGL must only come from servers
that have a CORS policy configured to work with
the domain that serves your application.
<topic_end>
<topic_start>
flutter renderers on the web
flutter offers a choice of two renderers on the web:
because the HTML renderer uses the <img>
element it can display images from
arbitrary sources. however,
this places the following limitations on what you
can do with them:
the CanvasKit renderer implements flutter’s image API fully.
however, it requires access to image pixels to do so,
and is therefore subject to the CORS policy.
<topic_end>
<topic_start>
solutions
<topic_end>
<topic_start>
in-memory, asset, and same-origin network images
if the app has the bytes of the encoded image in memory,
provided as an asset, or stored on the
same server that serves the application
(also known as same-origin), no extra effort is necessary.
the image can be displayed using
image.memory, image.asset, and image.network
in both HTML and CanvasKit modes.
<topic_end>
<topic_start>
cross-origin images
the HTML renderer can load cross-origin images
without extra configuration.
CanvasKit requires that the app gets the bytes of the encoded image.
there are several ways to do this, discussed below.
<topic_end>
<topic_start>
host your images in a CORS-enabled CDN.
typically, content delivery networks (cdn)
can be configured to customize what domains
are allowed to access your content.
for example, firebase site hosting allows
specifying a custom Access-Control-Allow-Origin
header in the firebase.json file.
<topic_end>
<topic_start>
lack control over the image server? use a CORS proxy.
if the image server cannot be configured to allow CORS
requests from your application,
you might still be able to load images by proxying
the requests through another server. this requires that the
intermediate server has sufficient access to load the images.
this method can be used in situations when the original
image server serves images publicly,
but is not configured with the correct CORS headers.
examples:
<topic_end>
<topic_start>
use <img> in a platform view.
flutter supports embedding HTML inside the app using
HtmlElementView.  use it to create an <img>
element to render the image from another domain.
however, do keep in mind that this comes with the
limitations explained in the section
“flutter renderers on the web” above.
as of today, using too many HTML elements
with the CanvasKit renderer might hurt performance.
if images interleave non-image content flutter needs to
create extra WebGL contexts between the <img> elements.
if your application needs to display a lot of images
on the same screen all at once, consider using
the HTML renderer instead of CanvasKit.
<topic_end>
<topic_start>
windows
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
add windows devtools for flutter
to choose the guide to add visual studio to your flutter configuration,
click the getting started path you followed.
<topic_end>
<topic_start>
building windows apps with flutter
this page discusses considerations unique to building
windows apps with flutter, including shell integration
and distribution of windows apps through the
microsoft store on windows.
<topic_end>
<topic_start>
integrating with windows
the windows programming interface combines traditional win32 APIs,
COM interfaces and more modern windows runtime libraries.
as all these provide a c-based ABI,
you can call into the services provided by the operating
system using dart’s foreign function interface library (dart:ffi).
FFI is designed to enable dart programs to efficiently call into
c libraries. it provides flutter apps with the ability to allocate
native memory with malloc or calloc, support for pointers,
structs and callbacks, and ABI types like long and size_t.
for more information about calling c libraries from flutter,
see c interop using dart:ffi.
in practice, while it is relatively straightforward to call
basic win32 APIs from dart in this way,
it is easier to use a wrapper library that abstracts the
intricacies of the COM programming model.
the win32 package provides a library
for accessing thousands of common windows APIs,
using metadata provided by microsoft for consistency and correctness.
the package also includes examples of
a variety of common use cases,
such as WMI, disk management, shell integration,
and system dialogs.
a number of other packages build on this foundation,
providing idiomatic dart access for the windows registry,
gamepad support, biometric storage,
taskbar integration, and serial port access, to name a few.
more generally, many other packages support windows,
including common packages such as url_launcher, shared_preferences, file_selector, and path_provider.
<topic_end>
<topic_start>
supporting windows UI guidelines
while you can use any visual style or theme you choose,
including material, some app authors might wish to build
an app that matches the conventions of microsoft’s
fluent design system. the fluent_ui package,
a flutter favorite, provides support for visuals
and common controls that are commonly found in
modern windows apps, including navigation views,
content dialogs, flyouts, date
pickers, and tree view widgets.
in addition, microsoft offers fluentui_system_icons,
a package that provides easy access to thousands of
fluent icons for use in your flutter app.
lastly, the bitsdojo_window package provides support
for “owner draw” title bars, allowing you to replace
the standard windows title bar with a custom one
that matches the rest of your app.
<topic_end>
<topic_start>
customizing the windows host application
when you create a windows app, flutter generates a
small c++ application that hosts flutter.
this “runner app” is responsible for creating and sizing a
traditional win32 window, initializing the flutter
engine and any native plugins,
and running the windows message loop
(passing relevant messages on to flutter for further processing).
you can, of course, make changes to this code to suit your needs,
including modifying the app name and icon,
and setting the window’s initial size and location.
the relevant code is in main.cpp,
where you will find code similar to the following:
replace myapp with the title you would like displayed in the
windows caption bar, as well as optionally adjusting the
dimensions for size and the window coordinates.
to change the windows application icon, replace the
app_icon.ico file in the windows\runner\resources
directory with an icon of your preference.
the generated windows executable filename can be changed
by editing the BINARY_NAME variable in windows/CMakeLists.txt:
when you run flutter build windows,
the executable file generated in the
build\windows\runner\Release directory
will match the newly given name.
finally, further properties for the app executable
itself can be found in the runner.rc file in the
windows\runner directory. here you can change the
copyright information and application version that
is embedded in the windows app, which is displayed
in the windows explorer properties dialog box.
to change the version number, edit the VERSION_AS_NUMBER
and VERSION_AS_STRING properties;
other information can be edited in the StringFileInfo block.
<topic_end>
<topic_start>
compiling with visual studio
for most apps, it’s sufficient to allow flutter to
handle the compilation process using the flutter run
and flutter build commands. if you are making significant
changes to the runner app or integrating flutter into an existing app,
you might want to load or compile the flutter app in visual studio itself.
follow these steps:
run flutter build windows to create the build\ directory.
open the visual studio solution file for the windows runner,
which can now be found in the build\windows directory,
named according to the parent flutter app.
in solution explorer, you will see a number of projects.
right-click the one that has the same name as the flutter app,
and choose set as startup project.
to generate the necessary dependencies,
run build > build solution
you can also press/
ctrl + shift + b.
to run the windows app from visual studio, go to debug > start debugging.
you can also press f5.
use the toolbar to switch between debug and release
configurations as appropriate.
<topic_end>
<topic_start>
distributing windows apps
there are various approaches you can use for
distributing your windows application.
here are some options:
<topic_end>
<topic_start>
MSIX packaging
MSIX, the new windows application package format,
provides a modern packaging format and installer.
this format can either be used to ship applications
to the microsoft store on windows, or you can
distribute app installers directly.
the easiest way to create an MSIX distribution
for a flutter project is to use the
msix pub package.
for an example of using the msix package
from a flutter desktop app,
see the desktop photo search sample.
<topic_end>
<topic_start>
create a self-signed .pfx certificate for local testing
for private deployment and testing with the help
of the MSIX installer, you need to give your application a
digital signature in the form of a .pfx certificate.
for deployment through the windows store,
generating a .pfx certificate is not required.
the windows store handles creation and management
of certificates for applications
distributed through its store.
distributing your application by self hosting it on a
website requires a certificate signed by a
certificate authority known to windows.
use the following instructions to generate a
self-signed .pfx certificate.
<topic_end>
<topic_start>
building your own zip file for windows
the flutter executable, .exe, can be found in your
project under build\windows\runner\<build mode>\.
in addition to that executable, you need the following:
place the DLL files in the directory next to the executable
and the other DLLs, and bundle them together in a zip file.
the resulting structure looks something like this:
at this point if desired it would be relatively simple to
add this folder to a windows installer such as inno setup, WiX, etc.
<topic_end>
<topic_start>
using packages
flutter supports using shared packages contributed by other developers
to the flutter and dart ecosystems. this allows quickly building
an app without having to develop everything from scratch.
what is the difference between a package
  and a plugin? a plugin is a type of
  package—the full designation is plugin package,
  which is generally shortened to plugin.
existing packages enable many use cases—for example,
making network requests (http),
navigation/route handling (go_router),
integration with device APIs
(url_launcher and battery_plus),
and using third-party platform SDKs like firebase
(flutterfire).
to write a new package, see developing packages.
to add assets, images, or fonts,
whether stored in files or packages,
see adding assets and images.
<topic_end>
<topic_start>
using packages
the following section describes how to use
existing published packages.
<topic_end>
<topic_start>
searching for packages
packages are published to pub.dev.
the flutter landing page on pub.dev displays
top packages that are compatible with flutter
(those that declare dependencies generally compatible with flutter),
and supports searching among all published packages.
the flutter favorites page on pub.dev lists
the plugins and packages that have been identified as
packages you should first consider using when writing
your app. for more information on what it means to
be a flutter favorite, see the
flutter favorites program.
you can also browse the packages on pub.dev by filtering
on android, iOS, web,
linux, windows, macOS,
or any combination thereof.
<topic_end>
<topic_start>
adding a package dependency to an app
to add the package, css_colors, to an app:
<topic_end>
<topic_start>
adding a package dependency to an app using flutter pub add
to add the package, css_colors, to an app:
<topic_end>
<topic_start>
removing a package dependency to an app using flutter pub remove
to remove the package, css_colors, to an app:
the installing tab,
available on any package page on pub.dev,
is a handy reference for these steps.
for a complete example,
see the css_colors example below.
<topic_end>
<topic_start>
conflict resolution
suppose you want to use some_package and
another_package in an app,
and both of these depend on url_launcher,
but in different versions.
that causes a potential conflict.
the best way to avoid this is for package authors to use
version ranges rather than specific versions when
specifying dependencies.
if some_package declares the dependencies above
and another_package declares a compatible
url_launcher dependency like '5.4.6' or
^5.5.0, pub resolves the issue automatically.
platform-specific dependencies on
gradle modules and/or CocoaPods
are solved in a similar way.
even if some_package and another_package
declare incompatible versions for url_launcher,
they might actually use url_launcher in
compatible ways. in this situation,
the conflict can be resolved by adding
a dependency override declaration to the app’s
pubspec.yaml file, forcing the use of a particular version.
for example, to force the use of url_launcher version 5.4.0,
make the following changes to the app’s pubspec.yaml file:
if the conflicting dependency is not itself a package,
but an android-specific library like guava,
the dependency override declaration must be added to
gradle build logic instead.
to force the use of guava version 28.0, make the following
changes to the app’s android/build.gradle file:
CocoaPods doesn’t currently offer dependency
override functionality.
<topic_end>
<topic_start>
developing new packages
if no package exists for your specific use case,
you can write a custom package.
<topic_end>
<topic_start>
managing package dependencies and versions
to minimize the risk of version collisions,
specify a version range in the pubspec.yaml file.
<topic_end>
<topic_start>
package versions
all packages have a version number, specified in the
package’s pubspec.yaml file. the current version of a package
is displayed next to its name (for example,
see the url_launcher package), as
well as a list of all prior versions
(see url_launcher versions).
to ensure that the app doesn’t break when you update a package,
specify a version range using one of the following formats.
ranged constraints: specify a minimum and maximum version.
ranged constraints using the caret syntax:
specify the version that serves as the inclusive minimum version.
this covers all versions from that version to the next major version.
this syntax means the same as the one noted in the first bullet.
to learn more, check out the package versioning guide.
<topic_end>
<topic_start>
updating package dependencies
when running flutter pub get
for the first time after adding a package,
flutter saves the concrete package version found in the pubspec.lock
lockfile. this ensures that you get the same version again
if you, or another developer on your team, run flutter pub get.
to upgrade to a new version of the package,
for example to use new features in that package,
run flutter pub upgrade
to retrieve the highest available version of the package
that is allowed by the version constraint specified in
pubspec.yaml.
note that this is a different command from
flutter upgrade or flutter update-packages,
which both update flutter itself.
<topic_end>
<topic_start>
dependencies on unpublished packages
packages can be used even when not published on pub.dev.
for private packages, or for packages not ready for publishing,
additional dependency options are available:
finally, use the ref argument to pin the dependency to a
specific git commit, branch, or tag. for more details, see
package dependencies.
<topic_end>
<topic_start>
examples
the following examples walk through the necessary steps for
using packages.
<topic_end>
<topic_start>
example: using the css_colors package
the css_colors package
defines color constants for CSS colors, so use the constants
wherever the flutter framework expects the color type.
to use this package:
create a new project called cssdemo.
open pubspec.yaml, and add the css-colors dependency:
run flutter pub get in the terminal,
or click get packages in VS code.
open lib/main.dart and replace its full contents with:
<code_start>
import 'package:css_colors/css_colors.dart';
 import 'package:flutter/material.dart';
 void main() {
   runApp(const MyApp());
 }
 class MyApp extends StatelessWidget {
   const MyApp({super.key});
   @override
   widget build(BuildContext context) {
     return const MaterialApp(
       home: DemoPage(),
     );
   }
 }
 class DemoPage extends StatelessWidget {
   const DemoPage({super.key});
   @override
   widget build(BuildContext context) {
     return scaffold(body: container(color: CSSColors.orange));
   }
 }
<code_end>
<topic_end>
<topic_start>
example: using the url_launcher package to launch the browser
the url_launcher plugin package enables opening
the default browser on the mobile platform to display
a given URL, and is supported on android, iOS, web,
windows, linux, and macOS.
this package is a special dart package called a
plugin package (or plugin),
which includes platform-specific code.
to use this plugin:
create a new project called launchdemo.
open pubspec.yaml, and add the url_launcher dependency:
run flutter pub get in the terminal,
or click get packages get in VS code.
open lib/main.dart and replace its full contents with the
following:
<code_start>
import 'package:flutter/material.dart';
 import 'package:path/path.dart' as p;
 import 'package:url_launcher/url_launcher.dart';
 void main() {
   runApp(const MyApp());
 }
 class MyApp extends StatelessWidget {
   const MyApp({super.key});
   @override
   widget build(BuildContext context) {
     return const MaterialApp(
       home: DemoPage(),
     );
   }
 }
 class DemoPage extends StatelessWidget {
   const DemoPage({super.key});
   void launchURL() {
     launchUrl(p.toUri('https://flutter.dev'));
   }
   @override
   widget build(BuildContext context) {
     return scaffold(
       body: center(
         child: ElevatedButton(
           onPressed: launchURL,
           child: const Text('Show flutter homepage'),
         ),
       ),
     );
   }
 }
<code_end>
run the app (or stop and restart it, if it was already running
before adding the plugin). click show flutter homepage.
you should see the default browser open on the device,
displaying the homepage for flutter.dev.
<topic_end>
<topic_start>
developing packages & plugins
<topic_end>
<topic_start>
package introduction
packages enable the creation of modular code that can be shared easily.
a minimal package consists of the following:
info note
  for a list of dos and don’ts when writing an effective plugin,
  see the medium article by mehmet fidanboylu,
  writing a good plugin.
<topic_end>
<topic_start>
package types
packages can contain more than one kind of content:
plugin packages can be written for android
(using kotlin or java), iOS (using swift or Objective-C),
web, macOS, windows, or linux, or any combination
thereof.
a concrete example is the url_launcher plugin package.
to see how to use the url_launcher package, and how it
was extended to implement support for web,
see the medium article by harry terkelsen,
how to write a flutter web plugin, part 1.
<topic_end>
<topic_start>
developing dart packages
the following instructions explain how to write a flutter
package.
<topic_end>
<topic_start>
step 1: create the package
to create a starter flutter package,
use the --template=package flag with flutter create:
this creates a package project in the hello
folder with the following content:
<topic_end>
<topic_start>
step 2: implement the package
for pure dart packages, simply add the functionality
inside the main lib/<package name>.dart file,
or in several files in the lib directory.
to test the package, add unit tests
in a test directory.
for additional details on how to organize the
package contents,
see the dart library package documentation.
<topic_end>
<topic_start>
developing plugin packages
if you want to develop a package that calls into
platform-specific APIs,
you need to develop a plugin package.
the API is connected to the platform-specific
implementation(s) using a platform channel.
<topic_end>
<topic_start>
federated plugins
federated plugins are a way of splitting support for
different platforms into separate packages.
so, a federated plugin can use one package for iOS,
another for android, another for web,
and yet another for a car (as an example of an IoT device).
among other benefits, this approach allows a domain expert
to extend an existing plugin to work for the platform they know best.
a federated plugin requires the following packages:
<topic_end>
<topic_start>
endorsed federated plugin
ideally, when adding a platform implementation to
a federated plugin, you will coordinate with the package
author to include your implementation.
in this way, the original author endorses your
implementation.
for example, say you write a foobar_windows
implementation for the (imaginary) foobar plugin.
in an endorsed plugin, the original foobar author
adds your windows implementation as a dependency
in the pubspec for the app-facing package.
then, when a developer includes the foobar plugin
in their flutter app, the windows implementation,
as well as the other endorsed implementations,
are automatically available to the app.
<topic_end>
<topic_start>
non-endorsed federated plugin
if you can’t, for whatever reason, get your implementation
added by the original plugin author, then your plugin
is not endorsed. a developer can still use your
implementation, but must manually add the plugin
to the app’s pubspec file. so, the developer
must include both the foobar dependency and
the foobar_windows dependency in order to achieve
full functionality.
for more information on federated plugins,
why they are useful, and how they are
implemented, see the medium article by harry terkelsen,
how to write a flutter web plugin, part 2.
<topic_end>
<topic_start>
specifying a plugin’s supported platforms
plugins can specify the platforms they support by
adding keys to the platforms map in the
pubspec.yaml file. for example,
the following pubspec file shows the
flutter: map for the hello plugin,
which supports only iOS and android:
when adding plugin implementations for more platforms,
the platforms map should be updated accordingly.
for example, here’s the map in the pubspec file
for the hello plugin,
when updated to add support for macOS and web:
<topic_end>
<topic_start>
federated platform packages
a platform package uses the same format,
but includes an implements entry indicating
which app-facing package it implements. for example,
a hello_windows plugin containing the windows
implementation for hello
would have the following flutter: map:
<topic_end>
<topic_start>
endorsed implementations
an app facing package can endorse a platform package by adding a
dependency on it, and including it as a default_package in the
platforms: map. if the hello plugin above endorsed hello_windows,
it would look as follows:
note that as shown here, an app-facing package can have
some platforms implemented within the package,
and others in endorsed federated implementations.
<topic_end>
<topic_start>
shared iOS and macOS implementations
many frameworks support both iOS and macOS with identical
or mostly identical APIs, making it possible to implement
some plugins for both iOS and macOS with the same codebase.
normally each platform’s implementation is in its own
folder, but the sharedDarwinSource option allows iOS
and macOS to use the same folder instead:
when sharedDarwinSource is enabled, instead of
an ios directory for iOS and a macos directory
for macOS, both platforms use a shared darwin
directory for all code and resources. when enabling
this option, you need to move any existing files
from ios and macos to the shared directory. you
also need to update the podspec file to set the
dependencies and deployment targets for both platforms,
for example:
<topic_end>
<topic_start>
step 1: create the package
to create a plugin package, use the --template=plugin
flag with flutter create.
use the --platforms= option followed by a
comma-separated list to specify the platforms
that the plugin supports. available platforms are:
android, ios, web, linux, macos, and windows.
if no platforms are specified, the
resulting project doesn’t support any platforms.
use the --org option to specify your organization,
using reverse domain name notation. this value is used
in various package and bundle identifiers in the
generated plugin code.
use the -a option to specify the language for android
or the -i option to specify the language for ios.
please choose one of the following:
this creates a plugin project in the hello folder
with the following specialized content:
by default, the plugin project uses swift for iOS code and
kotlin for android code. if you prefer Objective-C or java,
you can specify the iOS language using -i and the
android language using -a. for example:
<topic_end>
<topic_start>
step 2: implement the package
as a plugin package contains code for several platforms
written in several programming languages,
some specific steps are needed to ensure a smooth experience.
<topic_end>
<topic_start>
step 2a: define the package API (.dart)
the API of the plugin package is defined in dart code.
open the main hello/ folder in your favorite flutter editor.
locate the file lib/hello.dart.
<topic_end>
<topic_start>
step 2b: add android platform code (.kt/.java)
we recommend you edit the android code using android studio.
then use the following steps:
the android platform code of your plugin is located in
hello/java/com.example.hello/HelloPlugin.
you can run the example app from android studio by
pressing the run (▶) button.
<topic_end>
<topic_start>
step 2c: add iOS platform code (.swift/.h+.m)
we recommend you edit the iOS code using xcode.
before editing the iOS platform code in xcode,
first make sure that the code has been built at least once
(in other words, run the example app from your IDE/editor,
or in a terminal execute
cd hello/example; flutter build ios --no-codesign).
then use the following steps:
the iOS platform code for your plugin is located in
Pods/Development Pods/hello/../../example/ios/.symlinks/plugins/hello/ios/Classes
in the project navigator. (if you are using sharedDarwinSource,
the path will end with hello/darwin/Classes instead.)
you can run the example app by pressing the run (▶) button.
<topic_end>
<topic_start>
add CocoaPod dependencies
use the following instructions to add HelloPod with the version 0.0.1:
specify dependency at the end of ios/hello.podspec:
for private pods, refer to private CocoaPods to ensure repo access:
installing the plugin
the pod should appear in the installation summary.
<topic_end>
<topic_start>
step 2d: add linux platform code (.h+.cc)
we recommend you edit the linux code using an IDE with
c++ integration. the instructions below are for
visual studio code with the “c/c++” and “cmake” extensions
installed, but can be adjusted for other IDEs.
before editing the linux platform code in an IDE,
first make sure that the code has been built at least once
(in other words, run the example app from your flutter
IDE/editor, or in a terminal execute
cd hello/example; flutter build linux).
then use the following steps:
the linux platform code for your plugin is located in
flutter/ephemeral/.plugin_symlinks/hello/linux/.
you can run the example app using flutter run.
note: creating a runnable flutter application
on linux requires steps that are part of the flutter
tool, so even if your editor provides CMake
integration building and running that way won’t
work correctly.
<topic_end>
<topic_start>
step 2e: add macOS platform code (.swift)
we recommend you edit the macOS code using xcode.
before editing the macOS platform code in xcode,
first make sure that the code has been built at least once
(in other words, run the example app from your IDE/editor,
or in a terminal execute
cd hello/example; flutter build macos).
then use the following steps:
the macOS platform code for your plugin is located in
Pods/Development Pods/hello/../../example/macos/Flutter/ephemeral/.symlinks/plugins/hello/macos/Classes
in the project navigator. (if you are using sharedDarwinSource,
the path will end with hello/darwin/Classes instead.)
you can run the example app by pressing the run (▶) button.
<topic_end>
<topic_start>
step 2f: add windows platform code (.h+.cpp)
we recommend you edit the windows code using visual studio.
before editing the windows platform code in visual studio,
first make sure that the code has been built at least once
(in other words, run the example app from your IDE/editor,
or in a terminal execute
cd hello/example; flutter build windows).
then use the following steps:
the windows platform code for your plugin is located in
hello_plugin/Source files and hello_plugin/Header files in
the solution explorer.
you can run the example app by right-clicking hello_example in
the solution explorer and selecting set as startup project,
then pressing the run (▶) button. important: after
making changes to plugin code, you must select
build > build solution before running again, otherwise
an outdated copy of the built plugin will be run instead
of the latest version containing your changes.
<topic_end>
<topic_start>
step 2g: connect the API and the platform code
finally, you need to connect the API written in dart code with
the platform-specific implementations.
this is done using a platform channel,
or through the interfaces defined in a platform
interface package.
<topic_end>
<topic_start>
add support for platforms in an existing plugin project
to add support for specific platforms to an
existing plugin project, run flutter create with
the --template=plugin flag again in the project directory.
for example, to add web support in an existing plugin, run:
if this command displays a message about updating the
pubspec.yaml file, follow the provided instructions.
<topic_end>
<topic_start>
dart platform implementations
in many cases, non-web platform implementations only use the
platform-specific implementation language, as shown above. however,
platform implementations can also use platform-specific dart as well.
info note
  the examples below only apply to non-web platforms. web
  plugin implementations are always written in dart, and use
  pluginClass and fileName for their dart implementations
  as shown above.
<topic_end>
<topic_start>
dart-only platform implementations
in some cases, some platforms can be
implemented entirely in dart (for example, using FFI).
for a dart-only platform implementation on a platform other than web,
replace the pluginClass in pubspec.yaml with a dartPluginClass.
here is the hello_windows example above modified for a
dart-only implementation:
in this version you would have no c++ windows code, and would instead
subclass the hello plugin’s dart platform interface class with a
HelloPluginWindows class that includes a static
registerWith() method.  this method is called during startup,
and can be used to register the dart implementation:
<topic_end>
<topic_start>
hybrid platform implementations
platform implementations can also use both dart and a platform-specific
language. for example, a plugin could use a different platform channel
for each platform so that the channels can be customized per platform.
a hybrid implementation uses both of the registration systems
described above. here is the hello_windows example above modified for a
hybrid implementation:
the dart HelloPluginWindows class would use the registerWith()
shown above for dart-only implementations, while the c++ HelloPlugin
class would be the same as in a c++-only implementation.
<topic_end>
<topic_start>
testing your plugin
we encourage you test your plugin with automated tests
to ensure that functionality doesn’t regress
as you make changes to your code.
to learn more about testing your plugins,
check out testing plugins.
if you are writing tests for your flutter app
and plugins are causing crashes,
check out flutter in plugin tests.
<topic_end>
<topic_start>
developing FFI plugin packages
if you want to develop a package that calls into native APIs using
dart’s FFI, you need to develop an FFI plugin package.
both FFI plugin packages and (non-ffi) plugin packages support
bundling native code, but FFI plugin packages do not support
method channels and do include method channel registration code.
if you want to implement a plugin that uses both method channels
and FFI, use a (non-ffi) plugin. you can chose per platform to
use an FFI or (non-ffi) plugin.
FFI plugin packages were introduced in flutter 3.0, if you’re
targeting older flutter versions, you can use a (non-ffi) plugin.
<topic_end>
<topic_start>
step 1: create the package
to create a starter FFI plugin package,
use the --template=plugin_ffi flag with flutter create:
this creates an FFI plugin project in the hello
folder with the following specialized content:
lib: the dart code that defines the API of the plugin,
  and which calls into the native code using dart:ffi.
src: the native source code, and a CMakeLists.txt
  file for building that source code into a dynamic library.
platform folders (android, ios, windows, etc.): the
  build files for building and bundling the native code
  library with the platform application.
<topic_end>
<topic_start>
step 2: building and bundling native code
the pubspec.yaml specifies FFI plugins as follows:
this configuration invokes the native build
for the various target platforms and bundles
the binaries in flutter applications using these FFI plugins.
this can be combined with dartPluginClass,
such as when FFI is used for the
implementation of one platform in a federated plugin:
a plugin can have both FFI and method channels:
the native build systems that are invoked by FFI
(and method channels) plugins are:
<topic_end>
<topic_start>
step 3: binding to native code
to use the native code, bindings in dart are needed.
to avoid writing these by hand,
they are generated from the header file
(src/hello.h) by package:ffigen.
reference the ffigen docs for information
on how to install this package.
regenerate the bindings by running the following:
<topic_end>
<topic_start>
step 4: invoking native code
very short-running native functions can be directly
invoked from any isolate.
for an example, see sum in lib/hello.dart.
longer-running functions should be invoked on a
helper isolate to avoid dropping frames in
flutter applications.
for an example, see sumAsync in lib/hello.dart.
<topic_end>
<topic_start>
adding documentation
it is recommended practice to add the following documentation
to all packages:
<topic_end>
<topic_start>
API documentation
when you publish a package,
API documentation is automatically generated and
published to pub.dev/documentation.
for example, see the docs for device_info.
if you wish to generate API documentation locally on
your development machine, use the following commands:
change directory to the location of your package:
tell the documentation tool where the
    flutter SDK is located (change the following commands to reflect
    where you placed it):
run the dart doc tool
    (included as part of the flutter SDK), as follows:
for tips on how to write API documentation, see
effective dart documentation.
<topic_end>
<topic_start>
adding licenses to the LICENSE file
individual licenses inside each LICENSE file
should be separated by 80 hyphens
on their own on a line.
if a LICENSE file contains more than one
component license, then each component
license must start with the names of the
packages to which the component license applies,
with each package name on its own line,
and the list of package names separated from
the actual license text by a blank line.
(the packages need not match the names of
the pub package. for example, a package might itself contain
code from multiple third-party sources,
and might need to include a license for each one.)
the following example shows a well-organized license file:
here is another example of a well-organized license file:
here is an example of a poorly-organized license file:
another example of a poorly-organized license file:
<topic_end>
<topic_start>
publishing your package
lightbulb tip
  have you noticed that some of the packages and plugins
  on pub.dev are designated as flutter favorites?
  these are the packages published by verified developers
  and are identified as the packages and plugins you
  should first consider using when writing your app.
  to learn more,
  see the flutter favorites program.
once you have implemented a package, you can publish it on
pub.dev, so that other developers can easily use it.
prior to publishing, make sure to review the pubspec.yaml,
README.md, and CHANGELOG.md files to make sure their
content is complete and correct. also, to improve the
quality and usability of your package (and to make it
more likely to achieve the status of a flutter favorite),
consider including the following items:
next, run the publish command in dry-run mode
to see if everything passes analysis:
the next step is publishing to pub.dev,
but be sure that you are ready because
publishing is forever:
for more details on publishing, see the
publishing docs on dart.dev.
<topic_end>
<topic_start>
handling package interdependencies
if you are developing a package hello that depends on
the dart API exposed by another package, you need to add
that package to the dependencies section of your
pubspec.yaml file. the code below makes the dart API
of the url_launcher plugin available to hello:
you can now import 'package:url_launcher/url_launcher.dart'
and launch(someUrl) in the dart code of hello.
this is no different from how you include packages in
flutter apps or any other dart project.
but if hello happens to be a plugin package
whose platform-specific code needs access
to the platform-specific APIs exposed by url_launcher,
you also need to add suitable dependency declarations
to your platform-specific build files, as shown below.
<topic_end>
<topic_start>
android
the following example sets a dependency for
url_launcher in hello/android/build.gradle:
you can now import io.flutter.plugins.urllauncher.UrlLauncherPlugin
and access the UrlLauncherPlugin
class in the source code at hello/android/src.
for more information on build.gradle files, see the
gradle documentation on build scripts.
<topic_end>
<topic_start>
iOS
the following example sets a dependency for
url_launcher in hello/ios/hello.podspec:
you can now #import "urllauncherplugin.h" and
access the UrlLauncherPlugin class in the source code
at hello/ios/Classes.
for additional details on .podspec files, see the
CocoaPods documentation on them.
<topic_end>
<topic_start>
web
all web dependencies are handled by the pubspec.yaml
file like any other dart package.
<topic_end>
<topic_start>
flutter favorite program
the aim of the flutter favorite program is to identify
packages and plugins that you should first consider when
building your app.
this is not a guarantee of quality or suitability to your
particular situation—you should always perform your
own evaluation of packages and plugins for your project.
you can see the complete list of
flutter favorite packages on pub.dev.
info note
  if you came here looking for the happy paths recommendations,
  we have discontinued that project in favor of flutter favorites.
<topic_end>
<topic_start>
metrics
flutter favorite packages have passed high quality standards
using the following metrics:
<topic_end>
<topic_start>
flutter ecosystem  committee
the flutter ecosystem committee is comprised of flutter
team members and flutter community members spread
across its ecosystem.
one of their jobs is to decide when a package
has met the quality bar to become a flutter favorite.
the current committee members
(ordered alphabetically by last name)
are as follows:
if you’d like to nominate a package or plugin as a
potential future flutter favorite, or would like
to bring any other issues to the attention of the committee,
send the committee an email.
<topic_end>
<topic_start>
flutter favorite usage guidelines
flutter favorite packages are labeled as such on pub.dev
by the flutter team.
if you own a package that has been designated as a flutter favorite,
you must adhere to the following guidelines:
<topic_end>
<topic_start>
what’s next
you should expect the list of flutter favorite packages
to grow and change as the ecosystem continues to thrive.
the committee will continue working with package authors
to increase quality, as well as consider other areas of the
ecosystem that could benefit from the flutter favorite program,
such as tools, consulting firms, and prolific flutter contributors.
as the flutter ecosystem grows,
we’ll be looking at expanding the set of metrics,
which might include the following:
<topic_end>
<topic_start>
flutter favorites
you can see the complete list of
flutter favorite packages on pub.dev.
<topic_end>
<topic_start>
testing flutter apps
the more features your app has, the harder it is to test manually.
automated tests help ensure that your app performs correctly before
you publish it, while retaining your feature and bug fix velocity.
info note
  for hands-on practice of testing flutter apps, see the
  how to test a flutter app codelab.
automated testing falls into a few categories:
generally speaking, a well-tested app has many unit and widget tests,
tracked by code coverage, plus enough integration tests
to cover all the important use cases. this advice is based on
the fact that there are trade-offs between different kinds of testing,
seen below.
<topic_end>
<topic_start>
unit tests
a unit test tests a single function, method, or class.
the goal of a unit test is to verify the correctness of a
unit of logic under a variety of conditions.
external dependencies of the unit under test are generally
mocked out.
unit tests generally don’t read from or write
to disk, render to screen, or receive user actions from
outside the process running the test.
for more information regarding unit tests,
you can view the following recipes
or run flutter test --help in your terminal.
info note
  if you’re writing unit tests for code that
  uses plugins and you want to avoid crashes,
  check out plugins in flutter tests.
  if you want to test your flutter plugin,
  check out testing plugins.
<topic_end>
<topic_start>
recipes
an introduction to unit testing
mock dependencies using mockito
<topic_end>
<topic_start>
widget tests
a widget test (in other UI frameworks referred to as component test)
tests a single widget. the goal of a widget test is to verify that the
widget’s UI looks and interacts as expected. testing a widget involves
multiple classes and requires a test environment that provides the
appropriate widget lifecycle context.
for example, the widget being tested should be able to receive and
respond to user actions and events, perform layout, and instantiate child
widgets. a widget test is therefore more comprehensive than a unit test.
however, like a unit test, a widget test’s environment is replaced with
an implementation much simpler than a full-blown UI system.
<topic_end>
<topic_start>
recipes
an introduction to widget testing
find widgets
handle scrolling
tap, drag, and enter text
<topic_end>
<topic_start>
integration tests
an integration test tests a complete app or a large part of an app.
the goal of an integration test is to verify that all the widgets
and services being tested work together as expected.
furthermore, you can use integration
tests to verify your app’s performance.
generally, an integration test runs on a real device or an OS emulator,
such as iOS simulator or android emulator.
the app under test is typically isolated
from the test driver code to avoid skewing the results.
for more information on how to write integration tests, see the integration
testing page.
<topic_end>
<topic_start>
recipes
an introduction to integration testing
performance profiling
<topic_end>
<topic_start>
continuous integration services
continuous integration (ci) services allow you to run your
tests automatically when pushing new code changes.
this provides timely feedback on whether the code
changes work as expected and do not introduce bugs.
for information on running tests on various continuous
integration services, see the following:
<topic_end>
<topic_start>
an introduction to unit testing
how can you ensure that your app continues to work as you
add more features or change existing functionality?
by writing tests.
unit tests are handy for verifying the behavior of a single function,
method, or class. the test package provides the
core framework for writing unit tests, and the flutter_test
package provides additional utilities for testing widgets.
this recipe demonstrates the core features provided by the test package
using the following steps:
for more information about the test package,
see the test package documentation.
<topic_end>
<topic_start>
1. add the test dependency
the test package provides the core functionality for 
writing tests in dart. this is the best approach when
writing packages consumed by web, server, and flutter apps.
to add the test package as a dev dependency,
run flutter pub add:
<topic_end>
<topic_start>
2. create a test file
in this example, create two files: counter.dart and counter_test.dart.
the counter.dart file contains a class that you want to test and
resides in the lib folder. the counter_test.dart file contains
the tests themselves and lives inside the test folder.
in general, test files should reside inside a test folder
located at the root of your flutter application or package.
test files should always end with _test.dart,
this is the convention used by the test runner when searching for tests.
when you’re finished, the folder structure should look like this:
<topic_end>
<topic_start>
3. create a class to test
next, you need a “unit” to test. remember: “unit” is another name for a
function, method, or class. for this example, create a counter class
inside the lib/counter.dart file. it is responsible for incrementing
and decrementing a value starting at 0.
<code_start>
class counter {
  int value = 0;
  void increment() => value++;
  void decrement() => value--;
}
<code_end>
note: for simplicity, this tutorial does not follow the “test driven
development” approach. if you’re more comfortable with that style of
development, you can always go that route.
<topic_end>
<topic_start>
4. write a test for our class
inside the counter_test.dart file, write the first unit test. tests are
defined using the top-level test function, and you can check if the results
are correct by using the top-level expect function.
both of these functions come from the test package.
<code_start>
// import the test package and counter class
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
  test('Counter value should be incremented', () {
    final counter = counter();
    counter.increment();
    expect(counter.value, 1);
  });
}
<code_end>
<topic_end>
<topic_start>
5. combine multiple tests in a group
if you want to run a series of related tests,
use the flutter_test package group function to categorize the tests.
once put into a group, you can call flutter test on all tests in
that group with one command.
<code_start>
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
  group('Test start, increment, decrement', () {
    test('value should start at 0', () {
      expect(Counter().value, 0);
    });
    test('value should be incremented', () {
      final counter = counter();
      counter.increment();
      expect(counter.value, 1);
    });
    test('value should be decremented', () {
      final counter = counter();
      counter.decrement();
      expect(counter.value, -1);
    });
  });
}
<code_end>
<topic_end>
<topic_start>
6. run the tests
now that you have a counter class with tests in place,
you can run the tests.
<topic_end>
<topic_start>
run tests using IntelliJ or VSCode
the flutter plugins for IntelliJ and VSCode support running tests.
this is often the best option while writing tests because it provides the
fastest feedback loop as well as the ability to set breakpoints.
IntelliJ
VSCode
<topic_end>
<topic_start>
run tests in a terminal
to run the all tests from the terminal,
run the following command from the root of the project:
to run all tests you put into one group,
run the following command from the root of the project:
this example uses the group created in section 5.
to learn more about unit tests, you can execute this command:
<topic_end>
<topic_start>
mock dependencies using mockito
sometimes, unit tests might depend on classes that fetch data from live
web services or databases. this is inconvenient for a few reasons:
therefore, rather than relying on a live web service or database,
you can “mock” these dependencies. mocks allow emulating a live
web service or database and return specific results depending
on the situation.
generally speaking, you can mock dependencies by creating an alternative
implementation of a class. write these alternative implementations by
hand or make use of the mockito package as a shortcut.
this recipe demonstrates the basics of mocking with the
mockito package using the following steps:
for more information, see the mockito package documentation.
<topic_end>
<topic_start>
1. add the package dependencies
to use the mockito package, add it to the
pubspec.yaml file along with the flutter_test dependency in the
dev_dependencies section.
this example also uses the http package,
so define that dependency in the dependencies section.
mockito: 5.0.0 supports dart’s null safety thanks to code generation.
to run the required code generation, add the build_runner dependency
in the dev_dependencies section.
to add the dependencies, run flutter pub add:
<topic_end>
<topic_start>
2. create a function to test
in this example, unit test the fetchAlbum function from the
fetch data from the internet recipe.
to test this function, make two changes:
the function should now look like this:
<code_start>
Future<Album> fetchAlbum(http.Client client) async {
  final response = await client
      .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
<code_end>
in your app code, you can provide an http.Client to the fetchAlbum method 
directly with fetchAlbum(http.Client()). http.Client() creates a default
http.Client.
<topic_end>
<topic_start>
3. create a test file with a mock http.Client
next, create a test file.
following the advice in the introduction to unit testing recipe,
create a file called fetch_album_test.dart in the root test folder.
add the annotation @generatemocks([http.client]) to the main
function to generate a MockClient class with mockito.
the generated MockClient class implements the http.Client class.
this allows you to pass the MockClient to the fetchAlbum function,
and return different http responses in each test.
the generated mocks will be located in fetch_album_test.mocks.dart.
import this file to use them.
<code_start>
import 'package:http/http.dart' as http;
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';
// generate a MockClient using the mockito package.
// create new instances of this class in each test.
@generatemocks([http.client])
void main() {
}
<code_end>
next, generate the mocks running the following command:
<topic_end>
<topic_start>
4. write a test for each condition
the fetchAlbum() function does one of two things:
therefore, you want to test these two conditions.
use the MockClient class to return an “ok” response
for the success test, and an error response for the unsuccessful test.
test these conditions using the when() function provided by
mockito:
<code_start>
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'fetch_album_test.mocks.dart';
// generate a MockClient using the mockito package.
// create new instances of this class in each test.
@generatemocks([http.client])
void main() {
  group('fetchAlbum', () {
    test('returns an album if the http call completes successfully', () async {
      final client = MockClient();
      // use mockito to return a successful response when it calls the
      // provided http.Client.
      when(client
              .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
          .thenanswer((_) async =>
              http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
      expect(await fetchAlbum(client), isA<Album>());
    });
    test('throws an exception if the http call completes with an error', () {
      final client = MockClient();
      // use mockito to return an unsuccessful response when it calls the
      // provided http.Client.
      when(client
              .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
          .thenanswer((_) async => http.Response('Not found', 404));
      expect(fetchAlbum(client), throwsException);
    });
  });
}
<code_end>
<topic_end>
<topic_start>
5. run the tests
now that you have a fetchAlbum() function with tests in place,
run the tests.
you can also run tests inside your favorite editor by following the
instructions in the introduction to unit testing recipe.
<topic_end>
<topic_start>
complete example
<topic_end>
<topic_start>
lib/main.dart
<code_start>
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum(http.Client client) async {
  final response = await client
      .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  if (response.statuscode == 200) {
    // if the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    // if the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
class album {
  final int userId;
  final int id;
  final string title;
  const album({required this.userId, required this.id, required this.title});
  factory Album.fromJson(Map<String, dynamic> json) {
    return album(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as string,
    );
  }
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
  const MyApp({super.key});
  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  late final Future<Album> futureAlbum;
  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum(http.Client());
  }
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'fetch data example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: scaffold(
        appBar: AppBar(
          title: const Text('Fetch data example'),
        ),
        body: center(
          child: FutureBuilder<Album>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasdata) {
                return text(snapshot.data!.title);
              } else if (snapshot.haserror) {
                return text('${snapshot.error}');
              }
              // by default, show a loading spinner.
              return const CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
test/fetch_album_test.dart
<code_start>
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'fetch_album_test.mocks.dart';
// generate a MockClient using the mockito package.
// create new instances of this class in each test.
@generatemocks([http.client])
void main() {
  group('fetchAlbum', () {
    test('returns an album if the http call completes successfully', () async {
      final client = MockClient();
      // use mockito to return a successful response when it calls the
      // provided http.Client.
      when(client
              .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
          .thenanswer((_) async =>
              http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
      expect(await fetchAlbum(client), isA<Album>());
    });
    test('throws an exception if the http call completes with an error', () {
      final client = MockClient();
      // use mockito to return an unsuccessful response when it calls the
      // provided http.Client.
      when(client
              .get(uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
          .thenanswer((_) async => http.Response('Not found', 404));
      expect(fetchAlbum(client), throwsException);
    });
  });
}
<code_end>
<topic_end>
<topic_start>
summary
in this example, you’ve learned how to use mockito to test functions or classes
that depend on web services or databases. this is only a short introduction to
the mockito library and the concept of mocking. for more information,
see the documentation provided by the mockito package.
<topic_end>
<topic_start>
an introduction to widget testing
in the introduction to unit testing recipe,
you learned how to test dart classes using the test package.
to test widget classes, you need a few additional tools provided by the
flutter_test package, which ships with the flutter SDK.
the flutter_test package provides the following tools for
testing widgets:
if this sounds overwhelming, don’t worry. learn how all of these pieces fit
together throughout this recipe, which uses the following steps:
<topic_end>
<topic_start>
1. add the flutter_test dependency
before writing tests, include the flutter_test
dependency in the dev_dependencies section of the pubspec.yaml file.
if creating a new flutter project with the command line tools or
a code editor, this dependency should already be in place.
<topic_end>
<topic_start>
2. create a widget to test
next, create a widget for testing. for this recipe,
create a widget that displays a title and message.
<code_start>
class MyWidget extends StatelessWidget {
  const MyWidget({
    super.key,
    required this.title,
    required this.message,
  });
  final string title;
  final string message;
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'flutter demo',
      home: scaffold(
        appBar: AppBar(
          title: text(title),
        ),
        body: center(
          child: text(message),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
3. create a testWidgets test
with a widget to test, begin by writing your first test.
use the testWidgets() function provided by the
flutter_test package to define a test.
the testWidgets function allows you to define a
widget test and creates a WidgetTester to work with.
this test verifies that MyWidget displays a given title and message.
it is titled accordingly, and it will be populated in the next section.
<code_start>
void main() {
  // define a test. the TestWidgets function also provides a WidgetTester
  // to work with. the WidgetTester allows you to build and interact
  // with widgets in the test environment.
  testWidgets('MyWidget has a title and message', (tester) async {
    // test code goes here.
  });
}
<code_end>
<topic_end>
<topic_start>
4. build the widget using the WidgetTester
next, build MyWidget inside the test environment by using the
pumpWidget() method provided by WidgetTester.
the pumpWidget method builds and renders the provided widget.
create a MyWidget instance that displays “t” as the title
and “m” as the message.
<code_start>
void main() {
  testWidgets('MyWidget has a title and message', (tester) async {
    // create the widget by telling the tester to build it.
    await tester.pumpWidget(const MyWidget(title: 't', message: 'm'));
  });
}
<code_end>
<topic_end>
<topic_start>
notes about the pump() methods
after the initial call to pumpWidget(), the WidgetTester provides
additional ways to rebuild the same widget. this is useful if you’re
working with a StatefulWidget or animations.
for example, tapping a button calls setState(), but flutter won’t
automatically rebuild your widget in the test environment.
use one of the following methods to ask flutter to rebuild the widget.
info note
  to kick off the animation, you need to call pump()
  once (with no duration specified) to start the ticker.
  without it, the animation does not start.
these methods provide fine-grained control over the build lifecycle,
which is particularly useful while testing.
<topic_end>
<topic_start>
5. search for our widget using a finder
with a widget in the test environment, search
through the widget tree for the title and message
text widgets using a finder. this allows verification that
the widgets are being displayed correctly.
for this purpose, use the top-level find()
method provided by the flutter_test package to create the finders.
since you know you’re looking for text widgets, use the
find.text() method.
for more information about finder classes, see the
finding widgets in a widget test recipe.
<code_start>
void main() {
  testWidgets('MyWidget has a title and message', (tester) async {
    await tester.pumpWidget(const MyWidget(title: 't', message: 'm'));
    // create the finders.
    final titleFinder = find.text('T');
    final messageFinder = find.text('M');
  });
}
<code_end>
<topic_end>
<topic_start>
6. verify the widget using a matcher
finally, verify the title and message text widgets appear on screen
using the matcher constants provided by flutter_test.
matcher classes are a core part of the test package,
and provide a common way to verify a given
value meets expectations.
ensure that the widgets appear on screen exactly one time.
for this purpose, use the findsOneWidget matcher.
<code_start>
void main() {
  testWidgets('MyWidget has a title and message', (tester) async {
    await tester.pumpWidget(const MyWidget(title: 't', message: 'm'));
    final titleFinder = find.text('T');
    final messageFinder = find.text('M');
    // use the `findsonewidget` matcher provided by flutter_test to verify
    // that the text widgets appear exactly once in the widget tree.
    expect(titleFinder, findsOneWidget);
    expect(messageFinder, findsOneWidget);
  });
}
<code_end>
<topic_end>
<topic_start>
additional matchers
in addition to findsOneWidget, flutter_test provides additional
matchers for common cases.
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  // define a test. the TestWidgets function also provides a WidgetTester
  // to work with. the WidgetTester allows building and interacting
  // with widgets in the test environment.
  testWidgets('MyWidget has a title and message', (tester) async {
    // create the widget by telling the tester to build it.
    await tester.pumpWidget(const MyWidget(title: 't', message: 'm'));
    // create the finders.
    final titleFinder = find.text('T');
    final messageFinder = find.text('M');
    // use the `findsonewidget` matcher provided by flutter_test to
    // verify that the text widgets appear exactly once in the widget tree.
    expect(titleFinder, findsOneWidget);
    expect(messageFinder, findsOneWidget);
  });
}
class MyWidget extends StatelessWidget {
  const MyWidget({
    super.key,
    required this.title,
    required this.message,
  });
  final string title;
  final string message;
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: 'flutter demo',
      home: scaffold(
        appBar: AppBar(
          title: text(title),
        ),
        body: center(
          child: text(message),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
find widgets
to locate widgets in a test environment, use the finder
classes. while it’s possible to write your own finder classes,
it’s generally more convenient to locate widgets using the tools
provided by the flutter_test package.
during a flutter run session on a widget test, you can also
interactively tap parts of the screen for the flutter tool to
print the suggested finder.
this recipe looks at the find constant provided by
the flutter_test package, and demonstrates how
to work with some of the finders it provides.
for a full list of available finders,
see the CommonFinders documentation.
if you’re unfamiliar with widget testing and the role of
finder classes,
review the introduction to widget testing recipe.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. find a text widget
in testing, you often need to find widgets that contain specific text.
this is exactly what the find.text() method is for. it creates a
finder that searches for widgets that display a specific string of text.
<code_start>
testWidgets('finds a text widget', (tester) async {
  // build an app with a text widget that displays the letter 'h'.
  await tester.pumpWidget(const MaterialApp(
    home: scaffold(
      body: Text('H'),
    ),
  ));
  // find a widget that displays the letter 'h'.
  expect(find.text('H'), findsOneWidget);
});
<code_end>
<topic_end>
<topic_start>
2. find a widget with a specific key
in some cases, you might want to find a widget based on the key that has been
provided to it. this can be handy if displaying multiple instances of the
same widget. for example, a ListView might display several
text widgets that contain the same text.
in this case, provide a key to each widget in the list. this allows
an app to uniquely identify a specific widget, making it easier to find
the widget in the test environment.
<code_start>
testWidgets('finds a widget using a key', (tester) async {
  // define the test key.
  const testKey = Key('K');
  // build a MaterialApp with the testKey.
  await tester.pumpWidget(MaterialApp(key: testKey, home: container()));
  // find the MaterialApp widget using the testKey.
  expect(find.byKey(testKey), findsOneWidget);
});
<code_end>
<topic_end>
<topic_start>
3. find a specific widget instance
finally, you might be interested in locating a specific instance of a widget.
for example, this can be useful when creating widgets that take a child
property and you want to ensure you’re rendering the child widget.
<code_start>
testWidgets('finds a specific instance', (tester) async {
  const childWidget = padding(padding: EdgeInsets.zero);
  // provide the childWidget to the container.
  await tester.pumpWidget(Container(child: childWidget));
  // search for the childWidget in the tree and verify it exists.
  expect(find.byWidget(childWidget), findsOneWidget);
});
<code_end>
<topic_end>
<topic_start>
summary
the find constant provided by the flutter_test package provides
several ways to locate widgets in the test environment. this recipe
demonstrated three of these methods, and several more methods exist
for different purposes.
if the above examples do not work for a particular use-case,
see the CommonFinders documentation
to review all available methods.
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  testWidgets('finds a text widget', (tester) async {
    // build an app with a text widget that displays the letter 'h'.
    await tester.pumpWidget(const MaterialApp(
      home: scaffold(
        body: Text('H'),
      ),
    ));
    // find a widget that displays the letter 'h'.
    expect(find.text('H'), findsOneWidget);
  });
  testWidgets('finds a widget using a key', (tester) async {
    // define the test key.
    const testKey = Key('K');
    // build a MaterialApp with the testKey.
    await tester.pumpWidget(MaterialApp(key: testKey, home: container()));
    // find the MaterialApp widget using the testKey.
    expect(find.byKey(testKey), findsOneWidget);
  });
  testWidgets('finds a specific instance', (tester) async {
    const childWidget = padding(padding: EdgeInsets.zero);
    // provide the childWidget to the container.
    await tester.pumpWidget(Container(child: childWidget));
    // search for the childWidget in the tree and verify it exists.
    expect(find.byWidget(childWidget), findsOneWidget);
  });
}
<code_end>
<topic_end>
<topic_start>
handle scrolling
many apps feature lists of content,
from email clients to music apps and beyond.
to verify that lists contain the expected content
using widget tests,
you need a way to scroll through lists to search for particular items.
to scroll through lists via integration tests,
use the methods provided by the WidgetTester class,
which is included in the flutter_test package:
in this recipe, learn how to scroll through a list of items to
verify a specific widget is being displayed, and discuss the pros on cons of
different approaches.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. create an app with a list of items
this recipe builds an app that shows a long list of items.
to keep this recipe focused on testing, use the app created in the
work with long lists recipe.
if you’re unsure of how to work with long lists,
see that recipe for an introduction.
add keys to the widgets you want to interact with
inside the integration tests.
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp(
    items: List<String>.generate(10000, (i) => 'item $i'),
  ));
}
class MyApp extends StatelessWidget {
  final List<String> items;
  const MyApp({super.key, required this.items});
  @override
  widget build(BuildContext context) {
    const title = 'long list';
    return MaterialApp(
      title: title,
      home: scaffold(
        appBar: AppBar(
          title: const text(title),
        ),
        body: ListView.builder(
          // add a key to the ListView. this makes it possible to
          // find the list and scroll through it in the tests.
          key: const key('long_list'),
          itemCount: items.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: text(
                items[index],
                // add a key to the text widget for each item. this makes
                // it possible to look for a particular item in the list
                // and verify that the text is correct
                key: key('item_${index}_text'),
              ),
            );
          },
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
2. write a test that scrolls through the list
now, you can write a test. in this example, scroll through the list of items and
verify that a particular item exists in the list. the WidgetTester class
provides the scrollUntilVisible() method, which scrolls through a list
until a specific widget is visible. this is useful because the height of the
items in the list can change depending on the device.
rather than assuming that you know the height of all the items
in a list, or that a particular widget is rendered on all devices,
the scrollUntilVisible() method repeatedly scrolls through
a list of items until it finds what it’s looking for.
the following code shows how to use the scrollUntilVisible() method
to look through the list for a particular item. this code lives in a
file called test/widget_test.dart.
<code_start>
// this is a basic flutter widget test.
//
// to perform an interaction with a widget in your test, use the WidgetTester
// utility that flutter provides. for example, you can send tap and scroll
// gestures. you can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:scrolling/main.dart';
void main() {
  testWidgets('finds a deep item in a long list', (tester) async {
    // build our app and trigger a frame.
    await tester.pumpWidget(MyApp(
      items: List<String>.generate(10000, (i) => 'item $i'),
    ));
    final listFinder = find.byType(Scrollable);
    final itemFinder = find.byKey(const ValueKey('item_50_text'));
    // scroll until the item to be found appears.
    await tester.scrollUntilVisible(
      itemFinder,
      500.0,
      scrollable: listFinder,
    );
    // verify that the item contains the correct text.
    expect(itemFinder, findsOneWidget);
  });
}
<code_end>
<topic_end>
<topic_start>
3. run the test
run the test using the following command from the root of the project:
<topic_end>
<topic_start>
tap, drag, and enter text
many widgets not only display information, but also respond
to user interaction. this includes buttons that can be tapped,
and TextField for entering text.
to test these interactions, you need a way to simulate them
in the test environment. for this purpose, use the
WidgetTester library.
the WidgetTester provides methods for entering text,
tapping, and dragging.
in many cases, user interactions update the state of the app. in the test
environment, flutter doesn’t automatically rebuild widgets when the state
changes. to ensure that the widget tree is rebuilt after simulating a user
interaction, call the pump() or pumpAndSettle()
methods provided by the WidgetTester.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. create a widget to test
for this example,
create a basic todo app that tests three features:
to keep the focus on testing,
this recipe won’t provide a detailed guide on how to build the todo app.
to learn more about how this app is built,
see the relevant recipes:
<code_start>
class TodoList extends StatefulWidget {
  const TodoList({super.key});
  @override
  State<TodoList> createState() => _TodoListState();
}
class _TodoListState extends State<TodoList> {
  static const _appTitle = 'todo list';
  final todos = <string>[];
  final controller = TextEditingController();
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: _appTitle,
      home: scaffold(
        appBar: AppBar(
          title: const Text(_appTitle),
        ),
        body: column(
          children: [
            TextField(
              controller: controller,
            ),
            expanded(
              child: ListView.builder(
                itemCount: todos.length,
                itemBuilder: (context, index) {
                  final todo = todos[index];
                  return dismissible(
                    key: key('$todo$index'),
                    onDismissed: (direction) => todos.removeAt(index),
                    background: container(color: colors.red),
                    child: ListTile(title: text(todo)),
                  );
                },
              ),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              todos.add(controller.text);
              controller.clear();
            });
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
2. enter text in the text field
now that you have a todo app, begin writing the test.
start by entering text into the TextField.
accomplish this task by:
<code_start>
testWidgets('Add and remove a todo', (tester) async {
  // build the widget
  await tester.pumpWidget(const TodoList());
  // enter 'hi' into the TextField.
  await tester.enterText(find.byType(TextField), 'hi');
});
<code_end>
info note
  this recipe builds upon previous widget testing recipes.
  to learn the core concepts of widget testing,
  see the following recipes:
<topic_end>
<topic_start>
3. ensure tapping a button adds the todo
after entering text into the TextField, ensure that tapping
the FloatingActionButton adds the item to the list.
this involves three steps:
<code_start>
testWidgets('Add and remove a todo', (tester) async {
  // enter text code...
  // tap the add button.
  await tester.tap(find.byType(FloatingActionButton));
  // rebuild the widget after the state has changed.
  await tester.pump();
  // expect to find the item on screen.
  expect(find.text('hi'), findsOneWidget);
});
<code_end>
<topic_end>
<topic_start>
4. ensure swipe-to-dismiss removes the todo
finally, ensure that performing a swipe-to-dismiss action on the todo
item removes it from the list. this involves three steps:
<code_start>
testWidgets('Add and remove a todo', (tester) async {
  // enter text and add the item...
  // swipe the item to dismiss it.
  await tester.drag(find.byType(Dismissible), const offset(500, 0));
  // build the widget until the dismiss animation ends.
  await tester.pumpAndSettle();
  // ensure that the item is no longer on screen.
  expect(find.text('hi'), findsNothing);
});
<code_end>
<topic_end>
<topic_start>
complete example
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
  testWidgets('Add and remove a todo', (tester) async {
    // build the widget.
    await tester.pumpWidget(const TodoList());
    // enter 'hi' into the TextField.
    await tester.enterText(find.byType(TextField), 'hi');
    // tap the add button.
    await tester.tap(find.byType(FloatingActionButton));
    // rebuild the widget with the new item.
    await tester.pump();
    // expect to find the item on screen.
    expect(find.text('hi'), findsOneWidget);
    // swipe the item to dismiss it.
    await tester.drag(find.byType(Dismissible), const offset(500, 0));
    // build the widget until the dismiss animation ends.
    await tester.pumpAndSettle();
    // ensure that the item is no longer on screen.
    expect(find.text('hi'), findsNothing);
  });
}
class TodoList extends StatefulWidget {
  const TodoList({super.key});
  @override
  State<TodoList> createState() => _TodoListState();
}
class _TodoListState extends State<TodoList> {
  static const _appTitle = 'todo list';
  final todos = <string>[];
  final controller = TextEditingController();
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      title: _appTitle,
      home: scaffold(
        appBar: AppBar(
          title: const Text(_appTitle),
        ),
        body: column(
          children: [
            TextField(
              controller: controller,
            ),
            expanded(
              child: ListView.builder(
                itemCount: todos.length,
                itemBuilder: (context, index) {
                  final todo = todos[index];
                  return dismissible(
                    key: key('$todo$index'),
                    onDismissed: (direction) => todos.removeAt(index),
                    background: container(color: colors.red),
                    child: ListTile(title: text(todo)),
                  );
                },
              ),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            setState(() {
              todos.add(controller.text);
              controller.clear();
            });
          },
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
an introduction to integration testing
unit tests and widget tests are handy for testing individual classes,
functions, or widgets. however, they generally don’t test how
individual pieces work together as a whole, or capture the performance
of an application running on a real device. these tasks are performed
with integration tests.
integration tests are written using the integration_test package, provided
by the SDK.
in this recipe, learn how to test a counter app. it demonstrates
how to set up integration tests, how to verify specific text is displayed
by the app, how to tap specific widgets, and how to run integration tests.
this recipe uses the following steps:
<topic_end>
<topic_start>
1. create an app to test
first, create an app for testing. in this example,
test the counter app produced by the flutter create
command. this app allows a user to tap on a button
to increase a counter.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return const MaterialApp(
      title: 'counter app',
      home: MyHomePage(title: 'counter app home page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final string title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: text(widget.title),
      ),
      body: center(
        child: column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <widget>[
            const text(
              'you have pushed the button this many times:',
            ),
            text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // provide a key to this button. this allows finding this
        // specific button inside the test suite, and tapping it.
        key: const key('increment'),
        onPressed: _incrementCounter,
        tooltip: 'increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
2. add the integration_test dependency
next, use the integration_test and flutter_test packages
to write integration tests. add these dependencies to the dev_dependencies
section of the app’s pubspec.yaml file.
<topic_end>
<topic_start>
3. create the test files
create a new directory, integration_test, with an empty app_test.dart file:
<topic_end>
<topic_start>
4. write the integration test
now you can write tests. this involves three steps:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:introduction/main.dart';
void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  group('end-to-end test', () {
    testWidgets('tap on the floating action button, verify counter',
        (tester) async {
      // load app widget.
      await tester.pumpWidget(const MyApp());
      // verify the counter starts at 0.
      expect(find.text('0'), findsOneWidget);
      // finds the floating action button to tap on.
      final fab = find.byKey(const key('increment'));
      // emulate a tap on the floating action button.
      await tester.tap(fab);
      // trigger a frame.
      await tester.pumpAndSettle();
      // verify the counter increments by 1.
      expect(find.text('1'), findsOneWidget);
    });
  });
}
<code_end>
<topic_end>
<topic_start>
5. run the integration test
the process of running the integration tests varies depending on the platform
you are testing against. you can test against a mobile platform or the web.
<topic_end>
<topic_start>
5a. mobile
to test on a real iOS / android device, first connect the device and run the
following command from the root of the project:
or, you can specify the directory to run all integration tests:
this command runs the app and integration tests on the target device. for more
information, see the integration testing page.
<topic_end>
<topic_start>
5b. web
to get started testing in a web browser, download ChromeDriver.
next, create a new directory named test_driver containing a new file
named integration_test.dart:
<code_start>
import 'package:integration_test/integration_test_driver.dart';
future<void> main() => integrationDriver();
<code_end>
launch chromedriver as follows:
from the root of the project, run the following command:
for a headless testing experience, you can also run flutter drive 
with web-server as the target device identifier as follows:
<topic_end>
<topic_start>
integration testing
this page describes how to use the integration_test package to run
integration tests. tests written using this package have the following
properties:
info note
  the integration_test package is part of the flutter SDK itself.
  to use it, make sure that you update your app’s pubspec file
  to include this package as one of your dev_dependencies.
  for an example, see the project setup section below.
<topic_end>
<topic_start>
overview
unit tests, widget tests, and integration tests
there are three types of tests that flutter supports.
a unit test verifies the behavior of a method or class.
a widget test verifies the behavior of flutter widgets
without running the app itself. an integration test (also
called end-to-end testing or GUI testing) runs the full app.
hosts and targets
during development, you are probably writing the code
on a desktop computer, called the host machine,
and running the app on a mobile device, browser,
or desktop application, called the target device.
(if you are using a web
browser or desktop application,
the host machine is also the target device.)
integration_test
tests written with the integration_test package can:
migrating from flutter_driver
existing projects using flutter_driver can be migrated to
integration_test by following the migrating from flutter_drive
guide.
<topic_end>
<topic_start>
project setup
add integration_test and flutter_test to your pubspec.yaml file:
in your project, create a new directory
integration_test with a new file, <name>_test.dart:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:how_to/main.dart';
import 'package:integration_test/integration_test.dart';
void main() {
  testWidgets('tap on the floating action button, verify counter',
      (tester) async {
    // load app widget.
    await tester.pumpWidget(const MyApp());
    // verify the counter starts at 0.
    expect(find.text('0'), findsOneWidget);
    // finds the floating action button to tap on.
    final fab = find.byKey(const key('increment'));
    // emulate a tap on the floating action button.
    await tester.tap(fab);
    // trigger a frame.
    await tester.pumpAndSettle();
    // verify the counter increments by 1.
    expect(find.text('0'), findsNothing);
    expect(find.text('1'), findsOneWidget);
  });
}
<code_end>
info note
  only use testWidgets to declare your tests.
  otherwise, flutter could report errors incorrectly.
if you are looking for more examples, take a look at the testing_app of
the samples repository.
<topic_end>
<topic_start>
directory structure
see also:
<topic_end>
<topic_start>
running using the flutter command
these tests can be launched with the
flutter test command, where <device_id>:
is the optional device ID or pattern displayed
in the output of the flutter devices command:
this runs the tests in foo_test.dart. to run all tests in this directory on
the default device, run:
<topic_end>
<topic_start>
running in a browser
download and install ChromeDriver
and run it on port 4444:
to run tests with flutter drive, create a new directory containing a new file,
test_driver/integration_test.dart:
<code_start>
import 'package:integration_test/integration_test_driver.dart';
future<void> main() => integrationDriver();
<code_end>
then add IntegrationTestWidgetsFlutterBinding.ensureInitialized() in your
integration_test/<name>_test.dart file:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:how_to/main.dart';
import 'package:integration_test/integration_test.dart';
void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized(); // NEW
  testWidgets('tap on the floating action button, verify counter',
      (tester) async {
    // load app widget.
    await tester.pumpWidget(const MyApp());
    // verify the counter starts at 0.
    expect(find.text('0'), findsOneWidget);
    // finds the floating action button to tap on.
    final fab = find.byKey(const key('increment'));
    // emulate a tap on the floating action button.
    await tester.tap(fab);
    // trigger a frame.
    await tester.pumpAndSettle();
    // verify the counter increments by 1.
    expect(find.text('0'), findsNothing);
    expect(find.text('1'), findsOneWidget);
  });
}
<code_end>
in a separate process, run flutter_drive:
to learn more, see the
running flutter driver tests with web wiki page.
<topic_end>
<topic_start>
testing on firebase test lab
you can use the firebase test lab with both android
and iOS targets.
<topic_end>
<topic_start>
android setup
follow the instructions in the android device testing
section of the README.
<topic_end>
<topic_start>
iOS setup
follow the instructions in the iOS device testing
section of the README.
<topic_end>
<topic_start>
test lab project setup
go to the firebase console,
and create a new project if you don’t have one
already. then navigate to quality > test lab:
<topic_end>
<topic_start>
uploading an android APK
create an APK using gradle:
where <name>_test.dart is the file created in the
project setup section.
info note
  to use --dart-define with gradlew, you must base64 encode
  all parameters, and pass them to gradle in a comma separated list:
drag the “debug” APK from
<flutter_project_directory>/build/app/outputs/apk/debug
into the android robo test target on the web page.
this starts a robo test and allows you to run
other tests:
click run a test,
select the instrumentation test type and drag
the following two files:
if a failure occurs,
you can view the output by selecting the red icon:
<topic_end>
<topic_start>
uploading an android APK from the command line
see the firebase test lab section of the README
for instructions on uploading the APKs from the command line.
<topic_end>
<topic_start>
uploading xcode tests
see the firebase TestLab iOS instructions
for details on how to upload the .zip file
to the firebase TestLab section of the firebase console.
<topic_end>
<topic_start>
uploading xcode tests from the command line
see the iOS device testing section in the README
for instructions on how to upload the .zip file
from the command line.
<topic_end>
<topic_start>
performance profiling
when it comes to mobile apps, performance is critical to user experience.
users expect apps to have smooth scrolling and meaningful animations free of
stuttering or skipped frames, known as “jank.” how to ensure that your app
is free of jank on a wide variety of devices?
there are two options: first, manually test the app on different devices.
while that approach might work for a smaller app, it becomes more
cumbersome as an app grows in size. alternatively, run an integration
test that performs a specific task and records a performance timeline.
then, examine the results to determine whether a specific section of
the app needs to be improved.
in this recipe, learn how to write a test that records a performance
timeline while performing a specific task and saves a summary of the
results to a local file.
info note
  recording performance timelines isn’t supported on web.
  for performance profiling on web, see
  debugging performance for web apps
this recipe uses the following steps:
<topic_end>
<topic_start>
1. write a test that scrolls through a list of items
in this recipe, record the performance of an app as it scrolls through a
list of items. to focus on performance profiling, this recipe builds
on the scrolling recipe in widget tests.
follow the instructions in that recipe to create an app and write a test to
verify that everything works as expected.
<topic_end>
<topic_start>
2. record the performance of the app
next, record the performance of the app as it scrolls through the
list. perform this task using the traceAction()
method provided by the IntegrationTestWidgetsFlutterBinding class.
this method runs the provided function and records a timeline
with detailed information about the performance of the app. this example
provides a function that scrolls through the list of items,
ensuring that a specific item is displayed. when the function completes,
the traceAction() creates a report data map that contains the timeline.
specify the reportKey when running more than one traceAction.
by default all timelines are stored with the key timeline,
in this example the reportKey is changed to scrolling_timeline.
<code_start>
await binding.traceAction(
  () async {
    // scroll until the item to be found appears.
    await tester.scrollUntilVisible(
      itemFinder,
      500.0,
      scrollable: listFinder,
    );
  },
  reportKey: 'scrolling_timeline',
);
<code_end>
<topic_end>
<topic_start>
3. save the results to disk
now that you’ve captured a performance timeline, you need a way to review it.
the timeline object provides detailed information about all of the events
that took place, but it doesn’t provide a convenient way to review the results.
therefore, convert the timeline into a TimelineSummary.
the TimelineSummary can perform two tasks that make it easier
to review the results:
to capture the results, create a file named perf_driver.dart
in the test_driver folder and add the following code:
<code_start>
import 'package:flutter_driver/flutter_driver.dart' as driver;
import 'package:integration_test/integration_test_driver.dart';
future<void> main() {
  return integrationDriver(
    responseDataCallback: (data) async {
      if (data != null) {
        final timeline = driver.Timeline.fromJson(
          data['scrolling_timeline'] as Map<String, dynamic>,
        );
        // convert the timeline into a TimelineSummary that's easier to
        // read and understand.
        final summary = driver.TimelineSummary.summarize(timeline);
        // then, write the entire timeline to disk in a json format.
        // this file can be opened in the chrome browser's tracing tools
        // found by navigating to chrome://tracing.
        // optionally, save the summary to disk by setting includeSummary
        // to true
        await summary.writeTimelineToFile(
          'scrolling_timeline',
          pretty: true,
          includeSummary: true,
        );
      }
    },
  );
}
<code_end>
the integrationDriver function has a responseDataCallback 
which you can customize. 
by default, it writes the results to the integration_response_data.json file,
but you can customize it to generate a summary like in this example.
<topic_end>
<topic_start>
4. run the test
after configuring the test to capture a performance timeline and save a
summary of the results to disk, run the test with the following command:
the --profile option means to compile the app for the “profile mode” 
rather than the “debug mode”, so that the benchmark result is closer to 
what will be experienced by end users.
info note
  run the command with --no-dds when running on a mobile device or emulator.
  this option disables the dart development service (dds), which won’t
  be accessible from your computer.
<topic_end>
<topic_start>
5. review the results
after the test completes successfully, the build directory at the root of
the project contains two files:
<topic_end>
<topic_start>
summary example
<topic_end>
<topic_start>
complete example
integration_test/scrolling_test.dart
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:scrolling/main.dart';
void main() {
  final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  testWidgets('Counter increments smoke test', (tester) async {
    // build our app and trigger a frame.
    await tester.pumpWidget(MyApp(
      items: List<String>.generate(10000, (i) => 'item $i'),
    ));
    final listFinder = find.byType(Scrollable);
    final itemFinder = find.byKey(const ValueKey('item_50_text'));
    await binding.traceAction(
      () async {
        // scroll until the item to be found appears.
        await tester.scrollUntilVisible(
          itemFinder,
          500.0,
          scrollable: listFinder,
        );
      },
      reportKey: 'scrolling_timeline',
    );
  });
}
<code_end>
test_driver/perf_driver.dart
<code_start>
import 'package:flutter_driver/flutter_driver.dart' as driver;
import 'package:integration_test/integration_test_driver.dart';
future<void> main() {
  return integrationDriver(
    responseDataCallback: (data) async {
      if (data != null) {
        final timeline = driver.Timeline.fromJson(
          data['scrolling_timeline'] as Map<String, dynamic>,
        );
        // convert the timeline into a TimelineSummary that's easier to
        // read and understand.
        final summary = driver.TimelineSummary.summarize(timeline);
        // then, write the entire timeline to disk in a json format.
        // this file can be opened in the chrome browser's tracing tools
        // found by navigating to chrome://tracing.
        // optionally, save the summary to disk by setting includeSummary
        // to true
        await summary.writeTimelineToFile(
          'scrolling_timeline',
          pretty: true,
          includeSummary: true,
        );
      }
    },
  );
}
<code_end>
<topic_end>
<topic_start>
testing plugins
all of the usual types of flutter tests apply to
plugin packages as well, but because plugins contain
native code they often also require other kinds of tests
to test all of their functionality.
info note
  to learn how to test your plugin code, read on.
  to learn how to avoid crashes from a plugin when
  testing your flutter app, check out
  plugins in flutter tests.
<topic_end>
<topic_start>
types of plugin tests
to see examples of each of these types of tests, you can
create a new plugin from the plugin template
and look in the indicated directories.
dart unit tests and widget tests.
these tests allow you to test the dart portion of your plugin
just as you would test the dart code of a non-plugin package.
however, the plugin’s native code won’t be loaded,
so any calls to platform channels need to be mocked in tests.
see the test directory for an example.
dart integration tests.
since integration tests run in the context of a
flutter application (the example app),
they can test both the dart and native code,
as well as the interaction between them.
they are also useful for unit testing web implementation
code that needs to run in a browser.
these are often the most important tests for a plugin.
however, dart integration tests can’t interact with native UI,
such as native dialogs or the contents of platform views.
see the  example/integration_test directory for an example.
native unit tests.
just as dart unit tests can test the dart portions
of a plugin in isolation, native unit tests can
test the native parts in isolation.
each platform has its own native unit test system,
and the tests are written in the same native languages
as the code it is testing.
native unit tests can be especially valuable
if you need to mock out APIs wrapped by your plugin code,
which isn’t possible in a dart integration test.
you can set up and use any native test frameworks
you are familiar with for each platform,
but the following are already configured in the plugin template:
android:
JUnit tests can be found in android/src/test/.
iOS and macOS:
XCTest tests can be found in example/ios/RunnerTests/
and example/macos/RunnerTests/ respectively.
these are in the example directory,
not the top-level package directory,
because they are run via the example app’s project.
linux and windows:
GoogleTest tests can be found in linux/test/
and windows/test/, respectively.
other types of tests, which aren’t currently pre-configured
in the template, are native UI tests.
running your application under a native UI testing framework,
such as espresso or XCUITest,
enables tests that interact with both native and flutter UI elements,
so can be useful if your plugin can’t be tested without
native UI interactions.
<topic_end>
<topic_start>
running tests
<topic_end>
<topic_start>
dart unit tests
these can be run like any other flutter unit tests,
either from your preferred flutter IDE,
or using flutter test.
<topic_end>
<topic_start>
integration tests
for information on running this type of test, check out the
integration test documentation.
the commands must be run in the example directory.
<topic_end>
<topic_start>
native unit tests
for all platforms, you need to build the example
application at least once before running the unit tests,
to ensure that all of the platform-specific build
files have been created.
android JUnit
if you have the example opened as an android project
in android studio, you can run the unit tests using
the android studio test UI.
to run the tests from the command line,
use the following command in the example/android directory:
iOS and macOS XCTest
if you have the example app opened in xcode,
you can run the unit tests using the xcode test UI.
to run the tests from the command line,
use the following command in the example/ios (for iOS)
or example/macos (for macOS) directory:
for iOS tests, you might need to first open
runner.xcworkspace in xcode to configure code signing.
linux GoogleTest
to run the tests from the command line,
use the following command in the example directory,
replacing “my_plugin” with your plugin project name:
if you built the example app in release mode rather than
debug, replace “debug” with “release”.
windows GoogleTest
if you have the example app opened in visual studio,
you can run the unit tests using the visual studio test UI.
to run the tests from the command line,
use the following command in the example directory,
replacing “my_plugin” with your plugin project name:
if you built the example app in release mode rather
than debug, replace “debug” with “release”.
<topic_end>
<topic_start>
what types of tests to add
the general advice for testing flutter projects
applies to plugins as well.
some extra considerations for plugin testing:
since only integration tests can test the communication
between dart and the native languages,
try to have at least one integration test of each
platform channel call.
if some flows can’t be tested using integration
tests—for example if they require interacting with
native UI or mocking device state—consider writing
“end to end” tests of the two halves using unit tests:
native unit tests that set up the necessary mocks,
then call into the method channel entry point
with a synthesized call and validate the method response.
dart unit tests that mock the platform channel,
then call the plugin’s public API and validate the results.
<topic_end>
<topic_start>
plugins in flutter tests
info note
  to learn how to avoid crashes from a plugin when
  testing your flutter app, read on.
  to learn how to test your plugin code, check out
  testing plugins.
almost all flutter plugins have two parts:
in fact, the native (or host) language code distinguishes
a plugin package from a standard package.
building and registering the host portion of a plugin
is part of the flutter application build process,
so plugins only work when your code is running
in your application, such as with flutter run
or when running integration tests.
when running dart unit tests or
widget tests, the host code isn’t available.
if the code you are testing calls any plugins,
this often results in errors like the following:
info note
  plugin implementations that only use dart
  will work in unit tests. this is an implementation
  detail of the plugin, however,
  so tests shouldn’t rely on it.
when unit testing code that uses plugins,
there are several options to avoid this exception.
the following solutions are listed in order of preference.
<topic_end>
<topic_start>
wrap the plugin
in most cases, the best approach is to wrap plugin
calls in your own API,
and provide a way of mocking your own API in tests.
this has several advantages:
<topic_end>
<topic_start>
mock the plugin’s public API
if the plugin’s API is already based on class instances,
you can mock it directly, with the following caveats:
<topic_end>
<topic_start>
mock the plugin’s platform interface
if the plugin is a federated plugin,
it will include a platform interface that allows
registering implementations of its internal logic.
you can register a mock of that platform interface
implementation instead of the public API with the
following caveats:
an example of when this might be necessary is
mocking the implementation of a plugin used by
a package that you rely on,
rather than your own code,
so you can’t change how it’s called.
however, if possible,
you should mock the dependency that uses the plugin instead.
<topic_end>
<topic_start>
mock the platform channel
if the plugin uses platform channels,
you can mock the platform channels using
TestDefaultBinaryMessenger.
this should only be used if, for some reason,
none of the methods above are available,
as it has several drawbacks:
because of these limitations, TestDefaultBinaryMessenger
is mainly useful in the internal tests
of plugin implementations,
rather than tests of code using plugins.
you might also want to check out
testing plugins.
<topic_end>
<topic_start>
debugging flutter apps
there’s a wide variety of tools and features to help debug
flutter applications. here are some of the available tools:
<topic_end>
<topic_start>
other resources
you might find the following docs useful:
<topic_end>
<topic_start>
debug flutter apps from code
this guide describes which debugging features you can enable in your code.
for a full list of debugging and profiling tools, check out the
debugging page.
info note
  if you are looking for a way to use GDB to remotely debug the
  flutter engine running within an android app process,
  check out flutter_gdb.
<topic_end>
<topic_start>
add logging to your application
info note
  you can view logs in DevTools’ logging view
  or in your system console. this sections
  shows how to set up your logging statements.
you have two options for logging for your application.
import dart:io and invoking methods on
stderr and stdout. for example:
<code_start>
stderr.writeln('print me');
<code_end>
if you output too much at once, then android might discard some log lines.
to avoid this outcome,
use debugPrint() from flutter’s foundation library.
this wrapper around print throttles the output to avoid the android kernel
dropping output.
you can also log your app using the dart:developer log() function.
this allows you to include greater granularity and more information
in the logging output.
<topic_end>
<topic_start>
example 1
<code_start>
import 'dart:developer' as developer;
void main() {
  developer.log('log me', name: 'my.app.category');
  developer.log('log me 1', name: 'my.other.category');
  developer.log('log me 2', name: 'my.other.category');
}
<code_end>
you can also pass app data to the log call.
the convention for this is to use the error: named
parameter on the log() call, JSON encode the object
you want to send, and pass the encoded string to the
error parameter.
<topic_end>
<topic_start>
example 2
<code_start>
import 'dart:convert';
import 'dart:developer' as developer;
void main() {
  var myCustomObject = MyCustomObject();
  developer.log(
    'log me',
    name: 'my.app.category',
    error: jsonEncode(myCustomObject),
  );
}
<code_end>
DevTool’s logging view interprets the JSON encoded error parameter
as a data object.
DevTool renders in the details view for that log entry.
<topic_end>
<topic_start>
set breakpoints
you can set breakpoints in DevTools’ debugger or
in the built-in debugger of your IDE.
to set programmatic breakpoints:
insert programmatic breakpoints using the debugger() statement.
this statement takes an optional when argument.
this boolean argument sets a break when the given condition resolves to true.
example 3 illustrates this.
<topic_end>
<topic_start>
example 3
<code_start>
import 'dart:developer';
void someFunction(double offset) {
  debugger(when: offset > 30);
  // ...
}
<code_end>
<topic_end>
<topic_start>
debug app layers using flags
each layer of the flutter framework provides a function to dump its
current state or events to the console using the debugPrint property.
info note
  all of the following examples were run as macOS native apps on
  a MacBook pro m1. these will differ from any dumps your
  development machine prints.
lightbulb tip
  each render object in any tree includes the first five
  hexadecimal digits of its hashCode.
  this hash serves as a unique identifier for that render object.
<topic_end>
<topic_start>
print the widget tree
to dump the state of the widgets library,
call the debugDumpApp() function.
<topic_end>
<topic_start>
example 4: call debugDumpApp()
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: AppHome(),
    ),
  );
}
class AppHome extends StatelessWidget {
  const AppHome({super.key});
  @override
  widget build(BuildContext context) {
    return material(
      child: center(
        child: TextButton(
          onPressed: () {
            debugDumpApp();
          },
          child: const Text('Dump widget tree'),
        ),
      ),
    );
  }
}
<code_end>
this function recursively calls the toStringDeep() method starting with
the root of the widget tree. it returns a “flattened” tree.
example 4 produces the following widget tree. it includes:
many widgets that don’t appear in your app’s source.
the framework’s widgets’ build functions insert them during the build.
the following tree, for example, shows _InkFeatures.
that class implements part of the material widget.
it doesn’t appear anywhere in the code in example 4.
when the button changes from being pressed to being released,
this invokes the debugDumpApp() function.
it also coincides with the TextButton object calling setState()
and thus marking itself dirty.
this explains why a flutter marks a specific object as “dirty”.
when you review the widget tree, look for a line that resembles the following:
if you write your own widgets, override the
debugFillProperties() method to add information.
add DiagnosticsProperty objects to the method’s argument
and call the superclass method.
the toString method uses this function to fill in the widget’s description.
<topic_end>
<topic_start>
print the render tree
when debugging a layout issue, the widgets layer’s tree might lack detail.
the next level of debugging might require a render tree.
to dump the render tree:
<topic_end>
<topic_start>
example 5: call debugDumpRenderTree()
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: AppHome(),
    ),
  );
}
class AppHome extends StatelessWidget {
  const AppHome({super.key});
  @override
  widget build(BuildContext context) {
    return material(
      child: center(
        child: TextButton(
          onPressed: () {
            debugDumpRenderTree();
          },
          child: const Text('Dump render tree'),
        ),
      ),
    );
  }
}
<code_end>
when debugging layout issues, look at the size and constraints fields.
the constraints flow down the tree and the sizes flow back up.
in the render tree for example 5:
the RenderView, or window size, limits all render objects up to and
including RenderPositionedBox#dc1df render object
to the size of the screen.
this example sets the size to size(800.0, 600.0)
the constraints property of each render object limits the size
of each child. this property takes the BoxConstraints render object as a value.
starting with the RenderSemanticsAnnotations#fe6b5, the constraint equals
BoxConstraints(w=800.0, h=600.0).
the center widget created the RenderPositionedBox#dc1df render object
under the RenderSemanticsAnnotations#8187b subtree.
each child under this render object has BoxConstraints with both
minimum and maximum values. for example, RenderSemanticsAnnotations#a0a4b
uses BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0).
all children of the RenderPhysicalShape#8e171 render object use
BoxConstraints(BoxConstraints(56.0<=w<=800.0, 28.0<=h<=600.0)).
the child RenderPadding#8455f sets a padding value of
EdgeInsets(8.0, 0.0, 8.0, 0.0).
this sets a left and right padding of 8 to all subsequent children of
this render object.
they now have new constraints:
BoxConstraints(40.0<=w<=784.0, 28.0<=h<=600.0).
this object, which the creator field tells us is
probably part of the TextButton’s definition,
sets a minimum width of 88 pixels on its contents and a
specific height of 36.0. this is the TextButton class implementing
the material design guidelines regarding button dimensions.
RenderPositionedBox#80b8d render object loosens the constraints again
to center the text within the button.
the RenderParagraph#59bc2 render object picks its size based on
its contents.
if you follow the sizes back up the tree,
you see how the size of the text influences the width of all the boxes
that form the button.
all parents take their child’s dimensions to size themselves.
another way to notice this is by looking at the relayoutBoundary
attribute of in the descriptions of each box.
this tells you how many ancestors depend on this element’s size.
for example, the innermost RenderPositionedBox line has a relayoutBoundary=up13.
this means that when flutter marks the RenderConstrainedBox as dirty,
it also marks box’s 13 ancestors as dirty because the new dimensions
might affect those ancestors.
to add information to the dump if you write your own render objects,
override debugFillProperties().
add DiagnosticsProperty objects to the method’s argument
then call the superclass method.
<topic_end>
<topic_start>
print the layer tree
to debug a compositing issue, use debugDumpLayerTree().
<topic_end>
<topic_start>
example 6: call debugDumpLayerTree()
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: AppHome(),
    ),
  );
}
class AppHome extends StatelessWidget {
  const AppHome({super.key});
  @override
  widget build(BuildContext context) {
    return material(
      child: center(
        child: TextButton(
          onPressed: () {
            debugDumpLayerTree();
          },
          child: const Text('Dump layer tree'),
        ),
      ),
    );
  }
}
<code_end>
the RepaintBoundary widget creates:
a RenderRepaintBoundary RenderObject in the render tree
as shown in the example 5 results.
a new layer in the layer tree as shown in the example 6
results.
this reduces how much needs to be repainted.
<topic_end>
<topic_start>
print the focus tree
to debug a focus or shortcut issue, dump the focus tree
using the debugDumpFocusTree() function.
the debugDumpFocusTree() method returns the focus tree for the app.
the focus tree labels nodes in the following way:
if your app uses the focus widget, use the debugLabel
property to simplify finding its focus node in the tree.
you can also use the debugFocusChanges boolean property to enable
extensive logging when the focus changes.
<topic_end>
<topic_start>
example 7: call debugDumpFocusTree()
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(
    const MaterialApp(
      home: AppHome(),
    ),
  );
}
class AppHome extends StatelessWidget {
  const AppHome({super.key});
  @override
  widget build(BuildContext context) {
    return material(
      child: center(
        child: TextButton(
          onPressed: () {
            debugDumpFocusTree();
          },
          child: const Text('Dump focus tree'),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
print the semantics tree
the debugDumpSemanticsTree() function prints the semantic tree for the app.
the semantics tree is presented to the system accessibility APIs.
to obtain a dump of the semantics tree:
<topic_end>
<topic_start>
example 8: call debugDumpSemanticsTree()
<code_start>
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() {
  runApp(
    const MaterialApp(
      home: AppHome(),
    ),
  );
}
class AppHome extends StatelessWidget {
  const AppHome({super.key});
  @override
  widget build(BuildContext context) {
    return material(
      child: center(
        child: semantics(
          button: true,
          enabled: true,
          label: 'clickable text here!',
          child: GestureDetector(
              onTap: () {
                debugDumpSemanticsTree();
                if (kdebugmode) {
                  print('Clicked!');
                }
              },
              child: const Text('Click me!', style: TextStyle(fontSize: 56))),
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
print event timings
if you want to find out where your events happen relative to the frame’s
begin and end, you can set prints to log these events.
to print the beginning and end of the frames to the console,
toggle the debugPrintBeginFrameBanner
and the debugPrintEndFrameBanner.
the print frame banner log for example 1
to print the call stack causing the current frame to be scheduled,
use the debugPrintScheduleFrameStacks flag.
<topic_end>
<topic_start>
debug layout issues
to debug a layout problem using a GUI, set
debugPaintSizeEnabled to true.
this flag can be found in the rendering library.
you can enable it at any time and affects all painting while true.
consider adding it to the top of your void main() entry point.
<topic_end>
<topic_start>
example 9
see an example in the following code:
<code_start>
//add import to rendering library
import 'package:flutter/rendering.dart';
void main() {
  debugPaintSizeEnabled = true;
  runApp(const MyApp());
}
<code_end>
when enabled, flutter displays the following changes to your app:
the debugPaintBaselinesEnabled flag
does something similar but for objects with baselines.
the app displays the baseline for alphabetic characters in bright green
and the baseline for ideographic characters in orange.
alphabetic characters “sit” on the alphabetic baseline,
but that baseline “cuts” through the bottom of CJK characters.
flutter positions the ideographic baseline at the very bottom of the text line.
the debugPaintPointersEnabled flag turns on a special mode that
highlights any objects that you tap in teal.
this can help you determine if an object fails to hit test.
this might happen if the object falls outside the bounds of its parent
and thus not considered for hit testing in the first place.
if you’re trying to debug compositor layers, consider using the following flags.
use the debugPaintLayerBordersEnabled flag to find the boundaries
of each layer. this flag results in outlining each layer’s bounds in orange.
use the debugRepaintRainbowEnabled flag to display a repainted layer.
whenever a layer repaints, it overlays with a rotating set of colors.
any function or method in the flutter framework that starts with
debug... only works in debug mode.
<topic_end>
<topic_start>
debug animation issues
info note
  to debug animations with the least effort, slow them down.
  to slow down the animation,
  click slow animations in DevTools’ inspector view.
  this reduces the animation to 20% speed.
  if you want more control over the amount of slowness,
  use the following instructions.
set the timeDilation variable (from the scheduler
library) to a number greater than 1.0, for instance, 50.0.
it’s best to only set this once on app startup. if you
change it on the fly, especially if you reduce it while
animations are running, it’s possible that the framework
will observe time going backwards, which will probably
result in asserts and generally interfere with your efforts.
<topic_end>
<topic_start>
debug performance issues
info note
  you can achieve similar results to some of these debug
  flags using DevTools. some of the debug flags provide little benefit.
  if you find a flag with functionality you would like to add to DevTools,
  file an issue.
flutter provides a wide variety of top-level properties and functions
to help you debug your app at various points along the
development cycle.
to use these features, compile your app in debug mode.
the following list highlights some of flags and one function from the
rendering library for debugging performance issues.
to set these flags either:
you can generate stack traces on demand as well.
to print your own stack traces, add the debugPrintStack()
function to your app.
<topic_end>
<topic_start>
trace dart code performance
info note
  you can use the DevTools timeline events tab to perform traces.
  you can also import and export trace files into the timeline view,
  but only files generated by DevTools.
to perform custom performance traces and
measure wall or CPU time of arbitrary segments of dart code
like android does with systrace,
use dart:developer timeline utilities.
wrap the code you want to measure in timeline methods.
<code_start>
import 'dart:developer';
 void main() {
   Timeline.startSync('interesting function');
   // iWonderHowLongThisTakes();
   Timeline.finishSync();
 }
<code_end>
to ensure that the runtime performance characteristics closely match that
of your final product, run your app in profile mode.
<topic_end>
<topic_start>
add performance overlay
info note
  you can toggle display of the performance overlay on
  your app using the performance overlay button in the
  flutter inspector. if you prefer to do it in code,
  use the following instructions.
to enable the PerformanceOverlay widget in your code,
set the showPerformanceOverlay property to true on the
MaterialApp, CupertinoApp, or WidgetsApp
constructor:
<topic_end>
<topic_start>
example 10
<code_start>
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      showPerformanceOverlay: true,
      title: 'my awesome app',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'my awesome app'),
    );
  }
}
<code_end>
(if you’re not using MaterialApp, CupertinoApp,
or WidgetsApp, you can get the same effect by wrapping your
application in a stack and putting a widget on your stack that was
created by calling PerformanceOverlay.allEnabled().)
to learn how to interpret the graphs in the overlay,
check out the performance overlay in
profiling flutter performance.
<topic_end>
<topic_start>
add widget alignment grid
to add an overlay to a material design baseline grid on your app to
help verify alignments, add the debugShowMaterialGrid argument in the
MaterialApp constructor.
to add an overlay to non-Material applications, add a GridPaper widget.
<topic_end>
<topic_start>
use a native language debugger
info note
  this guide presumes you understand general debugging,
  have installed flutter and git, and have familiarity
  with the dart language as well as one of the following
  languages: java, kotlin, swift, or Objective-C.
if you write flutter apps only with dart code,
you can debug your code using your IDE’s debugger.
the flutter team recommends VS code.
if you write a platform-specific plugin or
use platform-specific libraries, you can debug
that portion of your code with a native debugger.
this guide shows you how you can connect two
debuggers to your dart app, one for dart, and one for the native code.
<topic_end>
<topic_start>
debug dart code
this guide describes how to use VS code to debug your flutter app.
you can also use your preferred IDE with the
flutter and dart plugins installed and configured.
<topic_end>
<topic_start>
debug dart code using VS code
the following procedure explains how to use the dart debugger
with the default sample flutter app.
the featured components in VS code work and appear when
debugging your own flutter project as well.
create a basic flutter app.
open the lib\main.dart file in the flutter app using
VS code.
click the bug icon
().
this opens the following panes in VS code:
the first time you run the debugger takes the longest.
test the debugger.
a. in main.dart, click on this line:
b. press shift + f9.
   this adds a breakpoint where the
   _counter variable increments.
c. in the app, click the + button
   to increment the counter. the app pauses.
d. at this point, VS code displays:
<topic_end>
<topic_start>
VS code flutter debugger
the flutter plugin for VS code adds a number of components
to the VS code user interface.
<topic_end>
<topic_start>
changes to VS code interface
when launched, the flutter debugger adds debugging tools to the
VS code interface.
the following screenshot and table explain the purpose of each tool.
to change where the panel (in orange) appears in VS code,
go to view > appearance > panel position.
<topic_end>
<topic_start>
VS code flutter debugging toolbar
the toolbar allows you to debug using any debugger.
you can step in, out, and over dart statements, hot reload, or resume the app.
<topic_end>
<topic_start>
update test flutter app
for the remainder of this guide, you need to update the
test flutter app. this update adds native code to debug.
open the lib/main.dart file using your preferred IDE.
replace the contents of main.dart with the following code.
<code_start>
// copyright 2023 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:flutter/material.dart';
 import 'package:url_launcher/url_launcher.dart';
 void main() {
   runApp(const MyApp());
 }
 class MyApp extends StatelessWidget {
   const MyApp({super.key});
   @override
   widget build(BuildContext context) {
     return MaterialApp(
       title: 'url launcher',
       theme: ThemeData(
         colorSchemeSeed: colors.purple,
         brightness: brightness.light,
       ),
       home: const MyHomePage(title: 'url launcher'),
     );
   }
 }
 class MyHomePage extends StatefulWidget {
   const MyHomePage({super.key, required this.title});
   final string title;
   @override
   State<MyHomePage> createState() => _MyHomePageState();
 }
 class _MyHomePageState extends State<MyHomePage> {
   future<void>? _launched;
   future<void> _launchInBrowser(Uri url) async {
     if (!await launchUrl(
       url,
       mode: LaunchMode.externalApplication,
     )) {
       throw Exception('Could not launch $url');
     }
   }
   future<void> _launchInWebView(Uri url) async {
     if (!await launchUrl(
       url,
       mode: LaunchMode.inAppWebView,
     )) {
       throw Exception('Could not launch $url');
     }
   }
   widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) {
     if (snapshot.haserror) {
       return Text('Error: ${snapshot.error}');
     } else {
       return const text('');
     }
   }
   @override
   widget build(BuildContext context) {
     final uri toLaunch = uri(
         scheme: 'https',
         host: 'docs.flutter.dev',
         path: 'testing/native-debugging');
     return scaffold(
       appBar: AppBar(
         title: text(widget.title),
       ),
       body: center(
         child: column(
           mainAxisAlignment: MainAxisAlignment.center,
           children: <widget>[
             padding(
               padding: const EdgeInsets.all(16),
               child: Text(toLaunch.toString()),
             ),
             FilledButton(
               onPressed: () => setState(() {
                 _launched = _launchInBrowser(toLaunch);
               }),
               child: const Text('Launch in browser'),
             ),
             const padding(padding: EdgeInsets.all(16)),
             FilledButton(
               onPressed: () => setState(() {
                 _launched = _launchInWebView(toLaunch);
               }),
               child: const Text('Launch in app'),
             ),
             const padding(padding: EdgeInsets.all(16.0)),
             FutureBuilder<void>(future: _launched, builder: _launchStatus),
           ],
         ),
       ),
     );
   }
 }
<code_end>
to add the url_launcher package as a dependency,
run flutter pub add:
to check what changed with the codebase:
in linux or macOS, run this find command.
in windows, run this command in the command prompt.
installing url_launcher added config files and code files
for all target platforms in the flutter app directory.
<topic_end>
<topic_start>
debug dart and native language code at the same time
this section explains how to debug the dart code in your flutter app
and any native code with its regular debugger.
this capability allows you to leverage flutter’s hot reload
when editing native code.
<topic_end>
<topic_start>
debug dart and android code using android studio
to debug native android code, you need a flutter app that contains
android code. in this section, you learn how to connect
the dart, java, and kotlin debuggers to your app.
you don’t need VS code to debug both dart and android code.
this guide includes the VS code instructions to be consistent
with the xcode and visual studio guides.
these section uses the same example flutter url_launcher app created
in update test flutter app.
info note
  if you want to use the GNU project debugger to debug the
  flutter engine running within an android app process,
  check out flutter_gdb.
<topic_end>
<topic_start>
build the android version of the flutter app in the terminal
to generate the needed android platform dependencies,
run the flutter build command.
<topic_end>
<topic_start>
start debugging with VS code first
if you use VS code to debug most of your code, start with this section.
to open the flutter app directory, go to
file >
open folder… and choose the my_app directory.
open the lib/main.dart file.
if you can build an app for more than one device,
you must select the device first.
go to
view >
command palette…
you can also press ctrl / cmd +
shift + p.
type flutter select.
click the flutter: select device command.
choose your target device.
click the debug icon
().
this opens the debug pane and launches the app.
wait for the app to launch on the device and for the debug pane to
indicate connected.
the debugger takes longer to launch the first time.
subsequent launches start faster.
this flutter app contains two buttons:
<topic_end>
<topic_start>
attach to the flutter process in android studio
click the attach debugger to android process button.
()
lightbulb tip
   if this button doesn’t appear in the projects menu bar, verify that
   you opened flutter application project but not a flutter plugin.
the process dialog displays one entry for each connected device.
select show all processes to display available processes for each
device.
choose the process to which you want to attach.
for this guide, select the com.example.my_app process
using the emulator Pixel_5_API_33.
locate the tab for android debugger in the debug pane.
in the project pane, expand
my_app_android >
android >
app >
src >
main >
java >
io.flutter plugins.
double click GeneratedProjectRegistrant to open the
java code in the edit pane.
at the end of this procedure, both the dart and android debuggers interact
with the same process.
use either, or both, to set breakpoints, examine stack, resume execution
and the like. in other words, debug!
<topic_end>
<topic_start>
start debugging with android studio first
if you use android studio to debug most of your code, start with this section.
to open the flutter app directory, go to
file >
open… and choose the my_app directory.
open the lib/main.dart file.
choose a virtual android device.
go to the toolbar, open the leftmost dropdown menu, and click on
open android emulator: <device>.
you can choose any installed emulator that’s doesn’t include arm64.
from that same menu, select the virtual android device.
from the toolbar, click run ‘main.dart’.
you can also press ctrl + shift + r.
after the app displays in the emulator, continue to the next step.
click the attach debugger to android process button.
()
lightbulb tip
   if this button doesn’t appear in the projects menu bar, verify that
   you opened flutter application project but not a flutter plugin.
the process dialog displays one entry for each connected device.
select show all processes to display available processes for each
device.
choose the process to which you want to attach.
for this guide, select the com.example.my_app process
using the emulator Pixel_5_API_33.
locate the tab for android debugger in the debug pane.
in the project pane, expand
my_app_android >
android >
app >
src >
main >
java >
io.flutter plugins.
double click GeneratedProjectRegistrant to open the
java code in the edit pane.
at the end of this procedure, both the dart and android debuggers interact
with the same process.
use either, or both, to set breakpoints, examine stack, resume execution
and the like. in other words, debug!
<topic_end>
<topic_start>
debug dart and iOS code using xcode
to debug iOS code, you need a flutter app that contains iOS code.
in this section, you learn to connect two debuggers to your app:
flutter via VS code and xcode. you need to run both VS code and xcode.
these section uses the same example flutter url_launcher app created
in update test flutter app.
<topic_end>
<topic_start>
build the iOS version of the flutter app in the terminal
to generate the needed iOS platform dependencies,
run the flutter build command.
<topic_end>
<topic_start>
start debugging with VS code first
if you use VS code to debug most of your code, start with this section.
<topic_end>
<topic_start>
start the dart debugger in VS code
to open the flutter app directory, go to
file >
open folder… and choose the my_app directory.
open the lib/main.dart file.
if you can build an app for more than one device,
you must select the device first.
go to
view >
command palette…
you can also press ctrl / cmd +
shift + p.
type flutter select.
click the flutter: select device command.
choose your target device.
click the debug icon
().
this opens the debug pane and launches the app.
wait for the app to launch on the device and for the debug pane to
indicate connected.
the debugger takes longer to launch the first time.
subsequent launches start faster.
this flutter app contains two buttons:
<topic_end>
<topic_start>
attach to the flutter process in xcode
to attach to the flutter app, go to
debug >
attach to process >
runner.
runner should be at the top of the attach to process menu
under the likely targets heading.
<topic_end>
<topic_start>
start debugging with xcode first
if you use xcode to debug most of your code, start with this section.
<topic_end>
<topic_start>
start the xcode debugger
open ios/Runner.xcworkspace from your flutter app directory.
select the correct device using the scheme menu in the toolbar.
if you have no preference, choose iPhone pro 14.
run this runner as a normal app in xcode.
when the run completes, the debug area at the bottom of xcode displays
 a message with the dart VM service URI. it resembles the following response:
copy the dart VM service URI.
<topic_end>
<topic_start>
attach to the dart VM in VS code
to open the command palette, go to
 view >
command palette…
you can also press cmd + shift + p.
type debug.
click the debug: attach to flutter on device command.
in the paste an VM service URI box, paste the URI you copied
 from xcode and press enter.
<topic_end>
<topic_start>
debug dart and macOS code using xcode
to debug macOS code, you need a flutter app that contains macOS code.
in this section, you learn to connect two debuggers to your app:
flutter via VS code and xcode. you need to run both VS code and xcode.
these section uses the same example flutter url_launcher app created
in update test flutter app.
<topic_end>
<topic_start>
build the macOS version of the flutter app in the terminal
to generate the needed macOS platform dependencies,
run the flutter build command.
<topic_end>
<topic_start>
start debugging with VS code first
<topic_end>
<topic_start>
start the debugger in VS code
to open the flutter app directory, go to
file >
open folder… and choose the my_app directory.
open the lib/main.dart file.
if you can build an app for more than one device,
you must select the device first.
go to
view >
command palette…
you can also press ctrl / cmd +
shift + p.
type flutter select.
click the flutter: select device command.
choose your target device.
click the debug icon
().
this opens the debug pane and launches the app.
wait for the app to launch on the device and for the debug pane to
indicate connected.
the debugger takes longer to launch the first time.
subsequent launches start faster.
this flutter app contains two buttons:
<topic_end>
<topic_start>
attach to the flutter process in xcode
to attach to the flutter app, go to
debug >
attach to process >
runner.
runner should be at the top of the attach to process menu
under the likely targets heading.
<topic_end>
<topic_start>
start debugging with xcode first
<topic_end>
<topic_start>
start the debugger in xcode
open macos/Runner.xcworkspace from your flutter app directory.
run this runner as a normal app in xcode.
when the run completes, the debug area at the bottom of xcode displays
a message with the dart VM service URI. it resembles the following response:
copy the dart VM service URI.
<topic_end>
<topic_start>
attach to the dart VM in VS code
to open the command palette, go to view > command palette…
you can also press cmd + shift + p.
type debug.
click the debug: attach to flutter on device command.
in the paste an VM service URI box, paste the URI you copied
from xcode and press enter.
<topic_end>
<topic_start>
debug dart and c++ code using visual studio
to debug c++ code, you need a flutter app that contains c++ code.
in this section, you learn to connect two debuggers to your app:
flutter via VS code and visual studio.
you need to run both VS code and visual studio.
these section uses the same example flutter url_launcher app created
in update test flutter app.
<topic_end>
<topic_start>
build the windows version of the flutter app in PowerShell or the command prompt
to generate the needed windows platform dependencies,
run the flutter build command.
<topic_end>
<topic_start>
start debugging with VS code first
if you use VS code to debug most of your code, start with this section.
<topic_end>
<topic_start>
start the debugger in VS code
to open the flutter app directory, go to
file >
open folder… and choose the my_app directory.
open the lib/main.dart file.
if you can build an app for more than one device,
you must select the device first.
go to
view >
command palette…
you can also press ctrl / cmd +
shift + p.
type flutter select.
click the flutter: select device command.
choose your target device.
click the debug icon
().
this opens the debug pane and launches the app.
wait for the app to launch on the device and for the debug pane to
indicate connected.
the debugger takes longer to launch the first time.
subsequent launches start faster.
this flutter app contains two buttons:
<topic_end>
<topic_start>
attach to the flutter process in visual studio
to open the project solution file, go to
file >
open >
Project/Solution…
you can also press ctrl + shift + o.
choose the build/windows/my_app.sln file in your flutter app directory.
go to debug > attach to process.
you can also press ctrl + alt + p.
from the attach to process dialog box, choose my_app.exe.
visual studio starts monitoring the flutter app.
<topic_end>
<topic_start>
start debugging with visual studio first
if you use visual studio to debug most of your code, start with this section.
<topic_end>
<topic_start>
start the local windows debugger
to open the project solution file, go to
file >
open >
Project/Solution…
you can also press ctrl + shift + o.
choose the build/windows/my_app.sln file in your flutter app directory.
set my_app as the startup project.
in the solution explorer, right-click on my_app and select
set as startup project.
click local windows debugger to start debugging.
you can also press f5.
when the flutter app has started, a console window displays
a message with the dart VM service URI. it resembles the following response:
copy the dart VM service URI.
<topic_end>
<topic_start>
attach to the dart VM in VS code
to open the command palette, go to
view >
command palette…
you can also press cmd + shift + p.
type debug.
click the debug: attach to flutter on device command.
in the paste an VM service URI box, paste the URI you copied
from visual studio and press enter.
<topic_end>
<topic_start>
resources
check out the following resources on debugging flutter, iOS, android,
macOS and windows:
<topic_end>
<topic_start>
flutter
<topic_end>
<topic_start>
android
you can find the following debugging resources on
developer.android.com.
<topic_end>
<topic_start>
iOS and macOS
you can find the following debugging resources on
developer.apple.com.
<topic_end>
<topic_start>
windows
you can find debugging resources on microsoft learn.
<topic_end>
<topic_start>
flutter's build modes
the flutter tooling supports three modes when compiling your app,
and a headless mode for testing.
you choose a compilation mode depending on where you are in
the development cycle. are you debugging your code? do you
need profiling information? are you ready to deploy your app?
a quick summary for when to use which mode is as follows:
the rest of the page details these modes.
<topic_end>
<topic_start>
debug
in debug mode, the app is set up for debugging on the physical
device, emulator, or simulator.
debug mode for mobile apps mean that:
debug mode for a web app means that:
by default, flutter run compiles to debug mode.
your IDE supports this mode. android studio,
for example, provides a run > debug… menu option,
as well as a green bug icon overlaid with a small triangle
on the project page.
info note
<topic_end>
<topic_start>
release
use release mode for deploying the app, when you want maximum
optimization and minimal footprint size. for mobile, release mode
(which is not supported on the simulator or emulator), means that:
release mode for a web app means that:
the command flutter run --release compiles to release mode.
your IDE supports this mode. android studio, for example,
provides a run > run… menu option, as well as a triangular
green run button icon on the project page.
you can compile to release mode for a specific target
with flutter build <target>. for a list of supported targets,
use flutter help build.
for more information, see the docs on releasing
iOS and android apps.
<topic_end>
<topic_start>
profile
in profile mode, some debugging ability is maintained—enough
to profile your app’s performance. profile mode is disabled on
the emulator and simulator, because their behavior is not representative
of real performance. on mobile, profile mode is similar to release mode,
with the following differences:
profile mode for a web app means that:
your IDE supports this mode. android studio, for example,
provides a run > profile… menu option.
the command flutter run --profile compiles to profile mode.
info note
  use the DevTools suite to profile your app’s performance.
for more information on the build modes, see
flutter’s build modes.
<topic_end>
<topic_start>
common flutter errors
<topic_end>
<topic_start>
introduction
this page explains several frequently-encountered flutter
framework errors (including layout errors) and gives suggestions
on how to resolve them.
this is a living document with more errors to be added in
future revisions, and your contributions are welcomed.
feel free to open an issue or submit a pull request to
make this page more useful to you and the flutter community.
<topic_end>
<topic_start>
‘a RenderFlex overflowed…’
RenderFlex overflow is one of the most frequently
encountered flutter framework errors,
and you’ve probably run into it already.
what does the error look like?
when it happens, yellow and black stripes appear,
indicating the area of overflow in the app UI.
in addition, an error message displays in the debug console:
how might you run into this error?
the error often occurs when a column or row has a
child widget that isn’t constrained in its size.
for example,
the code snippet below demonstrates a common scenario:
<code_start>
widget build(BuildContext context) {
  return row(
    children: [
      const Icon(Icons.message),
      column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Title', style: Theme.of(context).textTheme.headlineMedium),
          const text(
            'lorem ipsum dolor sit amet, consectetur adipiscing elit, sed '
            'do eiusmod tempor incididunt ut labore et dolore magna '
            'aliqua. ut enim ad minim veniam, quis nostrud '
            'exercitation ullamco laboris nisi ut aliquip ex ea '
            'commodo consequat.',
          ),
        ],
      ),
    ],
  );
}
<code_end>
in the above example,
the column tries to be wider than the space the row
(its parent) can allocate to it, causing an overflow error.
why does the column try to do that?
to understand this layout behavior, you need to know
how flutter framework performs layout:
“to perform layout, flutter walks the render tree in a depth-first traversal
and passes down size constraints from parent to child… children respond by
passing up a size to their parent object within the constraints the parent
established.” – flutter architectural overview
in this case, the row widget doesn’t constrain the
size of its children, nor does the column widget.
lacking constraints from its parent widget, the second
text widget tries to be as wide as all the characters
it needs to display. the self-determined width of the
text widget then gets adopted by the column, which
clashes with the maximum amount of horizontal space its parent,
the row widget, can provide.
how to fix it?
well, you need to make sure the column won’t attempt
to be wider than it can be. to achieve this,
you need to constrain its width. one way to do it is to
wrap the column in an expanded widget:
<code_start>
return const row(
  children: [
    Icon(Icons.message),
    expanded(
      child: column(
          // code omitted
          ),
    ),
  ],
);
<code_end>
another way is to wrap the column in a flexible widget
and specify a flex factor. in fact,
the expanded widget is equivalent to the flexible widget
with a flex factor of 1.0, as its source code shows.
to further understand how to use the flex widget in flutter layouts,
check out this 90-second widget of the week video
on the flexible widget.
further information:
the resources linked below provide further information about this error.
<topic_end>
<topic_start>
‘renderbox was not laid out’
while this error is pretty common,
it’s often a side effect of a primary error
occurring earlier in the rendering pipeline.
what does the error look like?
the message shown by the error looks like this:
how might you run into this error?
usually, the issue is related to violation of box constraints,
and it needs to be solved by providing more information
to flutter about how you’d like to constrain the widgets in question.
you can learn more about how constraints work
in flutter on the understanding constraints page.
the RenderBox was not laid out error is often
caused by one of two other errors:
<topic_end>
<topic_start>
‘vertical viewport was given unbounded height’
this is another common layout error you could run into
while creating a UI in your flutter app.
what does the error look like?
the message shown by the error looks like this:
how might you run into this error?
the error is often caused when a ListView
(or other kinds of scrollable widgets such as GridView)
is placed inside a column. a ListView takes all
the vertical space available to it,
unless it’s constrained by its parent widget.
however, a column doesn’t impose any constraint
on its children’s height by default.
the combination of the two behaviors leads to the failure of
determining the size of the ListView.
<code_start>
widget build(BuildContext context) {
  return center(
    child: column(
      children: <widget>[
        const Text('Header'),
        ListView(
          children: const <widget>[
            ListTile(
              leading: Icon(Icons.map),
              title: Text('Map'),
            ),
            ListTile(
              leading: Icon(Icons.subway),
              title: Text('Subway'),
            ),
          ],
        ),
      ],
    ),
  );
}
<code_end>
how to fix it?
to fix this error, specify how tall the ListView should be.
to make it as tall as the remaining space in the column,
wrap it using an expanded widget (as shown in the following example).
otherwise, specify an absolute height using a SizedBox
widget or a relative height using a flexible widget.
<code_start>
widget build(BuildContext context) {
  return center(
    child: column(
      children: <widget>[
        const Text('Header'),
        expanded(
          child: ListView(
            children: const <widget>[
              ListTile(
                leading: Icon(Icons.map),
                title: Text('Map'),
              ),
              ListTile(
                leading: Icon(Icons.subway),
                title: Text('Subway'),
              ),
            ],
          ),
        ),
      ],
    ),
  );
}
<code_end>
further information:
the resources linked below provide
further information about this error.
<topic_end>
<topic_start>
‘an InputDecorator…cannot have an unbounded width’
the error message suggests that it’s also related
to box constraints, which are important to understand
to avoid many of the most common flutter framework errors.
what does the error look like?
the message shown by the error looks like this:
how might you run into the error?
this error occurs, for example, when a row contains a
TextFormField or a TextField but the latter has
no width constraint.
<code_start>
widget build(BuildContext context) {
  return MaterialApp(
    home: scaffold(
      appBar: AppBar(
        title: const Text('Unbounded width of the TextField'),
      ),
      body: const row(
        children: [
          TextField(),
        ],
      ),
    ),
  );
}
<code_end>
how to fix it?
as suggested by the error message,
fix this error by constraining the text field
using either an expanded or SizedBox widget.
the following example demonstrates using an expanded widget:
<code_start>
widget build(BuildContext context) {
  return MaterialApp(
    home: scaffold(
      appBar: AppBar(
        title: const Text('Unbounded width of the TextField'),
      ),
      body: row(
        children: [
          expanded(child: TextFormField()),
        ],
      ),
    ),
  );
}
<code_end>
<topic_end>
<topic_start>
‘incorrect use of ParentData widget’
this error is about missing an expected parent widget.
what does the error look like?
the message shown by the error looks like this:
how might you run into the error?
while flutter’s widgets are generally flexible
in how they can be composed together in a UI,
a small subset of those widgets expect specific parent widgets.
when this expectation can’t be satisfied in your widget tree,
you’re likely to encounter this error.
here is an incomplete list of widgets that expect
specific parent widgets within the flutter framework.
feel free to submit a PR (using the doc icon in
the top right corner of the page) to expand this list.
how to fix it?
the fix should be obvious once you know
which parent widget is missing.
<topic_end>
<topic_start>
‘setstate called during build’
the build method in your flutter code isn’t
a good place to call setState,
either directly or indirectly.
what does the error look like?
when the error occurs,
the following message is displayed in the console:
how might you run into the error?
in general, this error occurs when the setState
method is called within the build method.
a common scenario where this error occurs is when
attempting to trigger a dialog from within the
build method. this is often motivated by the need to
immediately show information to the user,
but setState should never be called from a build method.
the following snippet seems to be a common culprit of this error:
<code_start>
widget build(BuildContext context) {
  // don't do this.
  showDialog(
      context: context,
      builder: (context) {
        return const AlertDialog(
          title: Text('Alert dialog'),
        );
      });
  return const center(
    child: column(
      children: <widget>[
        Text('Show material dialog'),
      ],
    ),
  );
}
<code_end>
this code doesn’t make an explicit call to setState,
but it’s called by showDialog.
the build method isn’t the right place to call
showDialog because build can be called by the
framework for every frame, for example, during an animation.
how to fix it?
one way to avoid this error is to use the navigator API
to trigger the dialog as a route. in the following example,
there are two pages. the second page has a
dialog to be displayed upon entry.
when the user requests the second page by
clicking a button on the first page,
the navigator pushes two routes–one
for the second page and another for the dialog.
<code_start>
class FirstScreen extends StatelessWidget {
  const FirstScreen({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(
        title: const Text('First screen'),
      ),
      body: center(
        child: ElevatedButton(
          child: const Text('Launch screen'),
          onPressed: () {
            // navigate to the second screen using a named route.
            Navigator.pushNamed(context, '/second');
            // immediately show a dialog upon loading the second screen.
            navigator.push(
              context,
              PageRouteBuilder(
                barrierDismissible: true,
                opaque: false,
                pageBuilder: (_, anim1, anim2) => const MyDialog(),
              ),
            );
          },
        ),
      ),
    );
  }
}
<code_end>
<topic_end>
<topic_start>
the ScrollController is attached to multiple scroll views
this error can occur when multiple scrolling
widgets (such as ListView) appear on the
screen at the same time. it’s more likely for
this error to occur on a web or desktop app,
than a mobile app since it’s rare to encounter
this scenario on mobile.
for more information and to learn how to fix,
check out the following video on
PrimaryScrollController:
<topic_end>
<topic_start>
references
to learn more about how to debug errors,
especially layout errors in flutter,
check out the following resources:
<topic_end>
<topic_start>
handling errors in flutter
the flutter framework catches errors that occur during callbacks
triggered by the framework itself, including errors encountered
during the build, layout, and paint phases. errors that don’t occur
within flutter’s callbacks can’t be caught by the framework,
but you can handle them by setting up an error handler on the
PlatformDispatcher.
all errors caught by flutter are routed to the
FlutterError.onError handler. by default,
this calls FlutterError.presentError,
which dumps the error to the device logs.
when running from an IDE, the inspector overrides this
behavior so that errors can also be routed to the IDE’s
console, allowing you to inspect the
objects mentioned in the message.
info note
  consider calling FlutterError.presentError
  from your custom error handler in order to see
  the logs in the console as well.
when an error occurs during the build phase,
the ErrorWidget.builder callback is
invoked to build the widget that is used
instead of the one that failed. by default,
in debug mode this shows an error message in red,
and in release mode this shows a gray background.
when errors occur without a flutter callback on the call stack,
they are handled by the PlatformDispatcher’s error callback. by default,
this only prints errors and does nothing else.
you can customize these behaviors,
typically by setting them to values in
your void main() function.
below each error type handling is explained. at the bottom
there’s a code snippet which handles all types of errors. even
though you can just copy-paste the snippet, we recommend you
to first get acquainted with each of the error types.
<topic_end>
<topic_start>
errors caught by flutter
for example, to make your application quit immediately any time an
error is caught by flutter in release mode, you could use the
following handler:
<code_start>
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
  FlutterError.onError = (details) {
    FlutterError.presentError(details);
    if (kreleasemode) exit(1);
  };
  runApp(const MyApp());
}
// rest of `flutter create` code...
<code_end>
info note
  the top-level kReleaseMode constant indicates
  whether the app was compiled in release mode.
this handler can also be used to report errors to a logging service.
for more details, see our cookbook chapter for
reporting errors to a service.
<topic_end>
<topic_start>
define a custom error widget for build phase errors
to define a customized error widget that displays whenever
the builder fails to build a widget, use MaterialApp.builder.
<code_start>
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, widget) {
        widget error = const text('...rendering error...');
        if (widget is scaffold || widget is navigator) {
          error = scaffold(body: center(child: error));
        }
        ErrorWidget.builder = (errordetails) => error;
        if (widget != null) return widget;
        throw StateError('widget is null');
      },
    );
  }
}
<code_end>
<topic_end>
<topic_start>
errors not caught by flutter
consider an onPressed callback that invokes an asynchronous function,
such as MethodChannel.invokeMethod (or pretty much any plugin).
for example:
<code_start>
OutlinedButton(
  child: const Text('Click me!'),
  onPressed: () async {
    const channel = MethodChannel('crashy-custom-channel');
    await channel.invokeMethod('blah');
  },
)
<code_end>
if invokeMethod throws an error, it won’t be forwarded to FlutterError.onError.
instead, it’s forwarded to the PlatformDispatcher.
to catch such an error, use PlatformDispatcher.instance.onError.
<code_start>
import 'package:flutter/material.dart';
import 'dart:ui';
void main() {
  MyBackend myBackend = MyBackend();
  PlatformDispatcher.instance.onError = (error, stack) {
    myBackend.sendError(error, stack);
    return true;
  };
  runApp(const MyApp());
}
<code_end>
<topic_end>
<topic_start>
handling all types of errors
say you want to exit application on any exception and to display
a custom error widget whenever a widget building fails - you can base
your errors handling on next code snippet:
<code_start>
import 'package:flutter/material.dart';
import 'dart:ui';
future<void> main() async {
  await myErrorsHandler.initialize();
  FlutterError.onError = (details) {
    FlutterError.presentError(details);
    myErrorsHandler.onErrorDetails(details);
  };
  PlatformDispatcher.instance.onError = (error, stack) {
    myErrorsHandler.onError(error, stack);
    return true;
  };
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      builder: (context, widget) {
        widget error = const text('...rendering error...');
        if (widget is scaffold || widget is navigator) {
          error = scaffold(body: center(child: error));
        }
        ErrorWidget.builder = (errordetails) => error;
        if (widget != null) return widget;
        throw StateError('widget is null');
      },
    );
  }
}
<code_end>
<topic_end>
<topic_start>
report errors to a service
while one always tries to create apps that are free of bugs,
they’re sure to crop up from time to time.
since buggy apps lead to unhappy users and customers,
it’s important to understand how often your users
experience bugs and where those bugs occur.
that way, you can prioritize the bugs with the
highest impact and work to fix them.
how can you determine how often your users experiences bugs?
whenever an error occurs, create a report containing the
error that occurred and the associated stacktrace.
you can then send the report to an error tracking
service, such as bugsnag, datadog,
firebase crashlytics, rollbar, or sentry.
the error tracking service aggregates all of the crashes your users
experience and groups them together. this allows you to know how often your
app fails and where the users run into trouble.
in this recipe, learn how to report errors to the
sentry crash reporting service using
the following steps:
<topic_end>
<topic_start>
1. get a DSN from sentry
before reporting errors to sentry, you need a “dsn” to uniquely identify
your app with the sentry.io service.
to get a DSN, use the following steps:
<topic_end>
<topic_start>
2. import the sentry package
import the sentry_flutter package into the app.
the sentry package makes it easier to send
error reports to the sentry error tracking service.
to add the sentry_flutter package as a dependency,
run flutter pub add:
<topic_end>
<topic_start>
3. initialize the sentry SDK
initialize the SDK to capture different unhandled errors automatically:
<code_start>
import 'package:flutter/widgets.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
future<void> main() async {
  await SentryFlutter.init(
    (options) => options.dsn = 'https://example@sentry.io/example',
    appRunner: () => runApp(const MyApp()),
  );
}
<code_end>
alternatively, you can pass the DSN to flutter using the dart-define tag:
<topic_end>
<topic_start>
what does that give me?
this is all you need for sentry to capture unhandled errors in dart and native layers.
this includes swift, Objective-C, c, and c++ on iOS, and java, kotlin, c, and c++ on android.
<topic_end>
<topic_start>
4. capture errors programmatically
besides the automatic error reporting that sentry generates by
importing and initializing the SDK,
you can use the API to report errors to sentry:
<code_start>
await Sentry.captureException(exception, stackTrace: stackTrace);
<code_end>
for more information, see the sentry API docs on pub.dev.
<topic_end>
<topic_start>
learn more
extensive documentation about using the sentry SDK can be found on sentry’s site.
<topic_end>
<topic_start>
complete example
to view a working example,
see the sentry flutter example app.
<topic_end>
<topic_start>
performance
flutter performance basics
info note
  if your app has a performance issue and you are
  trying to debug it, check out the DevTool’s page
  on using the performance view.
what is performance? why is performance important? how do i improve performance?
our goal is to answer those three questions (mainly the third one), and
anything related to them. this document should serve as the single entry
point or the root node of a tree of resources that addresses any questions
that you have about performance.
the answers to the first two questions are mostly philosophical,
and not as helpful to many developers who visit this page with specific
performance issues that need to be solved.
therefore, the answers to those
questions are in the appendix.
to improve performance, you first need metrics: some measurable numbers to
verify the problems and improvements.
in the metrics page,
you’ll see which metrics are currently used,
and which tools and APIs are available to get the metrics.
there is a list of frequently asked questions,
so you can find out if the questions you have or the problems you’re having
were already answered or encountered, and whether there are existing solutions.
(alternatively, you can check the flutter GitHub issue database using the
performance label.)
finally, the performance issues are divided into four categories. they
correspond to the four labels that are used in the flutter GitHub issue
database: “perf: speed”, “perf: memory”,
“perf: app size”, “perf: energy”.
the rest of the content is organized using those four categories.
<topic_end>
<topic_start>
speed
are your animations janky (not smooth)? learn how to
evaluate and fix rendering issues.
improving rendering performance
<topic_end>
<topic_start>
app size
how to measure your app’s size. the smaller the size,
the quicker it is to download.
measuring your app’s size
<topic_end>
<topic_start>
impeller rendering engine
<topic_end>
<topic_start>
what is impeller?
impeller provides a new rendering runtime for flutter.
the flutter team’s believes this solves flutter’s
early-onset jank issue.
impeller precompiles a smaller, simpler set of shaders
at engine build time so they don’t compile at runtime.
for a video introduction to impeller, check out the following
talk from google I/O 2023.
introducing impeller - flutter’s new rendering engine
impeller has the following objectives:
<topic_end>
<topic_start>
availability
where can you use impeller?
<topic_end>
<topic_start>
iOS
flutter enables impeller by default on iOS.
to disable impeller on iOS when debugging,
pass --no-enable-impeller to the flutter run command.
to disable impeller on iOS when deploying your app,
add the following tags under the top-level <dict> tag in your
app’s info.plist file.
the team continues to improve iOS support.
if you encounter performance or fidelity issues
with impeller on iOS, file an issue in the GitHub tracker.
prefix the issue title with [impeller] and
include a small reproducible test case.
<topic_end>
<topic_start>
macOS
impeller is available for macOS in preview as of
the flutter 3.13 stable release.
it continues to be in preview as of the 3.19 release.
to enable impeller on macOS when debugging,
pass --enable-impeller to the flutter run command.
to enable impeller on macOS when deploying your app,
add the following tags under the top-level <dict> tag in your
app’s info.plist file.
<topic_end>
<topic_start>
android
as of flutter 3.16, impeller is available behind
a flag on android devices that support vulkan.
it continues to be in preview as of the 3.19 release.
does your device support vulkan?
  you can determine whether your android device
  supports vulkan at checking for vulkan support.
you can try impeller on vulkan-capable android devices
by passing --enable-impeller to flutter run:
or, you can add the following setting to your project’s
AndroidManifest.xml file under the <application> tag:
<topic_end>
<topic_start>
bugs and issues
for the full list of impeller’s known bugs
and missing features,
the most up-to-date information is on the
impeller project board on GitHub.
the team continues to improve impeller support.
if you encounter performance or fidelity issues
with impeller on any platform,
file an issue in the GitHub tracker.
prefix the issue title with [impeller] and
include a small reproducible test case.
please include the following information when
submitting an issue for impeller:
<topic_end>
<topic_start>
architecture
to learn more details about impeller’s design and architecture,
check out the README.md file in the source tree.
<topic_end>
<topic_start>
additional information
<topic_end>
<topic_start>
performance best practices
info note
  to learn how to use the performance view
  (part of flutter DevTools)
  for debugging performance issues,
  see using the performance view.
generally, flutter applications are performant by default,
so you only need to avoid common pitfalls to get excellent
performance. these best practice recommendations will help you
write the most performant flutter app possible.
info note
  if you are writing web apps in flutter, you might be interested
  in a series of articles, written by the flutter material team,
  after they modified the flutter gallery app to make it more
  performant on the web:
how do you design a flutter app to most efficiently
render your scenes? in particular, how do you ensure
that the painting code generated by the
framework is as efficient as possible?
some rendering and layout operations are known
to be slow, but can’t always be avoided.
they should be used thoughtfully,
following the guidance below.
<topic_end>
<topic_start>
minimize expensive operations
some operations are more expensive than others,
meaning that they consume more resources.
obviously, you want to only use these operations
when necessary. how you design and implement your
app’s UI can have a big impact on how efficiently it runs.
<topic_end>
<topic_start>
control build() cost
here are some things to keep in mind when designing your UI:
for more information, check out:
<topic_end>
<topic_start>
use saveLayer() thoughtfully
some flutter code uses saveLayer(), an expensive operation,
to implement various visual effects in the UI.
even if your code doesn’t explicitly call saveLayer(),
other widgets or packages that you use might call it behind the scenes.
perhaps your app is calling saveLayer() more than necessary;
excessive calls to saveLayer() can cause jank.
<topic_end>
<topic_start>
why is saveLayer expensive?
calling saveLayer() allocates an offscreen buffer
and drawing content into the offscreen buffer might
trigger a render target switch.
the GPU wants to run like a firehose,
and a render target switch forces the GPU
to redirect that stream temporarily and then
direct it back again. on mobile GPUs this is
particularly disruptive to rendering throughput.
<topic_end>
<topic_start>
when is saveLayer required?
at runtime, if you need to dynamically display various shapes
coming from a server (for example), each with some transparency,
that might (or might not) overlap,
then you pretty much have to use saveLayer().
<topic_end>
<topic_start>
debugging calls to saveLayer
how can you tell how often your app calls saveLayer(),
either directly or indirectly?
the saveLayer() method triggers
an event on the DevTools timeline; learn when
your scene uses saveLayer by checking the
PerformanceOverlayLayer.checkerboardOffscreenLayers
switch in the DevTools performance view.
<topic_end>
<topic_start>
minimizing calls to saveLayer
can you avoid calls to saveLayer?
it might require rethinking of how you
create your visual effects:
note to package owners:
  as a best practice, consider providing documentation
  for when saveLayer might be necessary for your package,
  how it might be avoided, and when it can’t be avoided.
other widgets that might trigger saveLayer()
and are potentially costly:
<topic_end>
<topic_start>
minimize use of opacity and clipping
opacity is another expensive operation, as is clipping.
here are some tips you might find to be useful:
<topic_end>
<topic_start>
implement grids and lists thoughtfully
how your grids and lists are implemented
might be causing performance problems for your app.
this section describes an important best
practice when creating grids and lists,
and how to determine whether your app uses
excessive layout passes.
<topic_end>
<topic_start>
be lazy!
when building a large grid or list,
use the lazy builder methods, with callbacks.
that ensures that only the visible portion of the
screen is built at startup time.
for more information and examples, check out:
<topic_end>
<topic_start>
avoid intrinsics
for information on how intrinsic passes might be causing
problems with your grids and lists, see the next section.
<topic_end>
<topic_start>
minimize layout passes caused by intrinsic operations
if you’ve done much flutter programming, you are
probably familiar with how layout and constraints work
when creating your UI. you might even have memorized flutter’s
basic layout rule: constraints go down. sizes go up.
parent sets position.
for some widgets, particularly grids and lists,
the layout process can be expensive.
flutter strives to perform just one layout pass
over the widgets but, sometimes,
a second pass (called an intrinsic pass) is needed,
and that can slow performance.
<topic_end>
<topic_start>
what is an intrinsic pass?
an intrinsic pass happens when, for example,
you want all cells to have the size
of the biggest or smallest cell (or some
similar calculation that requires polling all cells).
for example, consider a large grid of cards.
a grid should have uniformly sized cells,
so the layout code performs a pass,
starting from the root of the grid (in the widget tree),
asking each card in the grid (not just the
visible cards) to return
its intrinsic size—the size
that the widget prefers, assuming no constraints.
with this information,
the framework determines a uniform cell size,
and re-visits all grid cells a second time,
telling each card what size to use.
<topic_end>
<topic_start>
debugging intrinsic passes
to determine whether you have excessive intrinsic passes,
enable the track layouts option
in DevTools (disabled by default),
and look at the app’s stack trace
to learn how many layout passes were performed.
once you enable tracking, intrinsic timeline events
are labeled as ‘$runtimetype intrinsics’.
<topic_end>
<topic_start>
avoiding intrinsic passes
you have a couple options for avoiding the intrinsic pass:
to dive even deeper into how layout works,
check out the layout and rendering
section in the flutter architectural overview.
<topic_end>
<topic_start>
build and display frames in 16ms
since there are two separate threads for building
and rendering, you have 16ms for building,
and 16ms for rendering on a 60hz display.
if latency is a concern,
build and display a frame in 16ms or less.
note that means built in 8ms or less,
and rendered in 8ms or less,
for a total of 16ms or less.
if your frames are rendering in well under
16ms total in profile mode,
you likely don’t have to worry about performance
even if some performance pitfalls apply,
but you should still aim to build and
render a frame as fast as possible. why?
if you are wondering why 60fps leads to a smooth visual experience,
check out the video why 60fps?
<topic_end>
<topic_start>
pitfalls
if you need to tune your app’s performance,
or perhaps the UI isn’t as smooth as you expect,
the DevTools performance view can help!
also, the flutter plugin for your IDE might
be useful. in the flutter performance window,
enable the show widget rebuild information check box.
this feature helps you detect when frames are
being rendered and displayed in more than 16ms.
where possible,
the plugin provides a link to a relevant tip.
the following behaviors might negatively impact
your app’s performance.
avoid using the opacity widget,
and particularly avoid it in an animation.
use AnimatedOpacity or FadeInImage instead.
for more information, check out
performance considerations for opacity animation.
when using an AnimatedBuilder,
avoid putting a subtree in the builder
function that builds widgets that don’t
depend on the animation. this subtree is
rebuilt for every tick of the animation.
instead, build that part of the subtree
once and pass it as a child to
the AnimatedBuilder. for more information,
check out performance optimizations.
avoid clipping in an animation.
if possible, pre-clip the image before animating it.
avoid using constructors with a concrete list
of children (such as column() or ListView())
if most of the children are not visible
on screen to avoid the build cost.
avoid overriding operator == on widget objects.
while it might seem like it would help by avoiding unnecessary rebuilds,
in practice it hurts performance because it results in O(N²) behavior.
the only exception to this rule is leaf widgets (widgets with no children),
in the specific case where comparing the properties of the widget
is likely to be significantly more efficient than rebuilding the widget
and where the widget will rarely change configuration.
even in such cases,
it is generally preferable to rely on caching the widgets,
because even one override of operator ==
can result in across-the-board performance degradation
as the compiler can no longer assume that the call is always static.
<topic_end>
<topic_start>
resources
for more performance info, check out the following resources:
<topic_end>
<topic_start>
measuring your app's size
many developers are concerned with the size of their compiled app.
as the APK, app bundle, or IPA version of a flutter app is
self-contained and holds all the code and assets needed to run the app,
its size can be a concern. the larger an app,
the more space it requires on a device,
the longer it takes to download,
and it might break the limit of useful
features like android instant apps.
<topic_end>
<topic_start>
debug builds are not representative
by default, launching your app with flutter run,
or by clicking the play button in your IDE
(as used in test drive and
write your first flutter app),
generates a debug build of the flutter app.
the app size of a debug build is large due to
the debugging overhead that allows for hot reload
and source-level debugging. as such, it is not representative of a production
app end users download.
<topic_end>
<topic_start>
checking the total size
a default release build, such as one created by flutter build apk or
flutter build ios, is built to conveniently assemble your upload package
to the play store and app store. as such, they’re also not representative of
your end-users’ download size. the stores generally reprocess and split
your upload package to target the specific downloader and the downloader’s
hardware, such as filtering for assets targeting the phone’s DPI, filtering
native libraries targeting the phone’s CPU architecture.
<topic_end>
<topic_start>
estimating total size
to get the closest approximate size on each platform, use the following
instructions.
<topic_end>
<topic_start>
android
follow the google play console’s instructions for checking app download and
install sizes.
produce an upload package for your application:
log into your google play console. upload your application binary by drag
dropping the .aab file.
view the application’s download and install size in the android vitals ->
app size tab.
the download size is calculated based on an XXXHDPI (~640dpi) device on an
arm64-v8a architecture. your end users’ download sizes might vary depending on
their hardware.
the top tab has a toggle for download size and install size. the page also
contains optimization tips further below.
<topic_end>
<topic_start>
iOS
create an xcode app size report.
first, by configuring the app version and build as described in the
iOS create build archive instructions.
then:
sign and export the IPA. the exported directory contains
app thinning size report.txt with details about your projected
application size on different devices and versions of iOS.
the app size report for the default demo app in flutter 1.17 shows:
in this example, the app has an approximate
download size of 5.4 MB and an approximate
installation size of 13.7 MB on an iPhone12,1 (model ID / hardware
number for iPhone 11)
and iPhone11,8 (iphone XR) running iOS 13.0.
to measure an iOS app exactly,
you have to upload a release IPA to apple’s
app store connect (instructions)
and obtain the size report from there.
IPAs are commonly larger than APKs as explained
in how big is the flutter engine?, a
section in the flutter FAQ.
<topic_end>
<topic_start>
breaking down the size
starting in flutter version 1.22 and DevTools version 0.9.1,
a size analysis tool is included to help developers understand the breakdown
of the release build of their application.
warning warning
  as stated in the checking total size section
  above, an upload package is not representative of your end users’ download
  size. be aware that redundant native library architectures and asset densities
  seen in the breakdown tool can be filtered by the play store and app store.
the size analysis tool is invoked by passing the --analyze-size flag when
building:
this build is different from a standard release build in two ways.
in addition to analyzing a single build, two builds can also be diffed by
loading two *-code-size-analysis_*.json files into DevTools. see
DevTools documentation for details.
through the summary, you can get a quick idea of the size usage per category
(such as asset, native code, flutter libraries, etc). the compiled dart
native library is further broken down by package for quick analysis.
warning warning
  this tool on iOS creates a .app rather than an IPA. use this tool to
  evaluate the relative size of the .app’s content. to get
  a closer estimate of the download size, reference the
  estimating total size section above.
<topic_end>
<topic_start>
deeper analysis in DevTools
the *-code-size-analysis_*.json file produced above can be further
analyzed in deeper detail in DevTools where a tree or a treemap view can
break down the contents of the application into the individual file level and
up to function level for the dart AOT artifact.
this can be done by flutter pub global run devtools, selecting
open app size tool and uploading the JSON file.
for further information on using the DevTools app size tool, see
DevTools documentation.
<topic_end>
<topic_start>
reducing app size
when building a release version of your app,
consider using the --split-debug-info tag.
this tag can dramatically reduce code size.
for an example of using this tag, see
obfuscating dart code.
some other things you can do to make your app smaller are:
<topic_end>
<topic_start>
deferred components
<topic_end>
<topic_start>
introduction
flutter has the capability to build apps that can
download additional dart code and assets at runtime.
this allows apps to reduce install apk size and download
features and assets when needed by the user.
we refer to each uniquely downloadable bundle of dart
libraries and assets as a “deferred component”.
to load these components, use dart’s deferred imports.
they can be compiled into split AOT and JavaScript shared libraries.
info note
  flutter supports deferred, or “lazy”, loading on android and the web.
  the implementations differ.
  android’s dynamic feature modules deliver the
  deferred components packaged as android modules.
  the web creates these components as separate *.js files.
  deferred code doesn’t impact other platforms,
  which continue to build as normal with all deferred
  components and assets included at initial install time.
though you can defer loading modules,
you must build the entire app and upload that app as a single
android app bundle (*.aab).
flutter doesn’t support dispatching partial updates without re-uploading
new android app bundles for the entire application.
flutter performs deferred loading when you compile your app
in release or profile mode.
debug mode treats all deferred components as regular imports.
the components are present at launch and load immediately.
this allows debug builds to hot reload.
for a deeper dive into the technical details of
how this feature works, see deferred components
on the flutter wiki.
<topic_end>
<topic_start>
how to set your project up for deferred components
the following instructions explain how to set up your
android app for deferred loading.
<topic_end>
<topic_start>
step 1: dependencies and initial project setup
add play core to the android app’s
    build.gradle dependencies.
    in android/app/build.gradle add the following:
if using the google play store as the
    distribution model for dynamic features,
    the app must support SplitCompat and provide an instance
    of a PlayStoreDeferredComponentManager.
    both of these tasks can be accomplished by setting
    the android:name property on the application in
    android/app/src/main/AndroidManifest.xml to
    io.flutter.embedding.android.FlutterPlayStoreSplitApplication:
io.flutter.app.FlutterPlayStoreSplitApplication handles
both of these tasks for you. if you use
FlutterPlayStoreSplitApplication,
you can skip to step 1.3.
if your android application
is large or complex, you might want to separately support
SplitCompat and provide the
PlayStoreDynamicFeatureManager manually.
to support SplitCompat, there are three methods
(as detailed in the android docs), any of which are valid:
make your application class extend
    SplitCompatApplication:
call SplitCompat.install(this);
    in the attachBaseContext() method:
declare SplitCompatApplication as the application
    subclass and add the flutter compatibility code from
  FlutterApplication to your application class:
the embedder relies on an injected
DeferredComponentManager instance to handle
install requests for deferred components.
provide a PlayStoreDeferredComponentManager into
the flutter embedder by adding the following code
to your app initialization:
opt into deferred components by adding
    the deferred-components entry to the app’s pubspec.yaml
    under the flutter entry:
the flutter tool looks for the deferred-components
  entry in the pubspec.yaml to determine whether the
  app should be built as deferred or not.
  this can be left empty for now unless you already
  know the components desired and the dart deferred libraries
  that go into each. you will fill in this section later
  in step 3.3 once gen_snapshot produces the loading units.
<topic_end>
<topic_start>
step 2: implementing deferred dart libraries
next, implement deferred loaded dart libraries in your
app’s dart code. the implementation does not need
to be feature complete yet. the example in the
rest of this page adds a new simple deferred widget
as a placeholder. you can also convert existing code
to be deferred by modifying the imports and
guarding usages of deferred code behind loadLibrary()
futures.
create a new dart library.
    for example, create a new DeferredBox widget that
    can be downloaded at runtime.
    this widget can be of any complexity but,
    for the purposes of this guide,
    create a simple box as a stand-in.
    to create a simple blue box widget,
    create box.dart with the following contents:
<code_start>
// box.dart
import 'package:flutter/material.dart';
/// a simple blue 30x30 box.
class DeferredBox extends StatelessWidget {
  const DeferredBox({super.key});
  @override
  widget build(BuildContext context) {
    return container(
      height: 30,
      width: 30,
      color: colors.blue,
    );
  }
}
<code_end>
import the new dart library
    with the deferred keyword in your app and
    call loadLibrary() (see lazily loading a library).
    the following example uses FutureBuilder
    to wait for the loadLibrary future (created in
    initState) to complete and display a
    CircularProgressIndicator as a placeholder.
    when the future completes, it returns the DeferredBox widget.
    SomeWidget can then be used in the app as normal and
    won’t ever attempt to access the deferred dart code until
    it has successfully loaded.
<code_start>
import 'package:flutter/material.dart';
import 'box.dart' deferred as box;
class SomeWidget extends StatefulWidget {
  const SomeWidget({super.key});
  @override
  State<SomeWidget> createState() => _SomeWidgetState();
}
class _SomeWidgetState extends State<SomeWidget> {
  late future<void> _libraryFuture;
  @override
  void initState() {
    super.initState();
    _libraryFuture = box.loadLibrary();
  }
  @override
  widget build(BuildContext context) {
    return FutureBuilder<void>(
      future: _libraryFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionstate == ConnectionState.done) {
          if (snapshot.haserror) {
            return Text('Error: ${snapshot.error}');
          }
          return box.DeferredBox();
        }
        return const CircularProgressIndicator();
      },
    );
  }
}
<code_end>
the loadLibrary() function returns a future<void>
that completes successfully when the code in the library
is available for use and completes with an error otherwise.
all usage of symbols from the deferred library should be
guarded behind a completed loadLibrary() call. all imports
of the library must be marked as deferred for it to be
compiled appropriately to be used in a deferred component.
if a component has already been loaded, additional calls
to loadLibrary() complete quickly (but not synchronously).
the loadLibrary() function can also be called early to
trigger a pre-load to help mask the loading time.
you can find another example of deferred import loading in
flutter gallery’s lib/deferred_widget.dart.
<topic_end>
<topic_start>
step 3: building the app
use the following flutter command to build a
deferred components app:
this command assists you by validating that your project
is properly set up to build deferred components apps.
by default, the build fails if the validator detects
any issues and guides you through suggested changes to fix them.
info note
  you can opt out of building deferred components
  with the --no-deferred-components flag.
  this flag causes all assets defined under
  deferred components to be treated as if they were
  defined under the assets section of pubspec.yaml.
  all dart code is compiled into a single shared library
  and loadLibrary() calls complete in the next event
  loop boundary (as soon as possible while being asynchronous).
  this flag is also equivalent to omitting the deferred-components:
  entry in pubspec.yaml.
the
    flutter build appbundle command
    runs the validator and attempts to build the app with
    gen_snapshot instructed to produce split AOT shared libraries
    as separate .so files. on the first run, the validator will
    likely fail as it detects issues; the tool makes
    recommendations for how to set up the project and fix these issues.
the validator is split into two sections: prebuild
and post-gen_snapshot validation. this is because any
validation referencing loading units cannot be performed
until gen_snapshot completes and produces a final set
of loading units.
info note
  you can opt to have the tool attempt to build your
  app without the validator by passing the
  --no-validate-deferred-components flag.
  this can result in unexpected and confusing
  instructions to resolve failures.
  this flag is meant to be used in
  custom implementations that do not rely on the default
  play-store-based implementation that the validator checks for.
the validator detects any new, changed, or removed
loading units generated by gen_snapshot.
the current generated loading units are tracked in your
<projectdirectory>/deferred_components_loading_units.yaml file.
this file should be checked into source control to ensure that
changes to the loading units by other developers can be caught.
the validator also checks for the following in the
android directory:
<projectdir>/android/app/src/main/res/values/strings.xml
    an entry for every deferred component mapping the key
    ${componentname}name to ${componentname}.
    this string resource is used by the AndroidManifest.xml
    of each feature module to define the dist:title property.
    for example:
<projectdir>/android/<componentname>
    an android dynamic feature module for
    each deferred component exists and contains a build.gradle
    and src/main/AndroidManifest.xml file.
    this only checks for existence and does not validate
    the contents of these files. if a file does not exist,
    it generates a default recommended one.
<projectdir>/android/app/src/main/res/values/androidmanifest.xml
    contains a meta-data entry that encodes
    the mapping between loading units and component name the
    loading unit is associated with. this mapping is used by the
    embedder to convert dart’s internal loading unit id
    to the name of a deferred component to install. for example:
the gen_snapshot validator won’t run until the prebuild
validator passes.
for each of these checks,
    the tool produces the modified or new files
    needed to pass the check.
    these files are placed in the
    <projectdir>/build/android_deferred_components_setup_files directory.
    it is recommended that the changes be applied by
    copying and overwriting the same files in the
    project’s android directory. before overwriting,
    the current project state should be committed to
    source control and the recommended changes should be
    reviewed to be appropriate. the tool won’t make any
    changes to your android/ directory automatically.
once the available
    loading units are generated and logged in
    <projectdirectory>/deferred_components_loading_units.yaml,
    it is possible to fully configure the pubspec’s
    deferred-components section so that the loading units
    are assigned to deferred components as desired.
    to continue with the box example, the generated
    deferred_components_loading_units.yaml file would contain:
the loading unit id (‘2’ in this case) is used
internally by dart, and can be ignored.
the base loading unit (id ‘1’) is not listed
and contains everything not explicitly contained
in another loading unit.
you can now add the following to pubspec.yaml:
to assign a loading unit to a deferred component,
add any dart lib in the loading unit into the
libraries section of the feature module.
keep the following guidelines in mind:
loading units should not be included
    in more than one component.
including one dart library from a
    loading unit indicates that the entire loading
    unit is assigned to the deferred component.
all loading units not assigned to
    a deferred component are included in the base component,
    which always exists implicitly.
loading units assigned to the same
    deferred component are downloaded, installed,
    and shipped together.
the base component is implicit and
    need not be defined in the pubspec.
assets can also be included by adding
    an assets section in the deferred component configuration:
an asset can be included in multiple deferred components,
but installing both components results in a replicated asset.
assets-only components can also be defined by omitting the
libraries section. these assets-only components must be
installed with the DeferredComponent utility class in
services rather than loadLibrary().
since dart libs are packaged together with assets,
if a dart library is loaded with loadLibrary(),
any assets in the component are loaded as well.
however, installing by component name and the services utility
won’t load any dart libraries in the component.
you are free to include assets in any component,
as long as they are installed and loaded when they
are first referenced, though typically,
assets and the dart code that uses those assets
are best packed in the same component.
manually add all deferred components
    that you defined in pubspec.yaml into the
    android/settings.gradle file as includes.
    for example, if there are three deferred components
    defined in the pubspec named, boxComponent, circleComponent,
    and assetComponent, ensure that android/settings.gradle
    contains the following:
repeat steps 3.1 through 3.6 (this step)
    until all validator recommendations are handled and the tool
    runs without further recommendations.
when successful, this command outputs an app-release.aab
file in build/app/outputs/bundle/release.
a successful build does not always mean the app was
built as intended. it is up to you to ensure that all loading
units and dart libraries are included in the way you intended.
for example, a common mistake is accidentally importing a
dart library without the deferred keyword,
resulting in a deferred library being compiled as part of
the base loading unit. in this case, the dart lib would
load properly because it is always present in the base,
and the lib would not be split off. this can be checked
by examining the deferred_components_loading_units.yaml
file to verify that the generated loading units are described
as intended.
when adjusting the deferred components configurations,
or making dart changes that add, modify, or remove loading units,
you should expect the validator to fail.
follow steps 3.1 through 3.6 (this step) to apply any
recommended changes to continue the build.
<topic_end>
<topic_start>
running the app locally
once your app has successfully built an .aab file,
use android’s bundletool to perform
local testing with the --local-testing flag.
to run the .aab file on a test device,
download the bundletool jar executable from
github.com/google/bundletool/releases and run:
where <your_app_project_dir> is the path to your app’s
project directory and <your_temp_dir> is any temporary
directory used to store the outputs of bundletool.
this unpacks your .aab file into an .apks file and
installs it on the device. all available android dynamic
features are loaded onto the device locally and
installation of deferred components is emulated.
before running build-apks again,
remove the existing app .apks file:
changes to the dart codebase require either incrementing
the android build ID or uninstalling and reinstalling
the app, as android won’t update the feature modules
unless it detects a new version number.
<topic_end>
<topic_start>
releasing to the google play store
the built .aab file can be uploaded directly to
the play store as normal. when loadLibrary() is called,
the needed android module containing the dart AOT lib and
assets is downloaded by the flutter engine using the
play store’s delivery feature.
<topic_end>
<topic_start>
improving rendering performance
info note
  to learn how to use the performance view
  (part of flutter DevTools)
  for debugging performance issues,
  see using the performance view.
rendering animations in your app is one of the most cited
topics of interest when it comes to measuring performance.
thanks in part to flutter’s skia engine and its ability
to quickly create and dispose of widgets,
flutter applications are performant by default,
so you only need to avoid common pitfalls to achieve
excellent performance.
<topic_end>
<topic_start>
general advice
if you see janky (non-smooth) animations, make
sure that you are profiling performance with an
app built in profile mode.
the default flutter build creates an app in debug mode,
which is not indicative of release performance.
for information,
see flutter’s build modes.
a couple common pitfalls:
for more information on evaluating performance
including information on common pitfalls,
see the following docs:
<topic_end>
<topic_start>
mobile-only advice
do you see noticeable jank on your mobile app, but only on
the first run of an animation? if so, see
reduce shader animation jank on mobile.
<topic_end>
<topic_start>
web-only advice
the following series of articles cover what the flutter material
team learned when improving performance of the flutter gallery
app on the web:
<topic_end>
<topic_start>
flutter performance profiling
info note
  to learn how to use the performance view
  (part of flutter DevTools)
  for debugging performance issues,
  see using the performance view.
<topic_end>
<topic_start>
what you'll learn
it’s been said that “a fast app is great,
but a smooth app is even better.”
if your app isn’t rendering smoothly,
how do you fix it? where do you begin?
this guide shows you where to start,
steps to take, and tools that can help.
info note
<topic_end>
<topic_start>
diagnosing performance problems
to diagnose an app with performance problems, you’ll enable
the performance overlay to look at the UI and raster threads.
(the raster thread was previously known as the GPU thread.)
before you begin, you want to make sure that you’re running in
profile mode, and that you’re not using an emulator.
for best results, you might choose the slowest device that
your users might use.
<topic_end>
<topic_start>
connect to a physical device
almost all performance debugging for flutter applications
should be conducted on a physical android or iOS device,
with your flutter application running in profile mode.
using debug mode, or running apps on simulators
or emulators, is generally not indicative of the final
behavior of release mode builds.
you should consider checking performance
on the slowest device that your users might reasonably use.
<topic_end>
<topic_start>
why you should run on a real device:
<topic_end>
<topic_start>
run in profile mode
flutter’s profile mode compiles and launches your application
almost identically to release mode, but with just enough additional
functionality to allow debugging performance problems.
for example, profile mode provides tracing information to the
profiling tools.
info note
  DevTools can’t connect to a flutter web app running
  in profile mode. use chrome DevTools to
  generate timeline events for a web app.
launch the app in profile mode as follows:
in VS code, open your launch.json file, and set the
flutterMode property to profile
(when done profiling, change it back to release or debug):
from the command line, use the --profile flag:
for more information on the different modes,
see flutter’s build modes.
you’ll begin by opening DevTools and viewing
the performance overlay, as discussed in the next section.
<topic_end>
<topic_start>
launch DevTools
DevTools provides features like profiling, examining the heap,
displaying code coverage, enabling the performance overlay,
and a step-by-step debugger.
DevTools’ timeline view allows you to investigate the
UI performance of your application on a frame-by-frame basis.
once your app is running in profile mode,
launch DevTools.
<topic_end>
<topic_start>
the performance overlay
the performance overlay displays statistics in two graphs
that show where time is being spent in your app. if the UI
is janky (skipping frames), these graphs help you figure out why.
the graphs display on top of your running app, but they aren’t
drawn like a normal widget—the flutter engine itself
paints the overlay and only minimally impacts performance.
each graph represents the last 300 frames for that thread.
this section describes how to enable the performance overlay
and use it to diagnose the cause of jank in your application.
the following screenshot shows the performance overlay running
on the flutter gallery example:
performance overlay showing the raster thread (top),
and UI thread (bottom).the vertical green bars
represent the current frame.
<topic_end>
<topic_start>
interpreting the graphs
the top graph (marked “gpu”) shows the time spent by 
the raster thread, the bottom one graph shows the time 
spent by the UI thread.
the white lines across the graphs show 16ms increments
along the vertical axis; if the graph ever goes over one
of these lines then you are running at less than 60hz.
the horizontal axis represents frames. the graph is
only updated when your application paints,
so if it’s idle the graph stops moving.
the overlay should always be viewed in profile mode,
since debug mode performance is intentionally sacrificed
in exchange for expensive asserts that are intended to aid
development, and thus the results are misleading.
each frame should be created and displayed within 1/60th of
a second (approximately 16ms). a frame exceeding this limit
(in either graph) fails to display, resulting in jank,
and a vertical red bar appears in one or both of the graphs.
if a red bar appears in the UI graph, the dart code is too
expensive. if a red vertical bar appears in the GPU graph,
the scene is too complicated to render quickly.
the vertical red bars indicate that the current frame is
expensive to both render and paint.When both graphs
display red, start by diagnosing the UI thread.
<topic_end>
<topic_start>
flutter’s threads
flutter uses several threads to do its work, though
only two of the threads are shown in the overlay.
all of your dart code runs on the UI thread.
although you have no direct access to any other thread,
your actions on the UI thread have performance consequences
on other threads.
the platform’s main thread. plugin code runs here.
    for more information, see the UIKit documentation for iOS,
    or the MainThread documentation for android.
    this thread is not shown in the performance overlay.
the UI thread executes dart code in the dart VM.
    this thread includes code that you wrote, and code executed by
    flutter’s framework on your app’s behalf.
    when your app creates and displays a scene, the UI thread creates
    a layer tree, a lightweight object containing device-agnostic
    painting commands, and sends the layer tree to the raster thread to
    be rendered on the device. don’t block this thread!
    shown in the bottom row of the performance overlay.
the raster thread takes the layer tree and displays
    it by talking to the GPU (graphic processing unit).
    you cannot directly access the raster thread or its data but,
    if this thread is slow, it’s a result of something you’ve done
    in the dart code. skia and impeller, the graphics libraries,
    run on this thread.
    shown in the top row of the performance overlay.
    this thread was previously known as the “gpu thread” because it
    rasterizes for the GPU. but it is running on the CPU.
    we renamed it to “raster thread” because many developers wrongly
    (but understandably)
    assumed the thread runs on the GPU unit.
performs expensive tasks (mostly I/O) that would
    otherwise block either the UI or raster threads.
    this thread is not shown in the performance overlay.
for links to more information and videos,
see the framework architecture on the
GitHub wiki, and the community article,
the layer cake.
<topic_end>
<topic_start>
displaying the performance overlay
you can toggle display of the performance overlay as follows:
<topic_end>
<topic_start>
using the flutter inspector
the easiest way to enable the PerformanceOverlay widget is
from the flutter inspector, which is available in the
inspector view in DevTools. simply click the
performance overlay button to toggle the overlay
on your running app.
<topic_end>
<topic_start>
from the command line
toggle the performance overlay using the p key from
the command line.
<topic_end>
<topic_start>
programmatically
to enable the overlay programmatically, see
performance overlay, a section in the
debugging flutter apps programmatically page.
<topic_end>
<topic_start>
identifying problems in the UI graph
if the performance overlay shows red in the UI graph,
start by profiling the dart VM, even if the GPU graph
also shows red.
<topic_end>
<topic_start>
identifying problems in the GPU graph
sometimes a scene results in a layer tree that is easy to construct,
but expensive to render on the raster thread. when this happens,
the UI graph has no red, but the GPU graph shows red.
in this case, you’ll need to figure out what your code is doing
that is causing rendering code to be slow. specific kinds of workloads
are more difficult for the GPU. they might involve unnecessary calls
to saveLayer, intersecting opacities with multiple objects,
and clips or shadows in specific situations.
if you suspect that the source of the slowness is during an animation,
click the slow animations button in the flutter inspector
to slow animations down by 5x.
if you want more control on the speed, you can also do this
programmatically.
is the slowness on the first frame, or on the whole animation?
if it’s the whole animation, is clipping causing the slow down?
maybe there’s an alternative way of drawing the scene that doesn’t
use clipping. for example, overlay opaque corners onto a square
instead of clipping to a rounded rectangle.
if it’s a static scene that’s being faded, rotated, or otherwise
manipulated, a RepaintBoundary might help.
<topic_end>
<topic_start>
checking for offscreen layers
the saveLayer method is one of the most expensive methods in
the flutter framework. it’s useful when applying post-processing
to the scene, but it can slow your app and should be avoided if
you don’t need it.  even if you don’t call saveLayer explicitly,
implicit calls might happen on your behalf. you can check whether
your scene is using saveLayer with the
PerformanceOverlayLayer.checkerboardOffscreenLayers switch.
once the switch is enabled, run the app and look for any images
that are outlined with a flickering box. the box flickers from
frame to frame if a new frame is being rendered.  for example,
perhaps you have a group of objects with opacities that are rendered
using saveLayer. in this case, it’s probably more performant to
apply an opacity to each individual widget, rather than a parent
widget higher up in the widget tree. the same goes for
other potentially expensive operations, such as clipping or shadows.
info note
  opacity, clipping, and shadows are not, in themselves,
  a bad idea. however, applying them to the top of the
  widget tree might cause extra calls to saveLayer,
  and needless processing.
when you encounter calls to saveLayer,
ask yourself these questions:
<topic_end>
<topic_start>
checking for non-cached images
caching an image with RepaintBoundary is good,
when it makes sense.
one of the most expensive operations,
from a resource perspective,
is rendering a texture using an image file.
first, the compressed image
is fetched from persistent storage.
the image is decompressed into host memory (gpu memory),
and transferred to device memory (ram).
in other words, image I/O can be expensive.
the cache provides snapshots of complex hierarchies so
they are easier to render in subsequent frames.
because raster cache entries are expensive to
construct and take up loads of GPU memory,
cache images only where absolutely necessary.
you can see which images are being cached by enabling the
PerformanceOverlayLayer.checkerboardRasterCacheImages switch.
run the app and look for images rendered with a randomly colored
checkerboard, indicating that the image is cached.
as you interact with the scene, the checkerboarded images
should remain constant—you don’t want to see flickering,
which would indicate that the cached image is being re-cached.
in most cases, you want to see checkerboards on static images,
but not on non-static images.  if a static image isn’t cached,
you can cache it by placing it into a RepaintBoundary
widget. though the engine might still ignore a repaint
boundary if it thinks the image isn’t complex enough.
<topic_end>
<topic_start>
viewing the widget rebuild profiler
the flutter framework is designed to make it hard to create
applications that are not 60fps and smooth. often, if you have jank,
it’s because there is a simple bug causing more of the UI to be
rebuilt each frame than required. the widget rebuild profiler
helps you debug and fix performance problems due to these sorts
of bugs.
you can view the widget rebuilt counts for the current screen and
frame in the flutter plugin for android studio and IntelliJ.
for details on how to do this, see show performance data
<topic_end>
<topic_start>
benchmarking
you can measure and track your app’s performance by writing
benchmark tests. the flutter driver library provides support
for benchmarking. using this integration test framework,
you can generate metrics to track the following:
tracking these benchmarks allows you to be informed when a
regression is introduced that adversely affects performance.
for more information, check out integration testing.
<topic_end>
<topic_start>
other resources
the following resources provide more information on using
flutter’s tools and debugging in flutter:
<topic_end>
<topic_start>
debugging performance for web apps
info note
  profiling flutter web apps requires flutter version 3.14 or later.
the flutter framework emits timeline events as it works to build frames,
draw scenes, and track other activity such as garbage collections.
these events are exposed in the 
chrome DevTools performance panel for debugging.
you can also emit your own timeline events using the dart:developer
timeline and TimelineTask APIs for further performance analysis.
<topic_end>
<topic_start>
optional flags to enhance tracing
to configure which timeline events are tracked, set any of the following top-level properties to true
in your app’s main method.
<topic_end>
<topic_start>
instructions
<topic_end>
<topic_start>
shader compilation jank
info note
  to learn how to use the performance view
  (part of flutter DevTools)
  for debugging performance issues,
  see using the performance view.
if the animations on your mobile app appear to be janky,
but only on the first run,
this is likely due to shader compilation.
flutter’s long term solution to
shader compilation jank is impeller,
which is in the stable release for iOS
and in preview behind a flag on android.
while we work on making impeller fully production ready,
you can mitigate shader compilation jank by bundling
precompiled shaders with an iOS app.
unfortunately, this approach doesn’t work well on android
due to precompiled shaders being device or GPU-specific.
the android hardware ecosystem is large enough that the
GPU-specific precompiled shaders bundled with an application
will work on only a small subset of devices,
and will likely make jank worse on the other devices,
or even create rendering errors.
also, note that we aren’t planning to make
improvements to the developer experience for creating
precompiled shaders described below. instead,
we are focusing our energies on the more robust
solution to this problem that impeller offers.
<topic_end>
<topic_start>
what is shader compilation jank?
a shader is a piece of code that runs on a
GPU (graphics processing unit).
when the skia graphics backend that flutter uses for rendering
sees a new sequence of draw commands for the first time,
it sometimes generates and compiles a
custom GPU shader for that sequence of commands.
this allows that sequence and potentially similar sequences
to render as fast as possible.
unfortunately, skia’s shader generation and compilation
happens in sequence with the frame workload.
the compilation could cost up to a few hundred milliseconds
whereas a smooth frame needs to be drawn within 16 milliseconds
for a 60 fps (frame-per-second) display.
therefore, a compilation could cause tens of frames
to be missed, and drop the fps from 60 to 6.
this is compilation jank.
after the compilation is complete,
the animation should be smooth.
on the other hand, impeller generates and compiles all
necessary shaders when we build the flutter engine.
therefore apps running on impeller already have
all the shaders they need, and the shaders can be used
without introducing jank into animations.
definitive evidence for the presence of shader compilation jank
is to set GrGLProgramBuilder::finalize in the tracing
with --trace-skia enabled.
the following screenshot shows an example timeline tracing.
<topic_end>
<topic_start>
what do we mean by “first run”?
on iOS, “first run” means that the user might see
jank when an animation first occurs every time
the user opens the app from scratch.
<topic_end>
<topic_start>
how to use SkSL warmup
flutter provides command line tools
for app developers to collect shaders that might be needed
for end-users in the SkSL (skia shader language) format.
the SkSL shaders can then be packaged into the app,
and get warmed up (pre-compiled) when an end-user first
opens the app, thereby reducing the compilation
jank in later animations.
use the following instructions to collect
and package the SkSL shaders:
run the app with --cache-sksl turned on
    to capture shaders in SkSL:
if the same app has been previously run
without --cache-sksl, then the
--purge-persistent-cache flag might be needed:
this flag removes older non-SkSL shader caches that
could interfere with SkSL shader capturing.
it also purges the SkSL shaders so use it only on the first
--cache-sksl run.
play with the app to trigger as many animations
    as needed; particularly those with compilation jank.
press m at the command line of flutter run to
    write the captured SkSL shaders into a file named something like
   flutter_01.sksl.json.
   for best results,
   capture SkSL shaders on an actual iOS device.
   a shader captured on a simulator isn’t likely to work correctly
   on actual hardware.
build the app with SkSL warm-up using the following,
    as appropriate:
if it’s built for a driver test like test_driver/app.dart,
make sure to also specify --target=test_driver/app.dart
(for example, flutter build ios --bundle-sksl-path
flutter_01.sksl.json --target=test_driver/app.dart).
test the newly built app.
alternatively, you can write some integration tests to
automate the first three steps using a single command.
for example:
with such integration tests,
you can easily and reliably get the
new SkSLs when the app code changes,
or when flutter upgrades.
such tests can also be used to verify the performance change
before and after the SkSL warm-up.
even better, you can put those tests into a
CI (continuous integration) system so the
SkSLs are generated and tested automatically over the lifetime of an app.
info note
  the integration_test package is now the recommended way
  to write integration tests. refer to the
  integration testing
  page for details.
take the original version of flutter gallery as an example.
the CI system is set up to generate SkSLs for every flutter commit,
and verifies the performance, in the transitions_perf_test.dart test.
for more details,
check out the flutter_gallery_sksl_warmup__transition_perf and
flutter_gallery_sksl_warmup__transition_perf_e2e_ios32 tasks.
the worst frame rasterization time is a useful metric from
such integration tests to indicate the severity of shader
compilation jank.
for instance,
the steps above reduce flutter gallery’s shader compilation
jank and speeds up its worst frame rasterization time on a
moto g4 from ~90 ms to ~40 ms. on iPhone 4s,
it’s reduced from ~300 ms to ~80 ms. that leads to the visual
difference as illustrated in the beginning of this article.
<topic_end>
<topic_start>
performance metrics
for a complete list of performance metrics flutter measures per commit, visit 
the following sites, click query, and filter the test and 
sub_result fields:
<topic_end>
<topic_start>
concurrency and isolates
all dart code runs in isolates,
which are similar to threads,
but differ in that isolates have their own isolated memory.
they do not share state in any way,
and can only communicate by messaging.
by default,
flutter apps do all of their work on a single isolate –
the main isolate.
in most cases, this model allows for simpler programming and
is fast enough that the application’s UI doesn’t become unresponsive.
sometimes though,
applications need to perform exceptionally large computations
that can cause “ui jank” (jerky motion).
if your app is experiencing jank for this reason,
you can move these computations to a helper isolate.
this allows the underlying runtime environment
to run the computation concurrently
with the main UI isolate’s work
and takes advantage of multi-core devices.
each isolate has its own memory
and its own event loop.
the event loop processes
events in the order that they’re added to an event queue.
on the main isolate,
these events can be anything from handling a user tapping in the UI,
to executing a function,
to painting a frame on the screen.
the following figure shows an example event queue
with 3 events waiting to be processed.
for smooth rendering,
flutter adds a “paint frame” event to the event queue
60 times per second(for a 60hz device).
if these events aren’t processed on time,
the application experiences UI jank,
or worse,
become unresponsive altogether.
whenever a process can’t be completed in a frame gap,
the time between two frames,
it’s a good idea to offload the work to another isolate
to ensure that the main isolate can produce 60 frames per second.
when you spawn an isolate in dart,
it can process the work concurrently with the main isolate,
without blocking it.
you can read more about how isolates
and the event loop work in dart on
the concurrency page of the dart
documentation.
<topic_end>
<topic_start>
common use cases for isolates
there is only one hard rule for when you should use isolates,
and that’s when large computations are causing your flutter application
to experience UI jank.
this jank happens when there is any computation that takes longer than
flutter’s frame gap.
any process could take longer to complete,
depending on the implementation
and the input data,
making it impossible to create an exhaustive list of
when you need to consider using isolates.
that said, isolates are commonly used for the following:
<topic_end>
<topic_start>
message passing between isolates
dart’s isolates are an implementation of the actor model.
they can only communicate with each other by message passing,
which is done with port objects.
when messages are “passed” between each other,
they are generally copied from the sending isolate to the
receiving isolate.
this means that any value passed to an isolate,
even if mutated on that isolate,
doesn’t change the value on the original isolate.
the only objects that aren’t copied when passed to an isolate
are immutable objects that can’t be changed anyway,
such a string or an unmodifiable byte.
when you pass an immutable object between isolates,
a reference to that object is sent across the port,
rather than the object being copied,
for better performance.
because immutable objects can’t be updated,
this effectively retains the actor model behavior.
an exception to this rule is
when an isolate exits when it sends a message using the isolate.exit method.
because the sending isolate won’t exist after sending the message,
it can pass ownership of the message from one isolate to the other,
ensuring that only one isolate can access the message.
the two lowest-level primitives that send messages are SendPort.send,
which makes a copy of a mutable message as it sends,
and isolate.exit,
which sends the reference to the message.
both isolate.run and compute
use isolate.exit under the hood.
<topic_end>
<topic_start>
short-lived isolates
the easiest way to move a process to an isolate in flutter is with
the isolate.run method.
this method spawns an isolate,
passes a callback to the spawned isolate to start some computation,
returns a value from the computation,
and then shuts the isolate down when the computation is complete.
this all happens concurrently with the main isolate,
and doesn’t block it.
the isolate.run method requires a single argument,
a callback function,
that is run on the new isolate.
this callback’s function signature must have exactly
one required, unnamed argument.
when the computation completes,
it returns the callback’s value back to the main isolate,
and exits the spawned isolate.
for example,
consider this code that loads a large JSON blob from a file,
and converts that JSON into custom dart objects.
if the json decoding process wasn’t off loaded to a new isolate,
this method would cause the UI to
become unresponsive for several seconds.
<code_start>
// produces a list of 211,640 photo objects.
// (the JSON file is ~20mb.)
Future<List<Photo>> getPhotos() async {
  final string jsonString = await rootBundle.loadString('assets/photos.json');
  final List<Photo> photos = await Isolate.run<List<Photo>>(() {
    final List<Object?> photoData = jsonDecode(jsonString) as List<Object?>;
    return photoData.cast<Map<String, Object?>>().map(Photo.fromJson).toList();
  });
  return photos;
}
<code_end>
for a complete walkthrough of using isolates to
parse JSON in the background, see this cookbook recipe.
<topic_end>
<topic_start>
stateful, longer-lived isolates
short-live isolates are convenient to use,
but there is performance overhead required to spawn new isolates,
and to copy objects from one isolate to another.
if you’re doing the same computation using isolate.run repeatedly,
you might have better performance by creating isolates that don’t exit immediately.
to do this, you can use a handful of lower-level isolate-related APIs that
isolate.run abstracts:
when you use the isolate.run method,
the new isolate immediately shuts down after it
returns a single message to the main isolate.
sometimes, you’ll need isolates that are long lived,
and can pass multiple messages to each other over time.
in dart, you can accomplish this with the isolate API
and ports.
these long-lived isolates are colloquially known as background workers.
long-lived isolates are useful when you have a specific process that either
needs to be run repeatedly throughout the lifetime of your application,
or if you have a process that runs over a period of time
and needs to yield multiple return values to the main isolate.
or, you might use worker_manager to manage long-lived isolates.
<topic_end>
<topic_start>
ReceivePorts and SendPorts
set up long-lived communication between isolates with two classes
(in addition to isolate):
ReceivePort and SendPort.
these ports are the only way isolates can communicate with each other.
ports behave similarly to streams,
in which the StreamController
or sink is created in one isolate,
and the listener is set up in the other isolate.
in this analogy,
the StreamConroller is called a SendPort,
and you can “add” messages with the send() method.
ReceivePorts are the listeners,
and when these listeners receive a new message,
they call a provided callback with the message as an argument.
for an in-depth explanation on setting up two-way
communication between the main isolate
and a worker isolate,
follow the examples in the dart documentation.
<topic_end>
<topic_start>
using platform plugins in isolates
as of flutter 3.7, you can use platform plugins in background isolates.
this opens many possibilities to offload heavy,
platform-dependent computations to an isolate that won’t block your UI.
for example, imagine you’re encrypting data
using a native host API
(such as an android API on android, an iOS API on iOS, and so on).
previously, marshaling data to the host platform could waste UI thread time,
and can now be done in a background isolate.
platform channel isolates use the BackgroundIsolateBinaryMessenger API.
the following snippet shows an example of using
the shared_preferences package in a background isolate.
<code_start>
import 'dart:isolate';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
  // identify the root isolate to pass to the background isolate.
  RootIsolateToken rootIsolateToken = RootIsolateToken.instance!;
  Isolate.spawn(_isolateMain, rootIsolateToken);
}
future<void> _isolateMain(RootIsolateToken rootIsolateToken) async {
  // register the background isolate with the root isolate.
  BackgroundIsolateBinaryMessenger.ensureInitialized(rootIsolateToken);
  // you can now use the shared_preferences plugin.
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  print(sharedPreferences.getBool('isDebug'));
}
<code_end>
<topic_end>
<topic_start>
limitations of isolates
if you’re coming to dart from a language with multithreading,
it’s reasonable to expect isolates to behave like threads,
but that isn’t the case.
isolates have their own global fields,
and can only communicate with message passing,
ensuring that mutable objects in an isolate are only ever accessible
in a single isolate.
therefore, isolates are limited by their access to their own memory.
for example,
if you have an application with a global mutable variable called configuration,
it is copied as a new global field in a spawned isolate.
if you mutate that variable in the spawned isolate,
it remains untouched in the main isolate.
this is true even if you pass the configuration object as a message
to the new isolate.
this is how isolates are meant to function,
and it’s important to keep in mind when you consider using isolates.
<topic_end>
<topic_start>
web platforms and compute
dart web platforms, including flutter web,
don’t support isolates.
if you’re targeting the web with your flutter app,
you can use the compute method to ensure your code compiles.
the compute() method runs the computation on
the main thread on the web,
but spawns a new thread on mobile devices.
on mobile and desktop platforms
await compute(fun, message)
is equivalent to await isolate.run(() => fun(message)).
for more information on concurrency on the web,
check out the concurrency documentation on dart.dev.
<topic_end>
<topic_start>
no rootBundle access or dart:ui methods
all UI tasks and flutter itself are coupled to the main isolate.
therefore,
you can’t access assets using rootBundle in spawned isolates,
nor can you perform any widget
or UI work in spawned isolates.
<topic_end>
<topic_start>
limited plugin messages from host platform to flutter
with background isolate platform channels,
you can use platform channels in isolates to send messages to the host platform
(for example android or iOS),
and receive responses to those messages.
however, you can’t receive unsolicited messages from the host platform.
as an example,
you can’t set up a long-lived firestore listener in a background isolate,
because firestore uses platform channels to push updates to flutter,
which are unsolicited.
you can, however, query firestore for a response in the background.
<topic_end>
<topic_start>
more information
for more information on isolates, check out the following resources:
<topic_end>
<topic_start>
performance FAQ
this page collects some frequently asked questions
about evaluating and debugging flutter’s performance.
<topic_end>
<topic_start>
more thoughts about performance
<topic_end>
<topic_start>
what is performance?
performance is a set of quantifiable properties of a performer.
in this context, performance isn’t the execution of an action itself;
it’s how well something or someone performs. therefore, we use the adjective
 performant.
while the how well part can, in general, be described in natural languages,
in our limited scope, the focus is on something that is quantifiable as a real
number. real numbers include integers and 0/1 binaries as special cases.
natural language descriptions are still very important. for example, a news
article that heavily criticizes flutter’s performance by just using words
without any numbers (a quantifiable value) could still be meaningful, and it
could have great impacts. the limited scope is chosen only because of our
limited resources.
the required quantity to describe performance is often referred to as a
metric.
to navigate through countless performance issues and metrics, you can categorize
based on performers.
for example, most of the content on this website is about the flutter app
performance, where the performer is a flutter app. infra performance is also
important to flutter, where the performers are build bots and CI task runners:
they heavily affect how fast flutter can incorporate code changes, to improve
the app’s performance.
here, the scope was intentionally broadened to include performance issues other
than just app performance issues because they can share many tools regardless of
who the performers are. for example, flutter app performance and infra
performance might share the same dashboard and similar alert mechanisms.
broadening the scope also allows performers to be included that traditionally
are easy to ignore. document performance is such an example. the performer
could be an API doc of the SDK, and a metric could be: the percentage of readers
who find the API doc useful.
<topic_end>
<topic_start>
why is performance important?
answering this question is not only crucial for validating the work in
performance, but also for guiding the performance work in order to be more
useful. the answer to “why is performance important?” often is also the answer
to “how is performance useful?”
simply speaking, performance is important and useful because, in the scope,
performance must have quantifiable properties or metrics. this implies:
not that non-performance, or non-measurable issues or descriptions are not
important. they’re meant to highlight the scenarios where performance can be
more useful.
<topic_end>
<topic_start>
1. a performance report is easy to consume
performance metrics are numbers. reading a number is much easier than reading a
passage. for example, it probably takes an engineer 1 second to consume the
performance rating as a number from 1 to 5. it probably takes the same engineer
at least 1 minute to read the full, 500-word feedback summary.
if there are many numbers, it’s easy to summarize or visualize them for quick
consumption. for example, you can quickly consume millions of numbers by
looking at its histogram, average, quantiles, and so on. if a metric has a
history of thousands of data points, then you can easily plot a timeline to
read its trend.
on the other hand, having n number of 500-word texts almost guarantees an
n-time cost to consume those texts. it would be a daunting task to analyze
thousands of historical descriptions, each having 500 words.
<topic_end>
<topic_start>
2. performance has little ambiguity
another advantage of having performance as a set of numbers is its unambiguity.
when you want an animation to have a performance of 20 ms per frame or
50 fps, there’s little room for different interpretations about the numbers. on
the other hand, to describe the same animation in words, someone might call it
good, while someone else might complain that it’s bad. similarly, the same
word or phrase could be interpreted differently by different people. you might
interpret an OK frame rate to be 60 fps, while someone else might interpret it
to be 30 fps.
numbers can still be noisy. for example, the measured time per frame might
be a true computation time of this frame, plus a random amount of time (noise)
that CPU/GPU spends on some unrelated work. hence, the metric fluctuates.
nevertheless, there’s no ambiguity of what the number means. and, there are
also rigorous theory and testing tools to handle such noise. for example, you
could take multiple measurements to estimate the distribution of a random
variable, or you could take the average of many measurements to eliminate the
noise by the law of large numbers.
<topic_end>
<topic_start>
3. performance is comparable and convertible
performance numbers not only have unambiguous meanings, but they also have
unambiguous comparisons. for example, there’s no doubt that 5 is greater than 4.
on the other hand, it might be subjective to figure out whether excellent is
better or worse than superb. similarly, could you figure out whether epic is
better than legendary? actually, the phrase strongly exceeds expectations
could be better than superb in someone’s interpretation. it only becomes
unambiguous and comparable after a definition that maps strongly exceeds
expectations to 4 and superb to 5.
numbers are also easily convertible using formulas and functions. for example,
60 fps can be converted to 16.67 ms per frame. a frame’s rendering
time x (ms) can be converted to a binary indicator
isSmooth = [x <= 16] = (x <= 16 ? 1 :0). such conversion can be compounded or
chained, so you can get a large variety of quantities using a single
measurement without any added noise or ambiguity. the converted quantity can
then be used for further comparisons and consumption. such conversions are
almost impossible if you’re dealing with natural languages.
<topic_end>
<topic_start>
4. performance is fair
if issues rely on verbose words to be discovered, then an unfair advantage is
given to people who are more verbose (more willing to chat or write) or those
who are closer to the development team, who have a larger bandwidth and lower
cost for chatting or face-to-face meetings.
by having the same metrics to detect problems no matter how far away or how
silent the users are, we can treat all issues fairly. that, in turn,
allows us to focus on the right issues that have greater impact.
<topic_end>
<topic_start>
how to make performance useful
the following summarizes the 4 points discussed here, from a slightly different
perspective:
make performance metrics easy to consume. do not overwhelm the readers with a
lot of numbers (or words). if there are many numbers, then try to summarize
them into a smaller set of numbers (for example, summarize many numbers into
a single average number). only notify readers when the numbers change
significantly (for example, automatic alerts on spikes or regressions).
make performance metrics as unambiguous as possible. define the unit that the
number is using. precisely describe how the number is measured. make the
number easily reproducible. when there’s a lot of noise, try to show the full
distribution, or eliminate the noise as much as possible by aggregating many
noisy measurements.
make it easy to compare performance. for example, provide a timeline to
compare the current version with the old version. provide ways and tools to
convert one metric to another. for example, if we can convert both memory
increase and fps drops into the number of users dropped or revenue lost in
dollars, then we can compare them and make an informed trade-off.
make performance metrics monitor a population that is as wide as possible,
so no one is left behind.
<topic_end>
<topic_start>
obfuscate dart code
<topic_end>
<topic_start>
what is code obfuscation?
code obfuscation is the process of modifying an
app’s binary to make it harder for humans to understand.
obfuscation hides function and class names in your
compiled dart code, replacing each symbol with
another symbol, making it difficult for an attacker
to reverse engineer your proprietary app.
flutter’s code obfuscation works
only on a release build.
<topic_end>
<topic_start>
limitations
note that obfuscating your code does not
encrypt resources nor does it protect against
reverse engineering.
it only renames symbols with more obscure names.
info
  it is a poor security practice to
  store secrets in an app.
<topic_end>
<topic_start>
supported targets
the following build targets
support the obfuscation process
described on this page:
info
  web apps don’t support obfuscation.
  a web app can be minified, which provides a similar result.
  when you build a release version of a flutter web app,
  the web compiler minifies the app. to learn more,
  see build and release a web app.
<topic_end>
<topic_start>
obfuscate your app
to obfuscate your app, use the flutter build command
in release mode
with the --obfuscate and  --split-debug-info options.
the --split-debug-info option specifies the directory
where flutter outputs debug files.
in the case of obfuscation, it outputs a symbol map.
for example:
once you’ve obfuscated your binary, save
the symbols file. you need this if you later
want to de-obfuscate a stack trace.
lightbulb tip
  the --split-debug-info option can also be used without --obfuscate
  to extract dart program symbols, reducing code size.
  to learn more about app size, see measuring your app’s size.
for detailed information on these flags, run
the help command for your specific target, for example:
if these flags are not listed in the output,
run flutter --version to check your version of flutter.
<topic_end>
<topic_start>
read an obfuscated stack trace
to debug a stack trace created by an obfuscated app,
use the following steps to make it human readable:
find the matching symbols file.
for example, a crash from an android arm64
device would need app.android-arm64.symbols.
provide both the stack trace (stored in a file)
and the symbols file to the flutter symbolize command.
for example:
for more information on the symbolize command,
run flutter symbolize -h.
<topic_end>
<topic_start>
read an obfuscated name
to make the name that an app obfuscated human readable,
use the following steps:
to save the name obfuscation map at app build time,
use --extra-gen-snapshot-options=--save-obfuscation-map=/<your-path>.
for example:
to recover the name, use the generated obfuscation map.
the obfuscation map is a flat JSON array with pairs of
original names and obfuscated names. for example,
["materialapp", "ex", "scaffold", "ey"], where ex
is the obfuscated name of MaterialApp.
<topic_end>
<topic_start>
caveat
be aware of the following when coding an app that will
eventually be an obfuscated binary.
<code_start>
expect(foo.runtimeType.toString(), equals('Foo'));
<code_end>
<topic_end>
<topic_start>
create flavors of a flutter app
<topic_end>
<topic_start>
what are flavors
have you ever wondered how to set up different environments in your flutter app?
flavors (known as build configurations in iOS and macOS), allow you (the developer) to
create separate environments for your app using the same code base.
for example, you might have one flavor for your full-fledged production app,
another as a limited “free” app, another for testing experimental features, and so on.
say you want to make both free and paid versions of your flutter app.
you can use flavors to set up both app versions
without writing two separate apps.
for example, the free version of the app has basic functionality and ads.
in contrast, the paid version has basic app functionality, extra features,
different styles for paid users, and no ads.
you also might use flavors for feature development.
if you’ve built a new feature and want to try it out,
you could set up a flavor to test it out.
your production code remains unaffected
until you’re ready to deploy your new feature.
flavors let you define compile-time configurations
and set parameters that are read at runtime to customize
your app’s behavior.
this document guides you through setting up flutter flavors for iOS, macOS, and android.
<topic_end>
<topic_start>
environment set up
prerequisites:
to set up flavors in iOS and macOS, you’ll define build configurations in xcode.
<topic_end>
<topic_start>
creating flavors in iOS and macOS
open your project in xcode.
select product > scheme > new scheme from the menu to
add a new scheme.
duplicate the build configurations to differentiate between the
default configurations that are already available and the new configurations
for the free scheme.
info note
  your configurations should be based on your debug.xconfig or release.xcconfig
  file, not the Pods-Runner.xcconfigs. you can check this by expanding the configuration names.
to match the free flavor, add -free
at the end of each new configuration name.
change the free scheme to match the build configurations already created.
<topic_end>
<topic_start>
using flavors in iOS and macOS
now that you’ve set up your free flavor,
you can, for example, add different product bundle identifiers per flavor.
a bundle identifier uniquely identifies your application.
in this example, we set the debug-free value to equal
com.flavor-test.free.
change the app bundle identifier to differentiate between schemes.
in product bundle identifier, append .free to each -free scheme value.
in the build settings, set the product name value to match each flavor.
for example, add debug free.
add the display name to info.plist. update the bundle display name
value to $(product_name).
now you have set up your flavor by making a free scheme
in xcode and setting the build configurations for that scheme.
for more information, skip to the launching your app flavors
section at the end of this document.
<topic_end>
<topic_start>
plugin configurations
if your app uses a flutter plugin, you need to update
ios/Podfile (if developing for iOS) and macos/Podfile (if developing for macOS).
<topic_end>
<topic_start>
using flavors in android
setting up flavors in android can be done in your project’s
build.gradle file.
inside your flutter project,
navigate to android/app/build.gradle.
create a flavorDimension to group your added product flavors.
gradle doesn’t combine product flavors that share the same dimension.
add a productFlavors object with the desired flavors along
with values for dimension, resValue,
and applicationId or applicationIdSuffix.
<topic_end>
<topic_start>
setting up launch configurations
next, add a launch.json file; this allows you to run the command
flutter run --flavor [environment name].
in VSCode, set up the launch configurations as follows:
you can now run the terminal command
flutter run --flavor free or you can set up a run
configuration in your IDE.
<topic_end>
<topic_start>
launching your app flavors
for examples of build flavors for iOS, macOS, and android,
check out the integration test samples in the flutter repo.
<topic_end>
<topic_start>
retrieving your app’s flavor at runtime
from your dart code, you can use the appFlavor API to determine what
flavor your app was built with.
<topic_end>
<topic_start>
conditionally bundling assets based on flavor
if you aren’t familiar with how to add assets to your app, see
adding assets and images.
if you have assets that are only used in a specific flavor in your app, you can
configure them to only be bundled into your app when building for that flavor.
this prevents your app bundle size from being bloated by unused assets.
here is an example:
in this example, files within the assets/common/ directory will always be bundled
when app is built during flutter run or flutter build. files within the
assets/free/ directory are bundled only when the --flavor option is set
to free. similarly, files within the assets/premium directory are
bundled only if --flavor is set to premium.
<topic_end>
<topic_start>
more information
for more information on creating and using flavors, check out
the following resources:
<topic_end>
<topic_start>
packages
for packages that support creating flavors, check out the following:
<topic_end>
<topic_start>
build and release an android app
during a typical development cycle,
you test an app using flutter run at the command line,
or by using the run and debug
options in your IDE. by default,
flutter builds a debug version of your app.
when you’re ready to prepare a release version of your app,
for example to publish to the google play store,
this page can help. before publishing,
you might want to put some finishing touches on your app.
this page covers the following topics:
info note
   throughout this page, [project] refers to 
   the directory that your application is in. while following
   these instructions, substitute [project] with 
   your app’s directory.
<topic_end>
<topic_start>
adding a launcher icon
when a new flutter app is created, it has a default launcher icon.
to customize this icon, you might want to check out the
flutter_launcher_icons package.
alternatively, you can do it manually using the following steps:
review the material design product
icons guidelines for icon design.
in the [project]/android/app/src/main/res/ directory,
place your icon files in folders named using
configuration qualifiers.
the default mipmap- folders demonstrate the correct
naming convention.
in AndroidManifest.xml, update the
application tag’s android:icon
attribute to reference icons from the previous
step (for example,
<application android:icon="@mipmap/ic_launcher" ...).
to verify that the icon has been replaced,
run your app and inspect the app icon in the launcher.
<topic_end>
<topic_start>
enabling material components
if your app uses platform views, you might want to enable
material components by following the steps described in the
getting started guide for android.
for example:
to find out the latest version, visit google maven.
<topic_end>
<topic_start>
sign the app
to publish on the play store, you need to
sign your app with a digital certificate.
android uses two signing keys: upload and app signing.
to create your app signing key, use play app signing
as described in the official play store documentation.
to sign your app, use the following instructions.
<topic_end>
<topic_start>
create an upload keystore
if you have an existing keystore, skip to the next step.
if not, create one using one of the following methods:
run the following command at the command line:
on macOS or linux, use the following command:
on windows, use the following command in PowerShell:
this command stores the upload-keystore.jks file in your home
directory. if you want to store it elsewhere, change
the argument you pass to the -keystore parameter.
however, keep the keystore file private;
don’t check it into public source control!
info note
the keytool command might not be in your path—it’s
part of java, which is installed as part of
android studio.  for the concrete path,
run flutter doctor -v and locate the path printed after
‘java binary at:’. then use that fully qualified path
replacing java (at the end) with keytool.
if your path includes space-separated names,
such as program files, use platform-appropriate
notation for the names. for example, on Mac/Linux
use program\ files, and on windows use
"program files".
the -storetype JKS tag is only required for java 9
or newer. as of the java 9 release,
the keystore type defaults to PKS12.
<topic_end>
<topic_start>
reference the keystore from the app
create a file named [project]/android/key.properties
that contains a reference to your keystore.
don’t include the angle brackets (< >).
they indicate that the text serves as a placeholder for your values.
the storeFile might be located at
/users/<user name>/upload-keystore.jks on macOS
or C:\\Users\\<user name>\\upload-keystore.jks on windows.
warning warning
  keep the key.properties file private;
  don’t check it into public source control.
<topic_end>
<topic_start>
configure signing in gradle
configure gradle to use your upload key when building your app in release mode 
by editing the [project]/android/app/build.gradle file.
add the keystore information from your properties file before the android block:
load the key.properties file into the keystoreProperties object.
find the buildTypes block:
and replace it with the following signing configuration info:
release builds of your app will now be signed automatically.
info note
  you might need to run flutter clean after changing the gradle file.
  this prevents cached builds from affecting the signing process.
for more information on signing your app, check out
sign your app on developer.android.com.
<topic_end>
<topic_start>
shrinking your code with r8
r8 is the new code shrinker from google, and it’s enabled by default
when you build a release APK or AAB. to disable r8, pass the --no-shrink
flag to flutter build apk or flutter build appbundle.
info note
  obfuscation and minification can considerably extend compile time
  of the android application.
<topic_end>
<topic_start>
enabling multidex support
when writing large apps or making use of large plugins,
you might encounter android’s dex limit of 64k methods
when targeting a minimum API of 20 or below.
this might also be encountered when running debug versions of your app
using flutter run that does not have shrinking enabled.
flutter tool supports easily enabling multidex. the simplest way is to
opt into multidex support when prompted. the tool detects multidex build errors
and asks before making changes to your android project.
opting in allows flutter to automatically depend on
androidx.multidex:multidex and use a generated
FlutterMultiDexApplication as the project’s application.
when you try to build and run your app with the run and debug
options in your IDE, your build might fail with the following message:
to enable multidex from the command line,
run flutter run --debug and select an android device:
when prompted, enter y.
the flutter tool enables multidex support and retries the build:
info note
  multidex support is natively included when targeting
  android SDK 21 or later. however, we don’t recommend
  targeting API 21+ purely to resolve the multidex issue
  as this might inadvertently exclude users running older devices.
you might also choose to manually support multidex by following android’s guides
and modifying your project’s android directory configuration.
a multidex keep file must be specified to include:
also, include any other classes used in app startup.
for more detailed guidance on adding multidex support manually,
check out the official android documentation.
<topic_end>
<topic_start>
reviewing the app manifest
review the default app manifest file, AndroidManifest.xml.
this file is located in [project]/android/app/src/main.
verify the following values:
<topic_end>
<topic_start>
reviewing the gradle build configuration
review the default gradle build file
(build.gradle, located in [project]/android/app),
to verify that the values are correct.
<topic_end>
<topic_start>
under the defaultConfig block
<topic_end>
<topic_start>
under the android block
for more information, check out the module-level build
section in the gradle build file.
<topic_end>
<topic_start>
building the app for release
you have two possible release formats when publishing to
the play store.
info note
  the google play store prefers the app bundle format.
  for more information, check out
  about android app bundles.
<topic_end>
<topic_start>
build an app bundle
this section describes how to build a release app bundle.
if you completed the signing steps,
the app bundle will be signed.
at this point, you might consider obfuscating your dart code
to make it more difficult to reverse engineer. obfuscating
your code involves adding a couple flags to your build command,
and maintaining additional files to de-obfuscate stack traces.
from the command line:
the release bundle for your app is created at
[project]/build/app/outputs/bundle/release/app.aab.
by default, the app bundle contains your dart code and the flutter
runtime compiled for armeabi-v7a (arm 32-bit), arm64-v8a
(arm 64-bit), and x86-64 (x86 64-bit).
<topic_end>
<topic_start>
test the app bundle
an app bundle can be tested in multiple ways.
this section describes two.
<topic_end>
<topic_start>
offline using the bundle tool
<topic_end>
<topic_start>
online using google play
<topic_end>
<topic_start>
build an APK
although app bundles are preferred over APKs, there are stores
that don’t yet support app bundles. in this case, build a release
APK for each target ABI (application binary interface).
if you completed the signing steps, the APK will be signed.
at this point, you might consider obfuscating your dart code
to make it more difficult to reverse engineer. obfuscating
your code involves adding a couple flags to your build command.
from the command line:
enter cd [project].
run flutter build apk --split-per-abi.
(the flutter build command defaults to --release.)
this command results in three APK files:
removing the --split-per-abi flag results in a fat APK that contains
your code compiled for all the target ABIs. such APKs are larger in
size than their split counterparts, causing the user to download
native binaries that are not applicable to their device’s architecture.
<topic_end>
<topic_start>
install an APK on a device
follow these steps to install the APK on a connected android device.
from the command line:
<topic_end>
<topic_start>
publishing to the google play store
for detailed instructions on publishing your app to the google play store,
check out the google play launch documentation.
<topic_end>
<topic_start>
updating the app’s version number
the default version number of the app is 1.0.0.
to update it, navigate to the pubspec.yaml file
and update the following line:
version: 1.0.0+1
the version number is three numbers separated by dots,
such as 1.0.0 in the example above, followed by an optional
build number such as 1 in the example above, separated by a +.
both the version and the build number can be overridden in flutter’s
build by specifying --build-name and --build-number, respectively.
in android, build-name is used as versionName while
build-number used as versionCode. for more information,
check out version your app in the android documentation.
when you rebuild the app for android, any updates in the version number
from the pubspec file will update the versionName and versionCode 
in the local.properties file.
<topic_end>
<topic_start>
android release FAQ
here are some commonly asked questions about deployment for
android apps.
<topic_end>
<topic_start>
when should i build app bundles versus APKs?
the google play store recommends that you deploy app bundles
over APKs because they allow a more efficient delivery of the
application to your users. however, if you’re distributing
your application by means other than the play store,
an APK might be your only option.
<topic_end>
<topic_start>
what is a fat APK?
a fat APK is a single APK that contains binaries for multiple
ABIs embedded within it. this has the benefit that the single APK
runs on multiple architectures and thus has wider compatibility,
but it has the drawback that its file size is much larger,
causing users to download and store more bytes when installing
your application. when building APKs instead of app bundles,
it is strongly recommended to build split APKs,
as described in build an APK using the
--split-per-abi flag.
<topic_end>
<topic_start>
what are the supported target architectures?
when building your application in release mode,
flutter apps can be compiled for armeabi-v7a (arm 32-bit),
arm64-v8a (arm 64-bit), and x86-64 (x86 64-bit).
flutter supports building for x86 android through ARM emulation.
<topic_end>
<topic_start>
how do i sign the app bundle created by flutter build appbundle?
see signing the app.
<topic_end>
<topic_start>
how do i build a release from within android studio?
in android studio, open the existing android/
folder under your app’s folder. then,
select build.gradle (module: app) in the project panel:
next, select the build variant. click build > select build variant
in the main menu. select any of the variants in the build variants
panel (debug is the default):
the resulting app bundle or APK files are located in
build/app/outputs within your app’s folder.
<topic_end>
<topic_start>
build and release an iOS app
this guide provides a step-by-step walkthrough of releasing a
flutter app to the app store and TestFlight.
<topic_end>
<topic_start>
preliminaries
xcode is required to build and release your app. you
must use a device running macOS to follow this guide.
before beginning the process of releasing your app,
ensure that it meets apple’s app review guidelines.
to publish your app to the app store,
you must first enroll in the apple developer program.
you can read more about the various membership options in apple’s
choosing a membership guide.
<topic_end>
<topic_start>
video overview
for those who prefer video over text,
the following video covers the same material as this guide.
release an iOS app with flutter in 7 steps
<topic_end>
<topic_start>
register your app on app store connect
manage your app’s life cycle on
app store connect (formerly iTunes connect).
you define your app name and description, add screenshots,
set pricing, and manage releases to the app store and TestFlight.
registering your app involves two steps: registering a unique
bundle ID, and creating an application record on app store connect.
for a detailed overview of app store connect, see the
app store connect guide.
<topic_end>
<topic_start>
register a bundle ID
every iOS application is associated with a bundle ID,
a unique identifier registered with apple.
to register a bundle ID for your app, follow these steps:
<topic_end>
<topic_start>
create an application record on app store connect
register your app on app store connect:
for a detailed overview, see
add an app to your account.
<topic_end>
<topic_start>
review xcode project settings
this step covers reviewing the most important settings
in the xcode workspace.
for detailed procedures and descriptions, see
prepare for app distribution.
navigate to your target’s settings in xcode:
verify the most important settings.
in the identity section of the general tab:
in the signing & capabilities tab:
in the deployment section of the build settings tab:
the general tab of your project settings should resemble
the following:
for a detailed overview of app signing, see
create, export, and delete signing certificates.
<topic_end>
<topic_start>
updating the app’s deployment version
if you changed deployment target in your xcode project,
open ios/Flutter/AppframeworkInfo.plist in your flutter app
and update the MinimumOSVersion value to match.
<topic_end>
<topic_start>
add an app icon
when a new flutter app is created, a placeholder icon set is created.
this step covers replacing these placeholder icons with your
app’s icons:
<topic_end>
<topic_start>
add a launch image
similar to the app icon,
you can also replace the placeholder launch image:
<topic_end>
<topic_start>
create a build archive and upload to app store connect
during development, you’ve been building, debugging, and testing
with debug builds. when you’re ready to ship your app to users
on the app store or TestFlight, you need to prepare a release build.
<topic_end>
<topic_start>
update the app’s build and version numbers
the default version number of the app is 1.0.0.
to update it, navigate to the pubspec.yaml file
and update the following line:
the version number is three numbers separated by dots,
such as 1.0.0 in the example above, followed by an optional
build number such as 1 in the example above, separated by a +.
both the version and the build number can be overridden in
flutter build ipa by specifying --build-name and --build-number,
respectively.
in iOS, build-name uses CFBundleShortVersionString
while build-number uses CFBundleVersion.
read more about iOS versioning at core foundation keys
on the apple developer’s site.
you can also override the pubspec.yaml build name and number in xcode:
<topic_end>
<topic_start>
create an app bundle
run flutter build ipa to produce an xcode build archive (.xcarchive file)
in your project’s build/ios/archive/ directory and an app store app
bundle (.ipa file) in build/ios/ipa.
consider adding the --obfuscate and --split-debug-info flags to
obfuscate your dart code to make it more difficult
to reverse engineer.
if you are not distributing to the app store, you can optionally
choose a different export method by
adding the option --export-method ad-hoc,
--export-method development or --export-method enterprise.
info note
  on versions of flutter where flutter build ipa --export-method is unavailable,
  open build/ios/archive/MyApp.xcarchive and follow the instructions below
  to validate and distribute the app from xcode.
<topic_end>
<topic_start>
upload the app bundle to app store connect
once the app bundle is created, upload it to
app store connect by either:
install and open the apple transport macOS app.
drag and drop the build/ios/ipa/*.ipa app bundle into the app.
or upload the app bundle from the command line by running:
run man altool for details about how to authenticate with the app store connect API key.
or open build/ios/archive/MyApp.xcarchive in xcode.
click the validate app button. if any issues are reported,
address them and produce another build. you can reuse the same
build ID until you upload an archive.
after the archive has been successfully validated, click
distribute app.
info note
  when you export your app at the end of distribute app,
  xcode will create a directory containing
  an IPA of your app and an ExportOptions.plist file.
  you can create new IPAs with the same options without launching
  xcode by running
  flutter build ipa --export-options-plist=path/to/exportoptions.plist.
  see xcodebuild -h for details about the keys in this property list.
you can follow the status of your build in the
activities tab of your app’s details page on
app store connect.
you should receive an email within 30 minutes notifying you that
your build has been validated and is available to release to testers
on TestFlight. at this point you can choose whether to release
on TestFlight, or go ahead and release your app to the app store.
for more details, see
upload an app to app store connect.
<topic_end>
<topic_start>
create a build archive with codemagic CLI tools
this step covers creating a build archive and uploading
your build to app store connect using flutter build commands
and codemagic CLI tools executed in a terminal
in the flutter project directory. this allows you to create a build archive
with full control of distribution certificates in a temporary keychain
isolated from your login keychain.
install the codemagic CLI tools:
you’ll need to generate an app store connect API key
with app manager access to automate operations with app store connect. to make
subsequent commands more concise, set the following environment variables from
the new key: issuer id, key id, and API key file.
you need to export or create an iOS distribution certificate to code sign and package a build archive.
if you have existing certificates, you can export the
private keys by executing the following command for each certificate:
or you can create a new private key by executing the following command:
later, you can have CLI tools automatically create a new iOS distribution from the private key.
set up a new temporary keychain to be used for code signing:
restore login keychain!
after running keychain initialize you must run the following:
keychain use-login
this sets your login keychain as the default to avoid potential
authentication issues with apps on your machine.
fetch the code signing files from app store connect:
where cert_key is either your exported iOS distribution certificate private key
or a new private key which automatically generates a new certificate. the certificate
will be created from the private key if it doesn’t exist in app store connect.
now add the fetched certificates to your keychain:
update the xcode project settings to use fetched code signing profiles:
install flutter dependencies:
install CocoaPods dependencies:
build the flutter the iOS project:
note that export_options.plist is the output of the xcode-project use-profiles command.
publish the app to app store connect:
as mentioned earlier, don’t forget to set your login keychain
as the default to avoid authentication issues
with apps on your machine:
you should receive an email within 30 minutes notifying you that
your build has been validated and is available to release to testers
on TestFlight. at this point you can choose whether to release
on TestFlight, or go ahead and release your app to the app store.
<topic_end>
<topic_start>
release your app on TestFlight
TestFlight allows developers to push their apps
to internal and external testers. this optional step
covers releasing your build on TestFlight.
for more details, see distribute an app using TestFlight.
<topic_end>
<topic_start>
release your app to the app store
when you’re ready to release your app to the world,
follow these steps to submit your app for review and
release to the app store:
apple notifies you when their app review process is complete.
your app is released according to the instructions you
specified in the version release section.
for more details, see
distribute an app through the app store.
<topic_end>
<topic_start>
troubleshooting
the distribute your app guide provides a
detailed overview of the process of releasing an app to the app store.
<topic_end>
<topic_start>
build and release a macOS app
this guide provides a step-by-step walkthrough of releasing a
flutter app to the app store.
<topic_end>
<topic_start>
preliminaries
before beginning the process of releasing your app,
ensure that it meets
apple’s app review guidelines.
in order to publish your app to the app store,
you must first enroll in the
apple developer program.
you can read more about the various
membership options in apple’s
choosing a membership guide.
<topic_end>
<topic_start>
register your app on app store connect
manage your app’s life cycle on
app store connect (formerly iTunes connect).
you define your app name and description, add screenshots,
set pricing, and manage releases to the app store and TestFlight.
registering your app involves two steps: registering a unique
bundle ID, and creating an application record on app store connect.
for a detailed overview of app store connect, see the
app store connect guide.
<topic_end>
<topic_start>
register a bundle ID
every macOS application is associated with a bundle ID,
a unique identifier registered with apple.
to register a bundle ID for your app, follow these steps:
<topic_end>
<topic_start>
create an application record on app store connect
register your app on app store connect:
for a detailed overview,
see add an app to your account.
<topic_end>
<topic_start>
review xcode project settings
this step covers reviewing the most important settings
in the xcode workspace.
for detailed procedures and descriptions, see
prepare for app distribution.
navigate to your target’s settings in xcode:
verify the most important settings.
in the identity section:
in the deployment info section:
in the signing & capabilities section:
the general tab of your project settings should resemble
the following:
for a detailed overview of app signing, see
create, export, and delete signing certificates.
<topic_end>
<topic_start>
configuring the app’s name, bundle identifier and copyright
the configuration for the product identifiers are centralized 
in macos/Runner/Configs/AppInfo.xcconfig. for the app’s name,
set PRODUCT_NAME, for the copyright set PRODUCT_COPYRIGHT,
and finally set PRODUCT_BUNDLE_IDENTIFIER for the app’s
bundle identifier.
<topic_end>
<topic_start>
updating the app’s version number
the default version number of the app is 1.0.0.
to update it, navigate to the pubspec.yaml file
and update the following line:
version: 1.0.0+1
the version number is three numbers separated by dots,
such as 1.0.0 in the example above, followed by an optional
build number such as 1 in the example above, separated by a +.
both the version and the build number can be overridden in flutter’s
build by specifying --build-name and --build-number,
respectively.
in macOS, build-name uses CFBundleShortVersionString
while build-number uses CFBundleVersion.
read more about iOS versioning at core foundation keys
on the apple developer’s site.
<topic_end>
<topic_start>
add an app icon
when a new flutter app is created, a placeholder icon set is created.
this step covers replacing these placeholder icons with your
app’s icons:
<topic_end>
<topic_start>
create a build archive with xcode
this step covers creating a build archive and uploading
your build to app store connect using xcode.
during development, you’ve been building, debugging, and testing
with debug builds. when you’re ready to ship your app to users
on the app store or TestFlight, you need to prepare a release build.
at this point, you might consider obfuscating your dart code
to make it more difficult to reverse engineer. obfuscating
your code involves adding a couple flags to your build command.
in xcode, configure the app version and build:
finally, create a build archive and upload it to app store connect:
you should receive an email within 30 minutes notifying you that
your build has been validated and is available to release to testers
on TestFlight. at this point you can choose whether to release
on TestFlight, or go ahead and release your app to the app store.
for more details, see
upload an app to app store connect.
<topic_end>
<topic_start>
create a build archive with codemagic CLI tools
this step covers creating a build archive and uploading
your build to app store connect using flutter build commands 
and codemagic CLI tools executed in a terminal
in the flutter project directory.
install the codemagic CLI tools:
you’ll need to generate an app store connect API key
with app manager access to automate operations with app store connect. to make
subsequent commands more concise, set the following environment variables from
the new key: issuer id, key id, and API key file.
you need to export or create a mac app distribution and a mac installer
distribution certificate to perform code signing and package a build archive.
if you have existing certificates, you can export the
private keys by executing the following command for each certificate:
or you can create a new private key by executing the following command:
later, you can have CLI tools automatically create a new mac app distribution and
mac installer distribution certificate. you can use the same private key for
each new certificate.
fetch the code signing files from app store connect:
where cert_key is either your exported mac app distribution certificate private key
or a new private key which automatically generates a new certificate.
if you do not have a mac installer distribution certificate,
you can create a new certificate by executing the following:
use cert_key of the private key you created earlier.
fetch the mac installer distribution certificates:
set up a new temporary keychain to be used for code signing:
restore login keychain!
  after running keychain initialize you must run the following:
keychain use-login
this sets your login keychain as the default to avoid potential
  authentication issues with apps on your machine.
now add the fetched certificates to your keychain:
update the xcode project settings to use fetched code signing profiles:
install flutter dependencies:
install CocoaPods dependencies:
build the flutter macOS project:
package the app:
publish the packaged app to app store connect:
as mentioned earlier, don’t forget to set your login keychain
as the default to avoid authentication issues
with apps on your machine:
<topic_end>
<topic_start>
release your app on TestFlight
TestFlight allows developers to push their apps
to internal and external testers. this optional step
covers releasing your build on TestFlight.
<topic_end>
<topic_start>
distribute to registered devices
see distribution guide 
to prepare an archive for distribution to designated mac computers.
<topic_end>
<topic_start>
release your app to the app store
when you’re ready to release your app to the world,
follow these steps to submit your app for review and
release to the app store:
apple notifies you when their app review process is complete.
your app is released according to the instructions you
specified in the version release section.
for more details, see
distribute an app through the app store.
<topic_end>
<topic_start>
troubleshooting
the distribute your app guide provides a
detailed overview of the process of releasing an app to the app store.
<topic_end>
<topic_start>
build and release a linux app to the snap store
during a typical development cycle,
you test an app using flutter run at the command line,
or by using the run and debug
options in your IDE. by default,
flutter builds a debug version of your app.
when you’re ready to prepare a release version of your app,
for example to publish to the snap store,
this page can help.
<topic_end>
<topic_start>
prerequisites
to build and publish to the snap store, you need the
following components:
<topic_end>
<topic_start>
set up the build environment
use the following instructions to set up your build environment.
<topic_end>
<topic_start>
install snapcraft
at the command line, run the following:
<topic_end>
<topic_start>
install LXD
to install LXD, use the following command:
LXD is required during the snap build process. once installed, LXD needs to be
configured for use. the default answers are suitable for most use cases.
on the first run, LXD might not be able to connect to its socket:
this means you need to add your username to the LXD
(lxd) group, so log out of your session and then log back in:
<topic_end>
<topic_start>
overview of snapcraft
the snapcraft tool builds snaps based on the instructions
listed in a snapcraft.yaml file.
to get a basic understanding of snapcraft and its
core concepts, take a look at the snap documentation
and the introduction to snapcraft.
additional links and information are listed at the
bottom of this page.
<topic_end>
<topic_start>
flutter snapcraft.yaml example
place the YAML file in your flutter
project under <project root>/snap/snapcraft.yaml.
(and remember that YAML files are sensitive to white space!)
for example:
the following sections explain the various pieces of the YAML file.
<topic_end>
<topic_start>
metadata
this section of the snapcraft.yaml file defines and
describes the application. the snap version is
derived (adopted) from the build section.
<topic_end>
<topic_start>
grade, confinement, and base
this section defines how the snap is built.
<topic_end>
<topic_start>
apps
this section defines the application(s) that exist inside the snap.
there can be one or more applications per snap. this example
has a single application—super_cool_app.
when a providing snap is installed, snapd will 
generate security policy that will allow it to 
listen on the well-known DBus name on the specified 
bus. if the system bus is specified, snapd will also 
generate DBus bus policy that allows ‘root’ to own 
the name and any user to communicate with the 
service. non-snap processes are allowed to 
communicate with the providing snap following 
traditional permissions checks. other (consuming) 
snaps might only communicate with the providing 
snap by connecting the snaps’ interface.
<topic_end>
<topic_start>
parts
this section defines the sources required to
assemble the snap.
parts can be downloaded and built automatically using plugins.
similar to extensions, snapcraft can use various plugins
(such as python, c, java, and ruby) to assist in the
building process. snapcraft also has some special plugins.
<topic_end>
<topic_start>
desktop file and icon
desktop entry files are used to add an application 
to the desktop menu. these files specify the name and 
icon of your application, the categories it belongs to,
related search keywords and more. these files have the 
extension .desktop and follow the XDG desktop entry 
specification version 1.1.
<topic_end>
<topic_start>
flutter super-cool-app.desktop example
place the .desktop file in your flutter project 
under <project root>/snap/gui/super-cool-app.desktop.
notice: icon and .desktop file name must be the same as your app name in
yaml file!
for example:
place your icon with .png extension in your flutter 
project under <project root>/snap/gui/super-cool-app.png.
<topic_end>
<topic_start>
build the snap
once the snapcraft.yaml file is complete,
run snapcraft as follows from the root directory
of the project.
to use the multipass VM backend:
to use the LXD container backend:
<topic_end>
<topic_start>
test the snap
once the snap is built, you’ll have a <name>.snap file
in your root project directory.
$ sudo snap install ./super-cool-app_0.1.0_amd64.snap –dangerous
<topic_end>
<topic_start>
publish
you can now publish the snap.
the process consists of the following:
<topic_end>
<topic_start>
snap store channels
the snap store uses channels to differentiate among
different versions of snaps.
the snapcraft upload command uploads the snap file to
the store. however, before you run this command,
you need to learn about the different release channels.
each channel consists of three components:
<topic_end>
<topic_start>
snap store automatic review
the snap store runs several automated checks against
your snap. there might also be a manual review,
depending on how the snap was built, and if there are
any specific security concerns. if the checks pass
without errors, the snap becomes available in the store.
<topic_end>
<topic_start>
additional resources
you can learn more from the following links on the
snapcraft.io site:
<topic_end>
<topic_start>
build and release a windows desktop app
one convenient approach to distributing windows apps
is the microsoft store.
this guide provides a step-by-step walkthrough
of packaging and deploying a flutter app in this way.
info note
  you are not required to publish windows apps through the
  microsoft store, particularly if you prefer more control
  over the distribution experience or don’t want to deal
  with the certification process. the microsoft documentation
  includes more information about traditional installation
  approaches, including windows installer.
<topic_end>
<topic_start>
preliminaries
before beginning the process of releasing
a flutter windows desktop app to the microsoft store,
first confirm that it satisfies microsoft store policies.
also, you must join the
microsoft partner network to be able to submit apps.
<topic_end>
<topic_start>
set up your application in the partner center
manage an application’s life cycle in the
microsoft partner center.
first, reserve the application name and
ensure that the required rights to the name exist.
once the name is reserved, the application
will be provisioned for services (such as
push notifications), and you can start adding add-ons.
options such as pricing, availability,
age ratings, and category have to be
configured together with the first submission
and are automatically retained
for the subsequent submissions.
<topic_end>
<topic_start>
packaging and deployment
in order to publish an application to microsoft store,
you must first package it.
the valid formats are .msix, .msixbundle,
.msixupload, .appx, .appxbundle,
.appxupload, and .xap.
<topic_end>
<topic_start>
manual packaging and deployment for the microsoft store
check out MSIX packaging
to learn about packaging
flutter windows desktop applications.
note that each product has a unique identity,
which the store assigns.
if the package is being built manually,
you have to include its identity details
manually during the packaging.
the essential information can be retrieved
from the partner center using the following instructions:
after manually packaging the application,
manually submit it to the
microsoft partner center.
you can do this by creating a new submission,
navigating to packages,
and uploading the created application package.
<topic_end>
<topic_start>
continuous deployment
in addition to manually creating and deploying the package,
you can automate the build, package, versioning,
and deployment process using CI/CD tooling after having submitted
the application to the microsoft store for the first time.
<topic_end>
<topic_start>
codemagic CI/CD
codemagic CI/CD uses the
msix pub package to package
flutter windows desktop applications.
for flutter applications, use either the
codemagic workflow editor
or codemagic.yaml
to package the application and deploy it
to the microsoft partner center.
additional options (such as the list of
capabilities and language resources
contained in the package)
can be configured using this package.
for publishing, codemagic uses the
partner center submission API;
so, codemagic requires
associating the azure active directory
and partner center accounts.
<topic_end>
<topic_start>
GitHub actions CI/CD
GitHub actions can use the
microsoft dev store CLI
to package applications into an MSIX and publish them to the microsoft store.
the setup-msstore-cli
GitHub action installs the cli so that the action can use it for packaging
and publishing.
as packaging the MSIX uses the
msix pub package, the project’s pubspec.yaml
must contain an appropriate msix_config node.
you must create an azure AD directory from the dev center with
global administrator permission.
the GitHub action requires environment secrets from the partner center.
AZURE_AD_TENANT_ID, AZURE_AD_ClIENT_ID, and AZURE_AD_CLIENT_SECRET
are visible on the dev center following the instructions for the
windows store publish action.
you also need the SELLER_ID secret, which can be found in the dev center
under account settings > organization profile > legal info.
the application must already be present in the microsoft dev center with at
least one complete submission, and msstore init must be run once within
the repository before the action can be performed. once complete, running
msstore package .
and
msstore publish
in a GitHub action packages the
application into an MSIX and uploads it to a new submission on the dev center.
the steps necessary for MSIX publishing resemble the following
<topic_end>
<topic_start>
updating the app’s version number
for apps published to the microsoft store,
the version number must be set during the
packaging process.
the default version number of the app is 1.0.0.0.
info note
  microsoft store apps are not allowed to have a
  version with a revision number other than zero.
  therefore, the last number of the version must
  remain zero for all releases.
  ensure that you follow microsoft’s
  versioning guidelines.
for apps not published to the microsoft store, you
can set the app’s executable’s file and product versions.
the executable’s default file version is 1.0.0.1,
and its default product version is 1.0.0+1. to update these,
navigate to the pubspec.yaml file and update the
following line:
the build name is three numbers separated by dots,
followed by an optional build number that is separated
by a +. in the example above, the build name is 1.0.0
and the build number is 1.
the build name becomes the first three numbers of the
file and product versions, while the build number becomes
the fourth number of the file and product versions.
both the build name and number can be overridden in
flutter build windows by specifying --build-name and
--build-number, respectively.
info note
  flutter projects created before flutter 3.3
  need to be updated to set the executable’s version
  information. for more information,
  refer to the version migration guide.
<topic_end>
<topic_start>
add app icons
to update the icon of a flutter windows
desktop application before packaging use the
following instructions:
when packaging with the msix pub package,
the logo path can also be configured inside the pubspec.yaml file.
to update the application image in the store listing,
navigate to the store listing step of the submission
and select store logos.
from there, you can upload the logo with
the size of 300 x 300 pixels.
all uploaded images are retained for subsequent submissions.
<topic_end>
<topic_start>
validating the application package
before publication to the microsoft store,
first validate the application package locally.
windows app certification kit
is a tool included in the
windows software development kit (sdk).
to validate the application:
the report might contain important warnings and information,
even if the certification passes.
<topic_end>
<topic_start>
build and release a web app
during a typical development cycle,
you test an app using flutter run -d chrome
(for example) at the command line.
this builds a debug version of your app.
this page helps you prepare a release version
of your app and covers the following topics:
<topic_end>
<topic_start>
building the app for release
build the app for deployment using the
flutter build web command.
you can also choose which renderer to use
by using the --web-renderer option (see web renderers).
this generates the app, including the assets,
and places the files into the /build/web
directory of the project.
the release build of a simple app has the
following structure:
info note
  the canvaskit directory and its contents are only present when the
  CanvasKit renderer is selected—not when the HTML renderer is selected.
launch a web server (for example,
python -m http.server 8000,
or by using the dhttpd package),
and open the /build/web directory. navigate to
localhost:8000 in your browser
(given the python SimpleHTTPServer example)
to view the release version of your app.
<topic_end>
<topic_start>
deploying to the web
when you are ready to deploy your app,
upload the release bundle
to firebase, the cloud, or a similar service.
here are a few possibilities, but there are
many others:
<topic_end>
<topic_start>
deploying to firebase hosting
you can use the firebase CLI to build and release your flutter app with firebase
hosting.
<topic_end>
<topic_start>
before you begin
to get started, install or update the firebase CLI:
<topic_end>
<topic_start>
initialize firebase
enable the web frameworks preview to the firebase framework-aware CLI:
in an empty directory or an existing flutter project, run the initialization
command:
answer yes when asked if you want to use a web framework.
if you’re in an empty directory,
 you’ll be asked to choose your web framework. choose flutter web.
choose your hosting source directory; this could be an existing flutter app.
select a region to host your files.
choose whether to set up automatic builds and deploys with GitHub.
deploy the app to firebase hosting:
running this command automatically runs flutter build web --release,
 so you don’t have to build your app in a separate step.
to learn more, visit the official firebase hosting documentation for
flutter on the web.
<topic_end>
<topic_start>
handling images on the web
the web supports the standard image widget to display images.
by design, web browsers run untrusted code without harming the host computer.
this limits what you can do with images compared to mobile and desktop platforms.
for more information, see displaying images on the web.
<topic_end>
<topic_start>
choosing a web renderer
by default, the flutter build and flutter run commands
use the auto choice for the web renderer. this means that
your app runs with the HTML renderer on mobile browsers and
CanvasKit on desktop browsers. we recommend this combination
to optimize for the characteristics of each platform.
for more information, see web renderers.
<topic_end>
<topic_start>
minification
minification is handled for you when you
create a release build.
<topic_end>
<topic_start>
embedding a flutter app into an HTML page
<topic_end>
<topic_start>
hostElement
added in flutter 3.10
you can embed a flutter web app into
any HTML element of your web page, with flutter.js and the hostElement
engine initialization parameter.
to tell flutter web in which element to render, use the hostElement parameter of the initializeEngine
function:
to learn more, check out customizing web app initialization.
<topic_end>
<topic_start>
iframe
you can embed a flutter web app,
as you would embed other content,
in an iframe tag of an HTML file.
in the following example, replace “url”
with the location of your HTML page:
<topic_end>
<topic_start>
PWA support
as of release 1.20, the flutter template for web apps includes support
for the core features needed for an installable, offline-capable PWA app.
flutter-based PWAs can be installed in the same way as any other web-based
PWA; the settings signaling that your flutter app is a PWA are provided by
manifest.json, which is produced by flutter create in the web directory.
PWA support remains a work in progress,
so please give us feedback if you see something that doesn’t look right.
<topic_end>
<topic_start>
continuous delivery with flutter
follow continuous delivery best practices with flutter to make sure your
application is delivered to your beta testers and validated on a frequent basis
without resorting to manual workflows.
<topic_end>
<topic_start>
CI/CD options
there are a number of continuous integration (ci) and continuous delivery (cd)
options available to help automate the delivery of your application.
<topic_end>
<topic_start>
all-in-one options with built-in flutter functionality
<topic_end>
<topic_start>
integrating fastlane with existing workflows
you can use fastlane with the following tooling:
this guide shows how to set up fastlane and then integrate it with 
your existing testing and continuous integration (ci) workflows. 
for more information, see “integrating fastlane with existing workflow”.
<topic_end>
<topic_start>
fastlane
fastlane is an open-source tool suite to automate releases and deployments 
for your app.
<topic_end>
<topic_start>
local setup
it’s recommended that you test the build and deployment process locally before
migrating to a cloud-based system. you could also choose to perform continuous
delivery from a local machine.
 on iOS, follow the
fastlane iOS beta deployment guide.
you can specify the archive path to avoid rebuilding the project. for example:
you’re now ready to perform deployments locally or migrate the deployment
process to a continuous integration (ci) system.
<topic_end>
<topic_start>
running deployment locally
<topic_end>
<topic_start>
cloud build and deploy setup
first, follow the local setup section described in ‘local setup’ to make sure
the process works before migrating onto a cloud system like travis.
the main thing to consider is that since cloud instances are ephemeral and
untrusted, you won’t be leaving your credentials like your play store service
account JSON or your iTunes distribution certificate on the server.
continuous integration (ci) systems generally support encrypted environment 
variables to store private data. you can pass these environment variables 
using --dart-define MY_VAR=MY_VALUE while building the app.
take precaution not to re-echo those variable values back onto the console in
your test scripts. those variables are also not available in pull requests
until they’re merged to ensure that malicious actors cannot create a pull
request that prints these secrets out. be careful with interactions with these
secrets in pull requests that you accept and merge.
<topic_end>
<topic_start>
xcode cloud
xcode cloud is a continuous integration and delivery service for building,
testing, and distributing apps and frameworks for apple platforms.
<topic_end>
<topic_start>
requirements
<topic_end>
<topic_start>
custom build script
xcode cloud recognizes custom build scripts that can be 
used to perform additional tasks at a designated time. it also includes a set
of predefined environment variables, such as $ci_workspace, which is the
location of your cloned repository.
info note
  the temporary build environment that xcode cloud uses includes tools that are
  part of macOS and xcode—for example, python—and additionally homebrew to
  support installing third-party dependencies and tools.
<topic_end>
<topic_start>
post-clone script
leverage the post-clone custom build script that runs after
xcode cloud clones your git repository using the following instructions:
create a file at ios/ci_scripts/ci_post_clone.sh and add the content below.
<code_start>
#!/bin/sh
# fail this script if any subcommand fails.
set -e
# the default execution directory of this script is the ci_scripts directory.
cd $ci_primary_repository_path # change working directory to the root of your cloned repo.
# install flutter using git.
git clone https://github.com/flutter/flutter.git --depth 1 -b stable $home/flutter
export PATH="$PATH:$HOME/flutter/bin"
# install flutter artifacts for iOS (--ios), or macOS (--macos) platforms.
flutter precache --ios
# install flutter dependencies.
flutter pub get
# install CocoaPods using homebrew.
HOMEBREW_NO_AUTO_UPDATE=1 # disable homebrew's automatic updates.
brew install cocoapods
# install CocoaPods dependencies.
cd ios && pod install # run `pod install` in the `ios` directory.
exit 0
<code_end>
this file should be added to your git repository and marked as executable.
<topic_end>
<topic_start>
workflow configuration
an xcode cloud workflow defines the steps performed in the CI/CD process
when your workflow is triggered.
info note
  this requires that your project is already initialized with git
  and linked to a remote repository.
to create a new workflow in xcode, use the following instructions:
choose product > xcode cloud > create workflow to open the
create workflow sheet.
select the product (app) that the workflow should be attached to, then click
the next button.
the next sheet displays an overview of the default workflow provided by xcode,
 and can be customized by clicking the edit workflow button.
<topic_end>
<topic_start>
branch changes
by default xcode suggests the branch changes condition that starts a new build
for every change to your git repository’s default branch.
for your app’s iOS variant, it’s reasonable that you would want xcode cloud to
trigger your workflow after you’ve made changes to your flutter packages, or
modified either the dart or iOS source files within the lib\ and ios\
directories.
this can be achieved by using the following files and folders conditions:
<topic_end>
<topic_start>
next build number
xcode cloud defaults the build number for new workflows to 1 and increments
it per successful build. if you’re using an existing app with a higher build
number, you’ll need to configure xcode cloud to use the correct build number
for its builds by simply specifying the next build number in your iteration.
check out setting the next build number for xcode cloud builds for more
information.
<topic_end>
<topic_start>
add flutter to an existing app
<topic_end>
<topic_start>
add-to-app
it’s sometimes not practical to rewrite your entire application in
flutter all at once. for those situations,
flutter can be integrated into your existing
application piecemeal, as a library or module.
that module can then be imported into your android or iOS
(currently supported platforms) app to render a part of your
app’s UI in flutter. or, just to run shared dart logic.
in a few steps, you can bring the productivity and the expressiveness of
flutter into your own app.
the add-to-app feature supports integrating multiple instances of any screen size.
this can help scenarios such as a hybrid navigation stack with mixed
native and flutter screens, or a page with multiple partial-screen flutter
views.
having multiple flutter instances allows each instance to maintain
independent application and UI state while using minimal
memory resources. see more in the multiple flutters page.
<topic_end>
<topic_start>
supported features
<topic_end>
<topic_start>
add to android applications
<topic_end>
<topic_start>
add to iOS applications
see our add-to-app GitHub samples repository
for sample projects in android and iOS that import
a flutter module for UI.
<topic_end>
<topic_start>
get started
to get started, see our project integration guide for
android and iOS:
<topic_end>
<topic_start>
API usage
after flutter is integrated into your project,
see our API usage guides at the following links:
<topic_end>
<topic_start>
limitations
<topic_end>
<topic_start>
add flutter to android
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
integrate a flutter module into your android project
flutter can be embedded into your existing android
application piecemeal, as a source code gradle
subproject or as AARs.
the integration flow can be done using the android studio
IDE with the flutter plugin or manually.
warning warning
  your existing android app might support architectures
  such as mips or x86. flutter currently only supports
  building ahead-of-time (aot) compiled libraries
  for x86_64, armeabi-v7a, and arm64-v8a.
consider using the abiFilters android gradle
  plugin API to limit the supported architectures in your APK.
  doing this avoids a missing libflutter.so runtime crash,
  for example:
<code_start>
android {
  //...
  defaultConfig {
    ndk {
      // filter for architectures supported by flutter.
      abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64'
    }
  }
}
<code_end>
the flutter engine has an x86 and x86_64 version.
  when using an emulator in debug Just-In-Time (jit) mode,
  the flutter module still runs correctly.
<topic_end>
<topic_start>
integrate your flutter module
<topic_end>
<topic_start>
integrate with android studio
the android studio IDE can help integrate your flutter module.
using android studio, you can edit both your android and flutter code
in the same IDE.
you can also use IntelliJ flutter plugin functionality like
dart code completion, hot reload, and widget inspector.
android studio supports add-to-app flows on android studio 2022.2 or later
with the flutter plugin for IntelliJ.
to build your app, the android studio plugin configures your
android project to add your flutter module as a dependency.
open your android project in android studio.
go to file > new > new project….
 the new project dialog displays.
click flutter.
if asked to provide your flutter SDK path, do so and click next.
complete the configuration of your flutter module.
if you have an existing project:
if you need to create a new flutter project:
click finish.
lightbulb tip
  by default, your project’s project pane might show the ‘android’ view.
  if you can’t see your new flutter files in the project pane,
  set your project pane to display project files.
  this shows all files without filtering.
<topic_end>
<topic_start>
integrate without android studio
to integrate a flutter module with an existing android app
manually, without using flutter’s android studio plugin,
follow these steps:
<topic_end>
<topic_start>
create a flutter module
let’s assume that you have an existing android app at
some/path/MyApp, and that you want your flutter
project as a sibling:
this creates a some/path/flutter_module/ flutter module project
with some dart code to get you started and an .android/
hidden subfolder. the .android folder contains an
android project that can both help you run a barebones
standalone version of your flutter module via flutter run
and it’s also a wrapper that helps bootstrap the flutter
module an embeddable android library.
info note
  add custom android code to your own existing
  application’s project or a plugin,
  not to the module in .android/.
  changes made in your module’s .android/
  directory won’t appear in your existing android
  project using the module.
do not source control the .android/ directory
  since it’s autogenerated. before building the
  module on a new machine, run flutter pub get
  in the flutter_module directory first to regenerate
  the .android/ directory before building the
  android project using the flutter module.
info note
  to avoid dex merging issues, flutter.androidPackage should
  not be identical to your host app’s package name.
<topic_end>
<topic_start>
java version requirement
flutter requires your project to declare compatibility with java 11 or later.
before attempting to connect your flutter module project
to your host android app, ensure that your host android
app declares the following source compatibility within your
app’s build.gradle file, under the android { } block.
<code_start>
android {
  //...
  compileOptions {
    sourceCompatibility 11 // the minimum value
    targetCompatibility 11 // the minimum value
  }
}
<code_end>
<topic_end>
<topic_start>
centralize repository settings
starting with gradle 7, android recommends using centralized repository
declarations in settings.gradle instead of project or module level
declarations in build.gradle files.
before attempting to connect your flutter module project to your
host android app, make the following changes.
remove the repositories block in all of your app’s build.gradle files.
add the dependencyResolutionManagement displayed in this step to the
settings.gradle file.
<topic_end>
<topic_start>
add the flutter module as a dependency
add the flutter module as a dependency of your
existing app in gradle. you can achieve this in two ways.
android archive
 the AAR mechanism creates generic android AARs as
 intermediaries that packages your flutter module.
 this is good when your downstream app builders don’t
 want to have the flutter SDK installed. but,
 it adds one more build step if you build frequently.
module source code
 the source code subproject mechanism is a convenient
 one-click build process, but requires the flutter SDK.
 this is the mechanism used by the android studio IDE plugin.
<topic_end>
<topic_start>
depend on the android archive (aar)
this option packages your flutter library as a generic local
maven repository composed of AARs and POMs artifacts.
this option allows your team to build the host app without
installing the flutter SDK. you can then distribute the
artifacts from a local or remote repository.
let’s assume you built a flutter module at
some/path/flutter_module, and then run:
then, follow the on-screen instructions to integrate.
more specifically, this command creates
(by default all debug/profile/release modes)
a local repository, with the following files:
to depend on the AAR, the host app must be able
to find these files.
to do that, edit settings.gradle in your host app
so that it includes the local repository and the dependency:
</br>
<topic_end>
<topic_start>
kotlin DSL based android project
after an aar build of a kotlin DSL-based android project,
follow these steps to add the flutter_module.
include the flutter module as a dependency in 
the android project’s app/build.gradle file.
<code_start>
android {
    buildTypes {
        release {
          ...
        }
        debug {
          ...
        }
        create("profile") {
            initWith(getByName("debug"))
        }
}
dependencies {
  // ...
  debugImplementation "com.example.flutter_module:flutter_debug:1.0"
  releaseImplementation 'com.example.flutter_module:flutter_release:1.0'
  add("profileImplementation", "com.example.flutter_module:flutter_profile:1.0")
}
<code_end>
the profileImplementation ID is a custom configuration to be
implemented in the app/build.gradle file of a host project.
<code_start>
configurations {
    getByName("profileImplementation") {
    }
}
<code_end>
<code_start>
include(":app")
dependencyResolutionManagement {
    repositories {
        maven(url = "https://storage.googleapis.com/download.flutter.io")
        maven(url = "some/path/flutter_module_project/build/host/outputs/repo")
    }
}
<code_end>
error important
  if you’re located in china, use a mirror site rather than the
  storage.googleapis.com domain. to learn more about mirror sites,
  check out using flutter in china page.
lightbulb tip
  you can also build an AAR for your flutter module in android studio using
  the build > flutter > build AAR menu.
<topic_end>
<topic_start>
depend on the module’s source code
this option enables a one-step build for both your
android project and flutter project. this option is
convenient when you work on both parts simultaneously
and rapidly iterate, but your team must install the
flutter SDK to build the host app.
lightbulb tip
  by default, the host app provides the :app gradle project.
  to change the name of this project, set
  flutter.hostAppProjectName in the flutter module’s
  gradle.properties file.
  include this project in the host app’s settings.gradle file.
include the flutter module as a subproject in the host app’s
settings.gradle. this example assumes flutter_module and MyApp
exist in the same directory
<code_start>
// include the host app project.
include ':app'                                    // assumed existing content
setBinding(new binding([gradle: this]))                                // new
evaluate(new file(                                                     // new
    settingsDir.parentFile,                                            // new
    'flutter_module/.android/include_flutter.groovy'                   // new
))                                                                     // new
<code_end>
the binding and script evaluation allows the flutter
module to include itself (as :flutter) and any
flutter plugins used by the module (such as :package_info and :video_player)
in the evaluation context of your settings.gradle.
introduce an implementation dependency on the flutter
module from your app:
<code_start>
dependencies {
    implementation project(':flutter')
}
<code_end>
your app now includes the flutter module as a dependency.
continue to the adding a flutter screen to an android app guide.
<topic_end>
<topic_start>
add a flutter screen to an android app
this guide describes how to add a single flutter screen to an
existing android app. a flutter screen can be added as a normal,
opaque screen, or as a see-through, translucent screen.
both options are described in this guide.
<topic_end>
<topic_start>
add a normal flutter screen
<topic_end>
<topic_start>
step 1: add FlutterActivity to AndroidManifest.xml
flutter provides FlutterActivity to display a flutter
experience within an android app. like any other activity,
FlutterActivity must be registered in your
AndroidManifest.xml. add the following XML to your
AndroidManifest.xml file under your application tag:
the reference to @style/launchtheme can be replaced
by any android theme that want to apply to your FlutterActivity.
the choice of theme dictates the colors applied to
android’s system chrome, like android’s navigation bar, and to
the background color of the FlutterActivity just before
the flutter UI renders itself for the first time.
<topic_end>
<topic_start>
step 2: launch FlutterActivity
with FlutterActivity registered in your manifest file,
add code to launch FlutterActivity from whatever point
in your app that you’d like. the following example shows
FlutterActivity being launched from an OnClickListener.
info note
make sure to use the following import:
<code_start>
myButton.setOnClickListener(new OnClickListener() {
  @override
  public void onClick(View v) {
    startActivity(
      FlutterActivity.createDefaultIntent(currentActivity)
    );
  }
});
<code_end>
<code_start>
myButton.setOnClickListener {
  startActivity(
    FlutterActivity.createDefaultIntent(this)
  )
}
<code_end>
the previous example assumes that your dart entrypoint
is called main(), and your initial flutter route is ‘/’.
the dart entrypoint can’t be changed using intent,
but the initial route can be changed using intent.
the following example demonstrates how to launch a
FlutterActivity that initially renders a custom
route in flutter.
<code_start>
myButton.addOnClickListener(new OnClickListener() {
  @override
  public void onClick(View v) {
    startActivity(
      FlutterActivity
        .withnewengine()
        .initialroute("/my_route")
        .build(currentactivity)
      );
  }
});
<code_end>
<code_start>
myButton.setOnClickListener {
  startActivity(
    FlutterActivity
      .withnewengine()
      .initialroute("/my_route")
      .build(this)
  )
}
<code_end>
replace "/my_route" with your desired initial route.
the use of the withNewEngine() factory method
configures a FlutterActivity that internally create
its own FlutterEngine instance. this comes with a
non-trivial initialization time. the alternative approach
is to instruct FlutterActivity to use a pre-warmed,
cached FlutterEngine, which minimizes flutter’s
initialization time. that approach is discussed next.
<topic_end>
<topic_start>
step 3: (optional) use a cached FlutterEngine
every FlutterActivity creates its own FlutterEngine
by default. each FlutterEngine has a non-trivial
warm-up time. this means that launching a standard
FlutterActivity comes with a brief delay before your flutter
experience becomes visible. to minimize this delay,
you can warm up a FlutterEngine before arriving at
your FlutterActivity, and then you can use
your pre-warmed FlutterEngine instead.
to pre-warm a FlutterEngine, find a reasonable
location in your app to instantiate a FlutterEngine.
the following example arbitrarily pre-warms a
FlutterEngine in the application class:
<code_start>
public class MyApplication extends application {
  public FlutterEngine flutterEngine;
  @override
  public void onCreate() {
    super.onCreate();
    // instantiate a FlutterEngine.
    flutterEngine = new FlutterEngine(this);
    // start executing dart code to pre-warm the FlutterEngine.
    flutterEngine.getDartExecutor().executeDartEntrypoint(
      DartEntrypoint.createDefault()
    );
    // cache the FlutterEngine to be used by FlutterActivity.
    FlutterEngineCache
      .getinstance()
      .put("my_engine_id", flutterEngine);
  }
}
<code_end>
<code_start>
class MyApplication : application() {
  lateinit var flutterEngine : FlutterEngine
  override fun onCreate() {
    super.onCreate()
    // instantiate a FlutterEngine.
    flutterEngine = FlutterEngine(this)
    // start executing dart code to pre-warm the FlutterEngine.
    flutterEngine.dartExecutor.executeDartEntrypoint(
      DartExecutor.DartEntrypoint.createDefault()
    )
    // cache the FlutterEngine to be used by FlutterActivity.
    FlutterEngineCache
      .getinstance()
      .put("my_engine_id", flutterEngine)
  }
}
<code_end>
the ID passed to the FlutterEngineCache can be whatever you want.
make sure that you pass the same ID to any FlutterActivity
or FlutterFragment that should use the cached FlutterEngine.
using FlutterActivity with a cached FlutterEngine
is discussed next.
info note
  to warm up a FlutterEngine, you must execute a dart
  entrypoint. keep in mind that the moment
  executeDartEntrypoint() is invoked,
  your dart entrypoint method begins executing.
  if your dart entrypoint invokes runApp()
  to run a flutter app, then your flutter app behaves as if it
  were running in a window of zero size until this
  FlutterEngine is attached to a FlutterActivity,
  FlutterFragment, or FlutterView. make sure that your app
  behaves appropriately between the time you warm it up and
  the time you display flutter content.
with a pre-warmed, cached FlutterEngine, you now need
to instruct your FlutterActivity to use the cached
FlutterEngine instead of creating a new one.
to accomplish this, use FlutterActivity’s withCachedEngine()
builder:
<code_start>
myButton.addOnClickListener(new OnClickListener() {
  @override
  public void onClick(View v) {
    startActivity(
      FlutterActivity
        .withcachedengine("my_engine_id")
        .build(currentactivity)
      );
  }
});
<code_end>
<code_start>
myButton.setOnClickListener {
  startActivity(
    FlutterActivity
      .withcachedengine("my_engine_id")
      .build(this)
  )
}
<code_end>
when using the withCachedEngine() factory method,
pass the same ID that you used when caching the desired
FlutterEngine.
now, when you launch FlutterActivity,
there is significantly less delay in
the display of flutter content.
info note
  when using a cached FlutterEngine, that FlutterEngine outlives any
  FlutterActivity or FlutterFragment that displays it. keep in
  mind that dart code begins executing as soon as you pre-warm the
  FlutterEngine, and continues executing after the destruction of your
  FlutterActivity/FlutterFragment. to stop executing and clear resources,
  obtain your FlutterEngine from the FlutterEngineCache and destroy the
  FlutterEngine with FlutterEngine.destroy().
info note
  runtime performance isn’t the only reason that you might
  pre-warm and cache a FlutterEngine.
  a pre-warmed FlutterEngine executes dart code independent
  from a FlutterActivity, which allows such a FlutterEngine
  to be used to execute arbitrary dart code at any moment.
  Non-UI application logic can be executed in a FlutterEngine,
  like networking and data caching, and in background behavior
  within a service or elsewhere. when using a FlutterEngine
  to execute behavior in the background, be sure to adhere to all
  android restrictions on background execution.
info note
  flutter’s debug/release builds have drastically different
  performance characteristics. to evaluate the performance
  of flutter, use a release build.
<topic_end>
<topic_start>
initial route with a cached engine
the concept of an initial route is available when configuring a
FlutterActivity or a FlutterFragment with a new FlutterEngine.
however, FlutterActivity and FlutterFragment don’t offer the
concept of an initial route when using a cached engine.
this is because a cached engine is expected to already be
running dart code, which means it’s too late to configure the
initial route.
developers that would like their cached engine to begin
with a custom initial route can configure their cached
FlutterEngine to use a custom initial route just before
executing the dart entrypoint. the following example
demonstrates the use of an initial route with a cached engine:
<code_start>
public class MyApplication extends application {
  @override
  public void onCreate() {
    super.onCreate();
    // instantiate a FlutterEngine.
    flutterEngine = new FlutterEngine(this);
    // configure an initial route.
    flutterEngine.getNavigationChannel().setInitialRoute("your/route/here");
    // start executing dart code to pre-warm the FlutterEngine.
    flutterEngine.getDartExecutor().executeDartEntrypoint(
      DartEntrypoint.createDefault()
    );
    // cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
    FlutterEngineCache
      .getinstance()
      .put("my_engine_id", flutterEngine);
  }
}
<code_end>
<code_start>
class MyApplication : application() {
  lateinit var flutterEngine : FlutterEngine
  override fun onCreate() {
    super.onCreate()
    // instantiate a FlutterEngine.
    flutterEngine = FlutterEngine(this)
    // configure an initial route.
    flutterEngine.navigationChannel.setInitialRoute("your/route/here");
    // start executing dart code to pre-warm the FlutterEngine.
    flutterEngine.dartExecutor.executeDartEntrypoint(
      DartExecutor.DartEntrypoint.createDefault()
    )
    // cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
    FlutterEngineCache
      .getinstance()
      .put("my_engine_id", flutterEngine)
  }
}
<code_end>
by setting the initial route of the navigation channel, the associated
FlutterEngine displays the desired route upon initial execution of the
runApp() dart function.
changing the initial route property of the navigation channel
after the initial execution of runApp() has no effect.
developers who would like to use the same FlutterEngine
between different activitys and fragments and switch
the route between those displays need to set up a method channel and
explicitly instruct their dart code to change navigator routes.
<topic_end>
<topic_start>
add a translucent flutter screen
most full-screen flutter experiences are opaque.
however, some apps would like to deploy a flutter
screen that looks like a modal, for example,
a dialog or bottom sheet. flutter supports translucent
FlutterActivitys out of the box.
to make your FlutterActivity translucent,
make the following changes to the regular process of
creating and launching a FlutterActivity.
<topic_end>
<topic_start>
step 1: use a theme with translucency
android requires a special theme property for activitys that render
with a translucent background. create or update an android theme with the
following property:
then, apply the translucent theme to your FlutterActivity.
your FlutterActivity now supports translucency.
next, you need to launch your FlutterActivity
with explicit transparency support.
<topic_end>
<topic_start>
step 2: start FlutterActivity with transparency
to launch your FlutterActivity with a transparent background,
pass the appropriate BackgroundMode to the IntentBuilder:
<code_start>
// using a new FlutterEngine.
startActivity(
  FlutterActivity
    .withnewengine()
    .backgroundmode(flutteractivitylaunchconfigs.backgroundmode.transparent)
    .build(context)
);
// using a cached FlutterEngine.
startActivity(
  FlutterActivity
    .withcachedengine("my_engine_id")
    .backgroundmode(flutteractivitylaunchconfigs.backgroundmode.transparent)
    .build(context)
);
<code_end>
<code_start>
// using a new FlutterEngine.
startActivity(
  FlutterActivity
    .withnewengine()
    .backgroundmode(flutteractivitylaunchconfigs.backgroundmode.transparent)
    .build(this)
);
// using a cached FlutterEngine.
startActivity(
  FlutterActivity
    .withcachedengine("my_engine_id")
    .backgroundmode(flutteractivitylaunchconfigs.backgroundmode.transparent)
    .build(this)
);
<code_end>
you now have a FlutterActivity with a transparent background.
info note
  make sure that your flutter content also includes a
  translucent background. if your flutter UI paints a
  solid background color, then it still appears as
  though your FlutterActivity has an opaque background.
<topic_end>
<topic_start>
add a flutter fragment to an android app
this guide describes how to add a flutter fragment to an existing
android app.  in android, a fragment represents a modular
piece of a larger UI. a fragment might be used to present
a sliding drawer, tabbed content, a page in a ViewPager,
or it might simply represent a normal screen in a
single-Activity app. flutter provides a FlutterFragment
so that developers can present a flutter experience any place
that they can use a regular fragment.
if an activity is equally applicable for your application needs,
consider using a FlutterActivity instead of a
FlutterFragment, which is quicker and easier to use.
FlutterFragment allows developers to control the following
details of the flutter experience within the fragment:
FlutterFragment also comes with a number of calls that
must be forwarded from its surrounding activity.
these calls allow flutter to react appropriately to OS events.
all varieties of FlutterFragment, and its requirements,
are described in this guide.
<topic_end>
<topic_start>
add a FlutterFragment to an activity with a new FlutterEngine
the first thing to do to use a FlutterFragment is to add it to a host
activity.
to add a FlutterFragment to a host activity, instantiate and
attach an instance of FlutterFragment in onCreate() within the
activity, or at another time that works for your app:
<code_start>
public class MyActivity extends FragmentActivity {
    // define a tag string to represent the FlutterFragment within this
    // activity's FragmentManager. this value can be whatever you'd like.
    private static final string TAG_FLUTTER_FRAGMENT = "flutter_fragment";
    // declare a local variable to reference the FlutterFragment so that you
    // can forward calls to it later.
    private FlutterFragment flutterFragment;
    @override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // inflate a layout that has a container for your FlutterFragment.
        // for this example, assume that a FrameLayout exists with an ID of
        // r.id.fragment_container.
        setContentView(R.layout.my_activity_layout);
        // get a reference to the activity's FragmentManager to add a new
        // FlutterFragment, or find an existing one.
        FragmentManager fragmentManager = getSupportFragmentManager();
        // attempt to find an existing FlutterFragment,
        // in case this is not the first time that onCreate() was run.
        flutterFragment = (flutterfragment) fragmentManager
            .findfragmentbytag(tag_flutter_fragment);
        // create and attach a FlutterFragment if one does not exist.
        if (flutterfragment == null) {
            flutterFragment = FlutterFragment.createDefault();
            fragmentManager
                .begintransaction()
                .add(
                    r.id.fragment_container,
                    flutterFragment,
                    TAG_FLUTTER_FRAGMENT
                )
                .commit();
        }
    }
}
<code_end>
<code_start>
class MyActivity : FragmentActivity() {
  companion object {
    // define a tag string to represent the FlutterFragment within this
    // activity's FragmentManager. this value can be whatever you'd like.
    private const val TAG_FLUTTER_FRAGMENT = "flutter_fragment"
  }
  // declare a local variable to reference the FlutterFragment so that you
  // can forward calls to it later.
  private var flutterFragment: FlutterFragment? = null
  override fun onCreate(savedInstanceState: bundle?) {
    super.onCreate(savedInstanceState)
    // inflate a layout that has a container for your FlutterFragment. for
    // this example, assume that a FrameLayout exists with an ID of
    // r.id.fragment_container.
    setContentView(R.layout.my_activity_layout)
    // get a reference to the activity's FragmentManager to add a new
    // FlutterFragment, or find an existing one.
    val fragmentManager: FragmentManager = supportFragmentManager
    // attempt to find an existing FlutterFragment, in case this is not the
    // first time that onCreate() was run.
    flutterFragment = fragmentManager
      .findfragmentbytag(tag_flutter_fragment) as FlutterFragment?
    // create and attach a FlutterFragment if one does not exist.
    if (flutterfragment == null) {
      var newFlutterFragment = FlutterFragment.createDefault()
      flutterFragment = newFlutterFragment
      fragmentManager
        .begintransaction()
        .add(
          r.id.fragment_container,
          newFlutterFragment,
          TAG_FLUTTER_FRAGMENT
        )
        .commit()
    }
  }
}
<code_end>
the previous code is sufficient to render a flutter UI
that begins with a call to your main() dart entrypoint,
an initial flutter route of /, and a new FlutterEngine.
however, this code is not sufficient to achieve all expected
flutter behavior. flutter depends on various OS signals that
must  be forwarded from your host activity to FlutterFragment.
these calls are shown in the following example:
<code_start>
public class MyActivity extends FragmentActivity {
    @override
    public void onPostResume() {
        super.onPostResume();
        flutterFragment.onPostResume();
    }
    @override
    protected void onNewIntent(@NonNull intent intent) {
        flutterFragment.onNewIntent(intent);
    }
    @override
    public void onBackPressed() {
        flutterFragment.onBackPressed();
    }
    @override
    public void onRequestPermissionsResult(
        int requestCode,
        @nonnull string[] permissions,
        @nonnull int[] grantResults
    ) {
        flutterFragment.onRequestPermissionsResult(
            requestCode,
            permissions,
            grantResults
        );
    }
    @override
    public void onActivityResult(
        int requestCode,
        int resultCode,
        @nullable intent data
    ) {
        super.onActivityResult(requestCode, resultCode, data);
        flutterFragment.onActivityResult(
            requestCode,
            resultCode,
            data
        );
    }
    @override
    public void onUserLeaveHint() {
        flutterFragment.onUserLeaveHint();
    }
    @override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        flutterFragment.onTrimMemory(level);
    }
}
<code_end>
<code_start>
class MyActivity : FragmentActivity() {
  override fun onPostResume() {
    super.onPostResume()
    flutterFragment!!.onPostResume()
  }
  override fun onNewIntent(@NonNull intent: intent) {
    flutterFragment!!.onNewIntent(intent)
  }
  override fun onBackPressed() {
    flutterFragment!!.onBackPressed()
  }
  override fun onRequestPermissionsResult(
    requestCode: int,
    permissions: Array<String?>,
    grantResults: IntArray
  ) {
    flutterFragment!!.onRequestPermissionsResult(
      requestCode,
      permissions,
      grantResults
    )
  }
  override fun onActivityResult(
    requestCode: int,
    resultCode: int,
    data: intent?
  ) {
    super.onActivityResult(requestCode, resultCode, data)
    flutterFragment!!.onActivityResult(
      requestCode,
      resultCode,
      data
    )
  }
  override fun onUserLeaveHint() {
    flutterFragment!!.onUserLeaveHint()
  }
  override fun onTrimMemory(level: int) {
    super.onTrimMemory(level)
    flutterFragment!!.onTrimMemory(level)
  }
}
<code_end>
with the OS signals forwarded to flutter,
your FlutterFragment works as expected.
you have now added a FlutterFragment to your existing android app.
the simplest integration path uses a new FlutterEngine,
which comes with a non-trivial initialization time,
leading to a blank UI until flutter is
initialized and rendered the first time.
most of this time overhead can be avoided by using
a cached, pre-warmed FlutterEngine, which is discussed next.
<topic_end>
<topic_start>
using a pre-warmed FlutterEngine
by default, a FlutterFragment creates its own instance
of a FlutterEngine, which requires non-trivial warm-up time.
this means your user sees a blank fragment for a brief moment.
you can mitigate most of this warm-up time by
using an existing, pre-warmed instance of FlutterEngine.
to use a pre-warmed FlutterEngine in a FlutterFragment,
instantiate a FlutterFragment with the withCachedEngine()
factory method.
<code_start>
// somewhere in your app, before your FlutterFragment is needed,
// like in the application class ...
// instantiate a FlutterEngine.
FlutterEngine flutterEngine = new FlutterEngine(context);
// start executing dart code in the FlutterEngine.
flutterEngine.getDartExecutor().executeDartEntrypoint(
    DartEntrypoint.createDefault()
);
// cache the pre-warmed FlutterEngine to be used later by FlutterFragment.
FlutterEngineCache
  .getinstance()
  .put("my_engine_id", flutterEngine);
<code_end>
<code_start>
FlutterFragment.withCachedEngine("my_engine_id").build();
<code_end>
<code_start>
// somewhere in your app, before your FlutterFragment is needed,
// like in the application class ...
// instantiate a FlutterEngine.
val flutterEngine = FlutterEngine(context)
// start executing dart code in the FlutterEngine.
flutterEngine.getDartExecutor().executeDartEntrypoint(
    DartEntrypoint.createDefault()
)
// cache the pre-warmed FlutterEngine to be used later by FlutterFragment.
FlutterEngineCache
  .getinstance()
  .put("my_engine_id", flutterEngine)
<code_end>
<code_start>
FlutterFragment.withCachedEngine("my_engine_id").build()
<code_end>
FlutterFragment internally knows about FlutterEngineCache
and retrieves the pre-warmed FlutterEngine based on the ID
given to withCachedEngine().
by providing a pre-warmed FlutterEngine,
as previously shown, your app renders the
first flutter frame as quickly as possible.
<topic_end>
<topic_start>
initial route with a cached engine
the concept of an initial route is available when configuring a
FlutterActivity or a FlutterFragment with a new FlutterEngine.
however, FlutterActivity and FlutterFragment don’t offer the
concept of an initial route when using a cached engine.
this is because a cached engine is expected to already be
running dart code, which means it’s too late to configure the
initial route.
developers that would like their cached engine to begin
with a custom initial route can configure their cached
FlutterEngine to use a custom initial route just before
executing the dart entrypoint. the following example
demonstrates the use of an initial route with a cached engine:
<code_start>
public class MyApplication extends application {
  @override
  public void onCreate() {
    super.onCreate();
    // instantiate a FlutterEngine.
    flutterEngine = new FlutterEngine(this);
    // configure an initial route.
    flutterEngine.getNavigationChannel().setInitialRoute("your/route/here");
    // start executing dart code to pre-warm the FlutterEngine.
    flutterEngine.getDartExecutor().executeDartEntrypoint(
      DartEntrypoint.createDefault()
    );
    // cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
    FlutterEngineCache
      .getinstance()
      .put("my_engine_id", flutterEngine);
  }
}
<code_end>
<code_start>
class MyApplication : application() {
  lateinit var flutterEngine : FlutterEngine
  override fun onCreate() {
    super.onCreate()
    // instantiate a FlutterEngine.
    flutterEngine = FlutterEngine(this)
    // configure an initial route.
    flutterEngine.navigationChannel.setInitialRoute("your/route/here");
    // start executing dart code to pre-warm the FlutterEngine.
    flutterEngine.dartExecutor.executeDartEntrypoint(
      DartExecutor.DartEntrypoint.createDefault()
    )
    // cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
    FlutterEngineCache
      .getinstance()
      .put("my_engine_id", flutterEngine)
  }
}
<code_end>
by setting the initial route of the navigation channel, the associated
FlutterEngine displays the desired route upon initial execution of the
runApp() dart function.
changing the initial route property of the navigation channel
after the initial execution of runApp() has no effect.
developers who would like to use the same FlutterEngine
between different activitys and fragments and switch
the route between those displays need to set up a method channel and
explicitly instruct their dart code to change navigator routes.
<topic_end>
<topic_start>
display a splash screen
the initial display of flutter content requires some wait time,
even if a pre-warmed FlutterEngine is used.
to help improve the user experience around
this brief waiting period, flutter supports the
display of a splash screen (also known as “launch screen”) until flutter
renders its first frame. for instructions about how to show a launch
screen, see the splash screen guide.
<topic_end>
<topic_start>
run flutter with a specified initial route
an android app might contain many independent flutter experiences,
running in different FlutterFragments, with different
FlutterEngines. in these scenarios,
it’s common for each flutter experience to begin with different
initial routes (routes other than /).
to facilitate this, FlutterFragment’s builder
allows you to specify a desired initial route, as shown:
<code_start>
// with a new FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
    .initialroute("myinitialroute/")
    .build();
<code_end>
<code_start>
// with a new FlutterEngine.
val flutterFragment = FlutterFragment.withNewEngine()
    .initialroute("myinitialroute/")
    .build()
<code_end>
info note
FlutterFragment’s initial route property has no effect when a pre-warmed
  FlutterEngine is used because the pre-warmed FlutterEngine already
  chose an initial route. the initial route can be chosen explicitly when
  pre-warming a FlutterEngine.
<topic_end>
<topic_start>
run flutter from a specified entrypoint
similar to varying initial routes, different
FlutterFragments might want to execute different
dart entrypoints. in a typical flutter app, there is only one
dart entrypoint: main(), but you can define other entrypoints.
FlutterFragment supports specification of the desired
dart entrypoint to execute for the given flutter experience.
to specify an entrypoint, build FlutterFragment, as shown:
<code_start>
FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
    .dartentrypoint("myspecialentrypoint")
    .build();
<code_end>
<code_start>
val flutterFragment = FlutterFragment.withNewEngine()
    .dartentrypoint("myspecialentrypoint")
    .build()
<code_end>
the FlutterFragment configuration results in the execution
of a dart entrypoint called mySpecialEntrypoint().
notice that the parentheses () are
not included in the dartEntrypoint string name.
info note
FlutterFragment’s dart entrypoint property has no effect
  when a pre-warmed FlutterEngine is used because the
  pre-warmed FlutterEngine already executed a dart entrypoint.
  the dart entrypoint can be chosen explicitly when pre-warming
  a FlutterEngine.
<topic_end>
<topic_start>
control FlutterFragment’s render mode
FlutterFragment can either use a SurfaceView to render its
flutter content, or it can use a TextureView.
the default is SurfaceView, which is significantly
better for performance than TextureView. however, SurfaceView
can’t be interleaved in the middle of an android view hierarchy.
a SurfaceView must either be the bottommost view in the hierarchy,
or the topmost view in the hierarchy.
additionally, on android versions before android n,
SurfaceViews can’t be animated because their layout and rendering
aren’t synchronized with the rest of the view hierarchy.
if either of these use cases are requirements for your app,
then you need to use TextureView instead of SurfaceView.
select a TextureView by building a FlutterFragment with a
texture RenderMode:
<code_start>
// with a new FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
    .rendermode(flutterview.rendermode.texture)
    .build();
// with a cached FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .rendermode(flutterview.rendermode.texture)
    .build();
<code_end>
<code_start>
// with a new FlutterEngine.
val flutterFragment = FlutterFragment.withNewEngine()
    .rendermode(flutterview.rendermode.texture)
    .build()
// with a cached FlutterEngine.
val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .rendermode(flutterview.rendermode.texture)
    .build()
<code_end>
using the configuration shown, the resulting FlutterFragment
renders its UI to a TextureView.
<topic_end>
<topic_start>
display a FlutterFragment with transparency
by default, FlutterFragment renders with an opaque background,
using a SurfaceView. (see “control FlutterFragment’s render
mode.”) that background is black for any pixels that aren’t
 painted by flutter. rendering with an opaque background is
the preferred rendering mode for performance reasons.
flutter rendering with transparency on android negatively
affects performance. however, there are many designs that
require transparent pixels in the flutter experience that
show through to the underlying android UI. for this reason,
flutter supports translucency in a FlutterFragment.
info note
  both SurfaceView and TextureView support transparency.
  however, when a SurfaceView is instructed to render with
  transparency, it positions itself at a higher z-index than
  all other android views, which means it appears
  above all other views. this is a limitation of SurfaceView.
  if it’s acceptable to render your flutter experience on top
  of all other content, then FlutterFragment’s default
  RenderMode of surface is the RenderMode that you
  should use. however, if you need to display android views both
  above and below your flutter experience, then you must specify a
  RenderMode of texture.
  see “control FlutterFragment’s render mode”
  for information about controlling the RenderMode.
to enable transparency for a FlutterFragment,
build it with the following configuration:
<code_start>
// using a new FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
    .transparencymode(flutterview.transparencymode.transparent)
    .build();
// using a cached FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .transparencymode(flutterview.transparencymode.transparent)
    .build();
<code_end>
<code_start>
// using a new FlutterEngine.
val flutterFragment = FlutterFragment.withNewEngine()
    .transparencymode(flutterview.transparencymode.transparent)
    .build()
// using a cached FlutterEngine.
val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .transparencymode(flutterview.transparencymode.transparent)
    .build()
<code_end>
<topic_end>
<topic_start>
the relationship between FlutterFragment and its activity
some apps choose to use fragments as entire android screens.
in these apps, it would be reasonable for a fragment to
control system chrome like android’s status bar,
navigation bar, and orientation.
in other apps, fragments are used to represent only
a portion of a UI. a FlutterFragment might be used to
implement the inside of a drawer, a video player,
or a single card. in these situations, it would be
inappropriate for the FlutterFragment to affect
android’s system chrome because there are other UI
pieces within the same window.
FlutterFragment comes with a concept that helps
differentiate between the case when a FlutterFragment
should be able to control its host activity, and the
cases when a FlutterFragment should only affect its
own behavior. to prevent a FlutterFragment from
exposing its activity to flutter plugins, and to
prevent flutter from controlling the activity’s system UI,
use the shouldAttachEngineToActivity() method in
FlutterFragment’s builder, as shown:
<code_start>
// using a new FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withNewEngine()
    .shouldattachenginetoactivity(false)
    .build();
// using a cached FlutterEngine.
FlutterFragment flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .shouldattachenginetoactivity(false)
    .build();
<code_end>
<code_start>
// using a new FlutterEngine.
val flutterFragment = FlutterFragment.withNewEngine()
    .shouldattachenginetoactivity(false)
    .build()
// using a cached FlutterEngine.
val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
    .shouldattachenginetoactivity(false)
    .build()
<code_end>
passing false to the shouldAttachEngineToActivity()
builder method prevents flutter from interacting with
the surrounding activity. the default value is true,
which allows flutter and flutter plugins to interact with the
surrounding activity.
info note
  some plugins might expect or require an activity reference.
  ensure that none of your plugins require an activity
  before you disable access.
<topic_end>
<topic_start>
add a flutter view to an android app
warning warning
  integrating via a FlutterView
  is advanced usage and requires manually creating custom, application specific
  bindings.
integrating via a FlutterView
requires a bit more work than via FlutterActivity and FlutterFragment previously
described.
fundamentally, the flutter framework on the dart side requires access to various
activity-level events and lifecycles to function. since the FlutterView (which
is an android.view.View)
can be added to any activity which is owned by the developer’s application
and since the FlutterView doesn’t have access to activity level events, the
developer must bridge those connections manually to the FlutterEngine.
how you choose to feed your application’s activities’ events to the FlutterView
will be specific to your application.
<topic_end>
<topic_start>
a sample
unlike the guides for FlutterActivity and FlutterFragment, the FlutterView
integration could be better demonstrated with a sample project.
a sample project is at https://github.com/flutter/samples/tree/main/add_to_app/android_view
to document a simple FlutterView integration where FlutterViews are used
for some of the cells in a RecycleView list of cards as seen in the gif above.
<topic_end>
<topic_start>
general approach
the general gist of the FlutterView-level integration is that you must recreate
the various interactions between your activity, the FlutterView
and the FlutterEngine
present in the FlutterActivityAndFragmentDelegate
in your own application’s code. the connections made in the FlutterActivityAndFragmentDelegate
are done automatically when using a FlutterActivity
or a FlutterFragment,
but since the FlutterView
in this case is being added to an activity or fragment in your application,
you must recreate the connections manually. otherwise, the FlutterView
will not render anything or have other missing functionalities.
a sample FlutterViewEngine
class shows one such possible implementation of an application-specific
connection between an activity, a FlutterView
and a FlutterEngine.
<topic_end>
<topic_start>
APIs to implement
the absolute minimum implementation needed for flutter to draw anything at all
is to:
the reverse detachFromFlutterEngine and other lifecycle methods on the LifecycleChannel
class must also be called to not leak resources when the FlutterView or activity
is no longer visible.
in addition, see the remaining implementation in the FlutterViewEngine
demo class or in the FlutterActivityAndFragmentDelegate
to ensure a correct functioning of other features such as clipboards, system
UI overlay, plugins etc.
<topic_end>
<topic_start>
manage plugins and dependencies in add-to-app
this guide describes how to set up your project to consume
plugins and how to manage your gradle library dependencies
between your existing android app and your flutter module’s plugins.
<topic_end>
<topic_start>
a. simple scenario
in the simple cases:
there are no additional steps needed. your add-to-app
module will work the same way as a full-Flutter app.
whether you integrate using android studio, 
gradle subproject or AARs,
transitive android gradle libraries are automatically
bundled as needed into your outer existing app.
<topic_end>
<topic_start>
b. plugins needing project edits
some plugins require you to make some edits to the
android side of your project.
for example, the integration instructions for the
firebase_crashlytics plugin require manual
edits to your android wrapper project’s build.gradle file.
for full-Flutter apps, these edits are done in your
flutter project’s /android/ directory.
in the case of a flutter module, there are only dart
files in your module project. perform those android
gradle file edits on your outer, existing android
app rather than in your flutter module.
info note
  astute readers might notice that the flutter module
  directory also contains an .android and an
  .ios directory. those directories are flutter-tool-generated
  and are only meant to bootstrap flutter into generic
  android or iOS libraries. they should not be edited or checked-in.
  this allows flutter to improve the integration point should
  there be bugs or updates needed with new versions of gradle,
  android, android gradle plugin, etc.
for advanced users, if more modularity is needed and you must
  not leak knowledge of your flutter module’s dependencies into
  your outer host app, you can rewrap and repackage your flutter
  module’s gradle library inside another native android gradle
  library that depends on the flutter module’s gradle library.
  you can make your android specific changes such as editing the
  AndroidManifest.xml, gradle files or adding more java files
  in that wrapper library.
<topic_end>
<topic_start>
c. merging libraries
the scenario that requires slightly more attention is if
your existing android application already depends on the
same android library that your flutter module
does (transitively via a plugin).
for instance, your existing app’s gradle might already have:
<code_start>
…
dependencies {
  …
  implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
  …
}
…
<code_end>
and your flutter module also depends on
firebase_crashlytics via pubspec.yaml:
<code_start>
…
dependencies:
  …
  firebase_crashlytics: ^0.1.3
  …
…
<code_end>
this plugin usage transitively adds a gradle dependency again via
firebase_crashlytics v0.1.3’s own gradle file:
<code_start>
…
dependencies {
  …
  implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
  …
}
…
<code_end>
the two com.crashlytics.sdk.android:crashlytics dependencies
might not be the same version. in this example,
the host app requested v2.10.1 and the flutter
module plugin requested v2.9.9.
by default, gradle v5
resolves dependency version conflicts
by using the newest version of the library.
this is generally ok as long as there are no API
or implementation breaking changes between the versions.
for example, you might use the new crashlytics library
in your existing app as follows:
<code_start>
…
dependencies {
  …
  implementation 'com.google.firebase:firebase-crashlytics:17.0.0-beta03
  …
}
…
<code_end>
this approach won’t work since there are major API differences
between the crashlytics’ gradle library version
v17.0.0-beta03 and v2.9.9.
for gradle libraries that follow semantic versioning,
you can generally avoid compilation and runtime errors
by using the same major semantic version in your
existing app and flutter module plugin.
<topic_end>
<topic_start>
add flutter to iOS
<topic_end>
<topic_start>
topics
<topic_end>
<topic_start>
integrate a flutter module into your iOS project
flutter UI components can be incrementally added into your existing iOS
application as embedded frameworks. there are a few ways to embed flutter 
in your existing application.
use the CocoaPods dependency manager and installed flutter SDK.
  in this case, the flutter_module is compiled from
  the source each time the app is built. (recommended.)
create frameworks for the flutter engine, your compiled dart code,
  and all flutter plugins. here, you manually embed the frameworks,
  and update your existing application’s build settings in xcode.
  this can be useful for teams that don’t want to require every developer
  to have the flutter SDK and cocoapods installed locally.
create frameworks for your compiled dart code,
  and all flutter plugins. use CocoaPods for the flutter engine. 
  with this option, embed the frameworks for your application
  and the plugins in xcode, but distribute the
  flutter engine as a CocoaPods podspec.
  this is similar to the second option, but it provides
  an alternative to distributing the large flutter.xcframework.
for examples using an app built with UIKit, 
see the iOS directories in the add_to_app code samples. 
for an example using SwiftUI, see the iOS directory in news feed app.
<topic_end>
<topic_start>
system requirements
your development environment must meet the
macOS system requirements for flutter
with xcode installed.
flutter supports iOS 12 and later.
additionally, you will need CocoaPods
version 1.10 or later.
<topic_end>
<topic_start>
create a flutter module
to embed flutter into your existing application, 
using any of the methods mentioned above, 
first create a flutter module.
from the command line, run:
a flutter module project is created at some/path/my_flutter/.
if you are using the first method mentioned above, 
the module should be created in the same parent directory 
as your existing iOS app.
from the flutter module directory, you can run the same flutter
commands you would in any other flutter project,
like flutter run --debug or flutter build ios.
you can also run the module in
android Studio/IntelliJ or VS code with
the flutter and dart plugins. this project contains a
single-view example version of your module before it’s
embedded in your existing application,
which is useful for incrementally
testing the flutter-only parts of your code.
<topic_end>
<topic_start>
module organization
the my_flutter module directory structure is similar to a
normal flutter application:
add your dart code to the lib/ directory.
add flutter dependencies to my_flutter/pubspec.yaml,
including flutter packages and plugins.
the .ios/ hidden subfolder contains an xcode workspace where
you can run a standalone version of your module.
it is a wrapper project to bootstrap your flutter code,
and contains helper scripts to facilitate building frameworks or
embedding the module into your existing application with CocoaPods.
info note
  add custom iOS code to your own existing application’s
  project or to a plugin, not to the module’s .ios/
  directory. changes made in your module’s .ios/
  directory don’t appear in your existing iOS project
  using the module, and might be overwritten by flutter.
do not source control the .ios/ directory since it’s autogenerated.
  before building the module on a new machine, run flutter pub get
  in the my_flutter directory first to regenerate the .ios/
  directory before building iOS project using the flutter module.
<topic_end>
<topic_start>
embed the flutter module in your existing application
after you have developed your flutter module,
you can embed it using the methods described at the top of the page.
info note
  you can run in debug mode on a simulator or a real device,
  and release on a real device. learn more about
  flutter’s build modes
to leverage flutter debugging functionality 
  such as hot reload, see  debugging your add-to-app module.
using flutter increases your app size.
<topic_end>
<topic_start>
option a - embed with CocoaPods and the flutter SDK
this method requires every developer working on your
project to have a locally installed version of the flutter SDK.
the flutter module is compiled from source each time the app is built.
simply build your application in xcode to automatically
run the script to embed your dart and plugin code.
this allows rapid iteration with the most up-to-date
version of your flutter module without running additional
commands outside of xcode.
the following example assumes that your existing
application and the flutter module are in sibling
directories. if you have a different directory structure,
you might need to adjust the relative paths.
if your existing application (myapp) doesn’t
already have a podfile, run pod init in the
MyApp directory to create one. 
you can find more details on using 
CocoaPods in the CocoaPods getting started guide.
add the following lines to your podfile:
<code_start>
flutter_application_path = '../my_flutter'
load file.join(flutter_application_path, '.ios', 'flutter', 'podhelper.rb')
<code_end>
for each podfile target that needs to
embed flutter, call install_all_flutter_pods(flutter_application_path).
<code_start>
target 'myapp' do
  install_all_flutter_pods(flutter_application_path)
end
<code_end>
in the podfile’s post_install block, call flutter_post_install(installer).
<code_start>
post_install do |installer|
  flutter_post_install(installer) if defined?(flutter_post_install)
end
<code_end>
info note
  the flutter_post_install method (added in flutter 3.1.0),
  adds build settings to support native apple silicon arm64 iOS simulators.
  include the if defined?(flutter_post_install) check to ensure your podfile
  is valid if you are running on older versions of flutter that don’t have this method.
run pod install.
info note
  when you change the flutter plugin dependencies in
  my_flutter/pubspec.yaml, run flutter pub get
  in your flutter module directory to refresh the list
  of plugins read by the podhelper.rb script.
  then, run pod install again from
  your application at some/path/MyApp.
the podhelper.rb script embeds your plugins,
flutter.framework, and app.framework into your project.
your app’s debug and release build configurations embed
the debug or release build modes of flutter, respectively.
add a profile build configuration
to your app to test in profile mode.
lightbulb tip
flutter.framework is the bundle for the flutter engine,
  and app.framework is the compiled dart code for this project.
open MyApp.xcworkspace in xcode.
you can now build the project using ⌘b.
<topic_end>
<topic_start>
option b - embed frameworks in xcode
alternatively, you can generate the necessary frameworks
and embed them in your application by manually editing
your existing xcode project. you might do this if members of your
team can’t locally install flutter SDK and CocoaPods,
or if you don’t want to use CocoaPods
as a dependency manager in your existing applications.
you must run flutter build ios-framework
every time you make code changes in your flutter module.
the following example assumes that you want to generate the
frameworks to some/path/MyApp/Flutter/.
warning warning
  always use flutter.xcframework and app.xcframework
  from the same directory. mixing .xcframework imports
  from different directories (such as Profile/Flutter.xcframework
  with Debug/App.xcframework) causes runtime crashes.
link and embed the generated frameworks into your existing
application in xcode.  there are multiple ways to do
this—use the method that is best for your project.
<topic_end>
<topic_start>
link on the frameworks
for example, you can drag the frameworks from
some/path/MyApp/Flutter/Release/ in finder
into your target’s build
settings > build phases > link binary with libraries.
in the target’s build settings, add $(project_dir)/flutter/release/
to the framework search paths (framework_search_paths).
lightbulb tip
  to use the simulator, you will need to 
  embed the debug version of the flutter frameworks in your
  debug build configuration. to do this 
  you can use $(project_dir)/flutter/$(configuration)
  in the framework search paths (framework_search_paths)
  build setting. this embeds the release frameworks in the release configuration, 
  and the debug frameworks in the debug configuration.
you must also open MyApp.xcodeproj/project.pbxproj (from finder) 
  and replace path = Flutter/Release/example.xcframework;
  with path = "flutter/$(configuration)/example.xcframework";
  for all added frameworks. (note the added ".)
<topic_end>
<topic_start>
embed the frameworks
the generated dynamic frameworks must be embedded
into your app to be loaded at runtime.
error important
  plugins might produce static or dynamic frameworks.
  static frameworks should be linked on, but never embedded.
  if you embed a static framework into your application,
  your application is not publishable to the app store
  and fails with a
  found an unexpected Mach-O header code archive error.
after linking the frameworks, you should see them in the 
frameworks, libraries, and embedded content
section of your target’s general settings. 
to embed the dynamic frameworks
select embed & sign.
they will then appear under embed frameworks within 
build phases as follows:
you should now be able to build the project in xcode using ⌘b.
<topic_end>
<topic_start>
option c - embed application and plugin frameworks in xcode and flutter framework with CocoaPods
alternatively, instead of distributing the large flutter.xcframework
to other developers, machines, or continuous integration systems,
you can instead generate flutter as CocoaPods podspec by adding
the flag --cocoapods. this produces a flutter.podspec
instead of an engine flutter.xcframework.
the app.xcframework and plugin frameworks are generated
as described in option b.
to generate the flutter.podspec and frameworks, run the following 
from the command line in the root of your flutter module:
host apps using CocoaPods can add flutter to their podfile:
<code_start>
pod 'flutter', :podspec => 'some/path/myapp/flutter/[build mode]/Flutter.podspec'
<code_end>
info note
  you must hard code the [build mode] value.
  for example, use debug if you need to use
  flutter attach and release when you’re ready to ship.
link and embed the generated app.xcframework,
FlutterPluginRegistrant.xcframework,
and any plugin frameworks into your existing application
as described in option b.
<topic_end>
<topic_start>
local network privacy permissions
on iOS 14 and higher, enable the dart multicast DNS
service in the debug version of your app
to add debugging functionalities such as hot-reload and
DevTools via flutter attach.
warning warning
  this service must not be enabled in the release
  version of your app, or you might experience app store rejections.
one way to do this is to maintain a separate copy of your app’s info.plist per
build configuration. the following instructions assume
the default debug and release.
adjust the names as needed depending on your app’s build configurations.
rename your app’s info.plist to Info-Debug.plist.
make a copy of it called Info-Release.plist and add it to your xcode project.
in Info-Debug.plist only add the key NSBonjourServices
and set the value to an array with the string _dartVmService._tcp.
note xcode will display this as “bonjour services”.
optionally, add the key NSLocalNetworkUsageDescription set to your
desired customized permission dialog text.
in your target’s build settings, change the info.plist file
(infoplist_file) setting path from path/to/Info.plist to path/to/Info-$(CONFIGURATION).plist.
this will resolve to the path Info-Debug.plist in debug and
Info-Release.plist in release.
alternatively, you can explicitly set the debug path to Info-Debug.plist
and the release path to Info-Release.plist.
if the Info-Release.plist copy is in your target’s build settings > build phases > copy bundle
resources build phase, remove it.
the first flutter screen loaded by your debug app will now prompt
for local network permission. the permission can also be allowed by enabling
settings > privacy > local network > your app.
<topic_end>
<topic_start>
apple silicon (arm64 macs)
on an apple silicon (m1) mac, the host app builds for an arm64 simulator.
while flutter supports arm64 simulators, some plugins might not. if you use
one of these plugins, you might see a compilation error like undefined symbols
for architecture arm64 and you must exclude arm64 from the simulator
architectures in your host app.
in your host app target, find the excluded architectures (excluded_archs) build setting.
click the right arrow disclosure indicator icon to expand the available build configurations.
hover over debug and click the plus icon. change any SDK to any iOS simulator SDK.
add arm64 to the build settings value.
when done correctly, xcode will add "excluded_archs[sdk=iphonesimulator*]" = arm64; to your project.pbxproj file.
repeat for any iOS unit test targets.
<topic_end>
<topic_start>
development
you can now add a flutter screen to your existing application.
<topic_end>
<topic_start>
add a flutter screen to an iOS app
this guide describes how to add a single flutter screen to an existing iOS app.
<topic_end>
<topic_start>
start a FlutterEngine and FlutterViewController
to launch a flutter screen from an existing iOS, you start a
FlutterEngine and a FlutterViewController.
the FlutterEngine serves as a host to the dart VM and your flutter runtime,
  and the FlutterViewController attaches to a FlutterEngine to pass 
  input events into flutter and to display frames rendered by the
  FlutterEngine.
the FlutterEngine might have the same lifespan as your
FlutterViewController or outlive your FlutterViewController.
lightbulb tip
  it’s generally recommended to pre-warm a long-lived
  FlutterEngine for your application because:
see loading sequence and performance
for more analysis on the latency and memory
trade-offs of pre-warming an engine.
<topic_end>
<topic_start>
create a FlutterEngine
where you create a FlutterEngine depends on your host app.
in this example, we create a FlutterEngine object inside a SwiftUI ObservableObject. 
we then pass this FlutterEngine into a ContentView using the 
 environmentObject() property.
<code_start>
import SwiftUI
 import flutter
 // the following library connects plugins with iOS platform code to this app.
 import FlutterPluginRegistrant
 class FlutterDependencies: ObservableObject {
   let flutterEngine = FlutterEngine(name: "my flutter engine")
   init(){
     // runs the default dart entrypoint with a default flutter route.
     flutterEngine.run()
     // connects plugins with iOS platform code to this app.
     GeneratedPluginRegistrant.register(with: self.flutterEngine);
   }
 }
 @main
 struct MyApp: app {
   // flutterDependencies will be injected using EnvironmentObject.
   @stateobject var flutterDependencies = FlutterDependencies()
     var body: some scene {
       WindowGroup {
         ContentView().environmentObject(flutterDependencies)
       }
     }
 }
<code_end>
as an example, we demonstrate creating a
FlutterEngine, exposed as a property, on app startup in
the app delegate.
<code_start>
import UIKit
import flutter
// the following library connects plugins with iOS platform code to this app.
import FlutterPluginRegistrant
@uiapplicationmain
class AppDelegate: FlutterAppDelegate { // more on the FlutterAppDelegate.
  lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [uiapplication.launchoptionskey: any]?) -> bool {
    // runs the default dart entrypoint with a default flutter route.
    flutterEngine.run();
    // connects plugins with iOS platform code to this app.
    GeneratedPluginRegistrant.register(with: self.flutterEngine);
    return super.application(application, didFinishLaunchingWithOptions: launchOptions);
  }
}
<code_end>
in this example, we create a FlutterEngine 
object inside a SwiftUI ObservableObject. 
we then pass this FlutterEngine into a 
ContentView using the environmentObject() property.
<code_start>
@import UIKit;
@import flutter;
@interface AppDelegate : FlutterAppDelegate // more on the FlutterAppDelegate below.
@property (nonatomic,strong) FlutterEngine *flutterengine;
@end
<code_end>
<code_start>
// the following library connects plugins with iOS platform code to this app.
#import <flutterpluginregistrant/generatedpluginregistrant.h>
#import "appdelegate.h"
@implementation AppDelegate
- (bool)application:(uiapplication *)application
    didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchoptions {
  self.flutterEngine = [[flutterengine alloc] initWithName:@"my flutter engine"];
  // runs the default dart entrypoint with a default flutter route.
  [self.flutterengine run];
  // connects plugins with iOS platform code to this app.
  [generatedpluginregistrant registerWithRegistry:self.flutterEngine];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
<code_end>
<topic_end>
<topic_start>
show a FlutterViewController with your FlutterEngine
the following example shows a generic ContentView with a
button hooked to present a FlutterViewController.
the FlutterViewController constructor takes the pre-warmed 
FlutterEngine as an argument. FlutterEngine is passed in 
as an EnvironmentObject via flutterDependencies.
<code_start>
import SwiftUI
import flutter
struct ContentView: view {
  // flutter dependencies are passed in an EnvironmentObject.
  @environmentobject var flutterDependencies: FlutterDependencies
  // button is created to call the showFlutter function when pressed.
  var body: some view {
    Button("Show flutter!") {
      showFlutter()
    }
  }
func showFlutter() {
    // get the RootViewController.
    guard
      let windowScene = UIApplication.shared.connectedScenes
        .first(where: { $0.activationstate == .foregroundactive && $0 is UIWindowScene }) as? UIWindowScene,
      let window = windowScene.windows.first(where: \.iskeywindow),
      let rootViewController = window.rootViewController
    else { return }
    // create the FlutterViewController.
    let flutterViewController = FlutterViewController(
      engine: flutterDependencies.flutterEngine,
      nibName: nil,
      bundle: nil)
    flutterViewController.modalPresentationStyle = .overcurrentcontext
    flutterViewController.isViewOpaque = false
    rootViewController.present(flutterViewController, animated: true)
  }
}
<code_end>
the following example shows a generic ViewController with a
UIButton hooked to present a FlutterViewController.
the FlutterViewController uses the FlutterEngine instance
created in the AppDelegate.
<code_start>
import UIKit
import flutter
class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    // make a button to call the showFlutter function when pressed.
    let button = UIButton(type:UIButton.ButtonType.custom)
    button.addTarget(self, action: #selector(showflutter), for: .touchupinside)
    button.setTitle("Show flutter!", for: UIControl.State.normal)
    button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
    button.backgroundColor = UIColor.blue
    self.view.addSubview(button)
  }
  @objc func showFlutter() {
    let flutterEngine = (uiapplication.shared.delegate as! AppDelegate).flutterEngine
    let flutterViewController =
        FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
    present(flutterViewController, animated: true, completion: nil)
  }
}
<code_end>
the following example shows a generic ViewController with a
UIButton hooked to present a FlutterViewController.
the FlutterViewController uses the FlutterEngine instance
created in the AppDelegate.
<code_start>
@import flutter;
#import "appdelegate.h"
#import "viewcontroller.h"
@implementation ViewController
- (void)viewdidload {
    [super viewDidLoad];
    // make a button to call the showFlutter function when pressed.
    UIButton *button = [uibutton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self
               action:@selector(showFlutter)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show flutter!" forState:UIControlStateNormal];
    button.backgroundColor = UIColor.blueColor;
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.view addSubview:button];
}
- (void)showflutter {
    FlutterEngine *flutterengine =
        ((appdelegate *)uiapplication.sharedapplication.delegate).flutterengine;
    FlutterViewController *flutterviewcontroller =
        [[flutterviewcontroller alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
    [self presentViewController:flutterViewController animated:YES completion:nil];
}
@end
<code_end>
now, you have a flutter screen embedded in your iOS app.
info note
  using the previous example, the default main()
  entrypoint function of your default dart library
  would run when calling run on the
  FlutterEngine created in the AppDelegate.
<topic_end>
<topic_start>
alternatively - create a FlutterViewController with an implicit FlutterEngine
as an alternative to the previous example, you can let the
FlutterViewController implicitly create its own FlutterEngine without
pre-warming one ahead of time.
this is not usually recommended because creating a
FlutterEngine on-demand could introduce a noticeable
latency between when the FlutterViewController is
presented and when it renders its first frame. this could, however, be
useful if the flutter screen is rarely shown, when there are no good
heuristics to determine when the dart VM should be started, and when flutter
doesn’t need to persist state between view controllers.
to let the FlutterViewController present without an existing
FlutterEngine, omit the FlutterEngine construction, and create the
FlutterViewController without an engine reference.
<code_start>
// existing code omitted.
func showFlutter() {
  let flutterViewController = FlutterViewController(project: nil, nibName: nil, bundle: nil)
  present(flutterViewController, animated: true, completion: nil)
}
<code_end>
<code_start>
// existing code omitted.
- (void)showflutter {
  FlutterViewController *flutterviewcontroller =
      [[flutterviewcontroller alloc] initWithProject:nil nibName:nil bundle:nil];
  [self presentViewController:flutterViewController animated:YES completion:nil];
}
@end
<code_end>
see loading sequence and performance
for more explorations on latency and memory usage.
<topic_end>
<topic_start>
using the FlutterAppDelegate
letting your application’s UIApplicationDelegate subclass
FlutterAppDelegate is recommended but not required.
the FlutterAppDelegate performs functions such as:
<topic_end>
<topic_start>
creating a FlutterAppDelegate subclass
creating a subclass of the FlutterAppDelegate in UIKit apps was shown 
in the start a FlutterEngine and FlutterViewController section. 
in a SwiftUI app, you can create a subclass of the 
FlutterAppDelegate that conforms to the ObservableObject protocol as follows:
then, in your view, the AppDelegateis accessible as an EnvironmentObject.
<topic_end>
<topic_start>
if you can’t directly make FlutterAppDelegate a subclass
if your app delegate can’t directly make FlutterAppDelegate a subclass,
make your app delegate implement the FlutterAppLifeCycleProvider
protocol in order to make sure your plugins receive the necessary callbacks.
otherwise, plugins that depend on these events might have undefined behavior.
for instance:
<code_start>
import foundation
import flutter
class AppDelegate: UIResponder, UIApplicationDelegate, FlutterAppLifeCycleProvider, ObservableObject {
  private let lifecycleDelegate = FlutterPluginAppLifeCycleDelegate()
  let flutterEngine = FlutterEngine(name: "flutter_nps_engine")
  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [uiapplication.launchoptionskey : any]? = nil) -> bool {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [uiapplication.launchoptionskey : any]? = nil) -> bool {
    flutterEngine.run()
    return lifecycleDelegate.application(application, didFinishLaunchingWithOptions: launchOptions ?? [:])
  }
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: data) {
    lifecycleDelegate.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
  }
  func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: error) {
    lifecycleDelegate.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
  }
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [anyhashable : any], fetchCompletionHandler completionHandler: @escaping (uibackgroundfetchresult) -> void) {
    lifecycleDelegate.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
  }
  func application(_ app: UIApplication, open url: URL, options: [uiapplication.openurloptionskey : any] = [:]) -> bool {
    return lifecycleDelegate.application(app, open: url, options: options)
  }
  func application(_ application: UIApplication, handleOpen url: URL) -> bool {
    return lifecycleDelegate.application(application, handleOpen: url)
  }
  func application(_ application: UIApplication, open url: URL, sourceApplication: string?, annotation: any) -> bool {
    return lifecycleDelegate.application(application, open: url, sourceApplication: sourceApplication ?? "", annotation: annotation)
  }
  func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (bool) -> void) {
    lifecycleDelegate.application(application, performActionFor: shortcutItem, completionHandler: completionHandler)
  }
  func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: string, completionHandler: @escaping () -> void) {
    lifecycleDelegate.application(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
  }
  func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (uibackgroundfetchresult) -> void) {
    lifecycleDelegate.application(application, performFetchWithCompletionHandler: completionHandler)
  }
  func add(_ delegate: FlutterApplicationLifeCycleDelegate) {
    lifecycleDelegate.add(delegate)
  }
}
<code_end>
<code_start>
@import flutter;
@import UIKit;
@import FlutterPluginRegistrant;
@interface AppDelegate : UIResponder <uiapplicationdelegate, FlutterAppLifeCycleProvider>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,strong) FlutterEngine *flutterengine;
@end
<code_end>
the implementation should delegate mostly to a
FlutterPluginAppLifeCycleDelegate:
<code_start>
@interface AppDelegate ()
@property (nonatomic, strong) FlutterPluginAppLifeCycleDelegate* lifeCycleDelegate;
@end
@implementation AppDelegate
- (instancetype)init {
    if (self = [super init]) {
        _lifeCycleDelegate = [[flutterpluginapplifecycledelegate alloc] init];
    }
    return self;
}
- (bool)application:(uiapplication*)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id>*))launchOptions {
    self.flutterEngine = [[flutterengine alloc] initWithName:@"io.flutter" project:nil];
    [self.flutterengine runWithEntrypoint:nil];
    [generatedpluginregistrant registerWithRegistry:self.flutterEngine];
    return [_lifecycledelegate application:application didFinishLaunchingWithOptions:launchOptions];
}
// returns the key window's rootViewController, if it's a FlutterViewController.
// otherwise, returns nil.
- (flutterviewcontroller*)rootflutterviewcontroller {
    UIViewController* viewController = [uiapplication sharedApplication].keyWindow.rootViewController;
    if ([viewcontroller isKindOfClass:[FlutterViewController class]]) {
        return (flutterviewcontroller*)viewcontroller;
    }
    return nil;
}
- (void)application:(uiapplication*)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
    [_lifecycledelegate application:application
didRegisterUserNotificationSettings:notificationSettings];
}
- (void)application:(uiapplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    [_lifecycledelegate application:application
didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(uiapplication*)application
didReceiveRemoteNotification:(NSDictionary*)userInfo
fetchCompletionHandler:(void (^)(uibackgroundfetchresult result))completionHandler {
    [_lifecycledelegate application:application
       didReceiveRemoteNotification:userInfo
             fetchCompletionHandler:completionHandler];
}
- (bool)application:(uiapplication*)application
            openURL:(NSURL*)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options {
    return [_lifecycledelegate application:application openURL:url options:options];
}
- (bool)application:(uiapplication*)application handleOpenURL:(NSURL*)url {
    return [_lifecycledelegate application:application handleOpenURL:url];
}
- (bool)application:(uiapplication*)application
            openURL:(NSURL*)url
  sourceApplication:(NSString*)sourceApplication
         annotation:(id)annotation {
    return [_lifecycledelegate application:application
                                   openURL:url
                         sourceApplication:sourceApplication
                                annotation:annotation];
}
- (void)application:(uiapplication*)application
performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem
  completionHandler:(void (^)(bool succeeded))completionHandler {
    [_lifecycledelegate application:application
       performActionForShortcutItem:shortcutItem
                  completionHandler:completionHandler];
}
- (void)application:(uiapplication*)application
handleEventsForBackgroundURLSession:(nonnull NSString*)identifier
  completionHandler:(nonnull void (^)(void))completionhandler {
    [_lifecycledelegate application:application
handleEventsForBackgroundURLSession:identifier
                  completionHandler:completionHandler];
}
- (void)application:(uiapplication*)application
performFetchWithCompletionHandler:(void (^)(uibackgroundfetchresult result))completionHandler {
    [_lifecycledelegate application:application performFetchWithCompletionHandler:completionHandler];
}
- (void)addapplicationlifecycledelegate:(nsobject<flutterplugin>*)delegate {
    [_lifecycledelegate addDelegate:delegate];
}
@end
<code_end>
<topic_end>
<topic_start>
launch options
the examples demonstrate running flutter using the default launch settings.
in order to customize your flutter runtime,
you can also specify the dart entrypoint, library, and route.
<topic_end>
<topic_start>
dart entrypoint
calling run on a FlutterEngine, by default,
runs the main() dart function
of your lib/main.dart file.
you can also run a different entrypoint function by using
runWithEntrypoint with an NSString specifying
a different dart function.
info note
  dart entrypoint functions other than main()
  must be annotated with the following in order to
  not be tree-shaken away when compiling:
<topic_end>
<topic_start>
dart library
in addition to specifying a dart function, you can specify an entrypoint
function in a specific file.
for instance the following runs myOtherEntrypoint()
in lib/other_file.dart instead of main() in lib/main.dart:
<topic_end>
<topic_start>
route
starting in flutter version 1.22, an initial route can be set for your flutter
WidgetsApp when constructing the FlutterEngine or the
FlutterViewController.
this code sets your dart:ui’s window.defaultRouteName
to "/onboarding" instead of "/".
alternatively, to construct a FlutterViewController directly without pre-warming
a FlutterEngine:
lightbulb tip
  in order to imperatively change your current flutter
  route from the platform side after the FlutterEngine
  is already running, use pushRoute()
  or popRoute() on the FlutterViewController.
to pop the iOS route from the flutter side,
  call SystemNavigator.pop().
see navigation and routing for more about flutter’s routes.
<topic_end>
<topic_start>
other
the previous example only illustrates a few ways to customize
how a flutter instance is initiated. using platform channels,
you’re free to push data or prepare your flutter environment
in any way you’d like, before presenting the flutter UI using a
FlutterViewController.
<topic_end>
<topic_start>
debug your add-to-app module
once you’ve integrated the flutter module to your project and used flutter’s
platform APIs to run the flutter engine and/or UI,
you can then build and run your android or iOS app the same way
you run normal android or iOS apps.
however, flutter is now powering the UI in places where you’re showing a
FlutterActivity or FlutterViewController.
<topic_end>
<topic_start>
debugging
you might be used to having your suite of favorite flutter debugging tools
available to you automatically when running flutter run or an equivalent
command from an IDE. but you can also use all your flutter
debugging functionalities such as hot reload, performance
overlays, DevTools, and setting breakpoints in add-to-app scenarios.
these functionalities are provided by the flutter attach mechanism.
flutter attach can be initiated through different pathways,
such as through the SDK’s CLI tools,
through VS code or IntelliJ/Android studio.
flutter attach can connect as soon as you run your FlutterEngine, and
remains attached until your FlutterEngine is disposed. but you can invoke
flutter attach before starting your engine. flutter attach waits for
the next available dart VM that is hosted by your engine.
<topic_end>
<topic_start>
terminal
run flutter attach or flutter attach -d deviceId to attach from the terminal.
<topic_end>
<topic_start>
VS code
<topic_end>
<topic_start>
build the iOS version of the flutter app in the terminal
to generate the needed iOS platform dependencies,
run the flutter build command.
<topic_end>
<topic_start>
start debugging with VS code first
if you use VS code to debug most of your code, start with this section.
<topic_end>
<topic_start>
start the dart debugger in VS code
to open the flutter app directory, go to
file >
open folder… and choose the my_app directory.
open the lib/main.dart file.
if you can build an app for more than one device,
you must select the device first.
go to
view >
command palette…
you can also press ctrl / cmd +
shift + p.
type flutter select.
click the flutter: select device command.
choose your target device.
click the debug icon
().
this opens the debug pane and launches the app.
wait for the app to launch on the device and for the debug pane to
indicate connected.
the debugger takes longer to launch the first time.
subsequent launches start faster.
this flutter app contains two buttons:
<topic_end>
<topic_start>
attach to the flutter process in xcode
to attach to the flutter app, go to
debug >
attach to process >
runner.
runner should be at the top of the attach to process menu
under the likely targets heading.
<topic_end>
<topic_start>
start debugging with xcode first
if you use xcode to debug most of your code, start with this section.
<topic_end>
<topic_start>
start the xcode debugger
open ios/Runner.xcworkspace from your flutter app directory.
select the correct device using the scheme menu in the toolbar.
if you have no preference, choose iPhone pro 14.
run this runner as a normal app in xcode.
when the run completes, the debug area at the bottom of xcode displays
 a message with the dart VM service URI. it resembles the following response:
copy the dart VM service URI.
<topic_end>
<topic_start>
attach to the dart VM in VS code
to open the command palette, go to
 view >
command palette…
you can also press cmd + shift + p.
type debug.
click the debug: attach to flutter on device command.
in the paste an VM service URI box, paste the URI you copied
 from xcode and press enter.
you can also create a .vscode/launch.json file in your flutter module project.
this enables you to attach using the run > start debugging command or f5:
<topic_end>
<topic_start>
IntelliJ / android studio
select the device on which the flutter module runs so flutter attach filters for the right start signals.
<topic_end>
<topic_start>
wireless debugging
you can debug your app wirelessly on an iOS or android device
using flutter attach.
<topic_end>
<topic_start>
iOS
on iOS, you must follow the steps below:
ensure that your device is wirelessly connected to xcode
as described in the iOS setup guide.
open xcode > product > scheme > edit scheme
select the arguments tab
add either --vm-service-host=0.0.0.0 for IPv4, 
or --vm-service-host=::0 for IPv6 as a launch argument
you can determine if you’re on an IPv6 network by opening your mac’s 
settings > Wi-Fi > details (of the network you’re connected to) > TCP/IP 
and check to see if there is an IPv6 address section.
<topic_end>
<topic_start>
android
ensure that your device is wirelessly connected to android studio 
as described in the android setup guide.
<topic_end>
<topic_start>
multiple flutter screens or views
<topic_end>
<topic_start>
scenarios
if you’re integrating flutter into an existing app,
or gradually migrating an existing app to use flutter,
you might find yourself wanting to add multiple
flutter instances to the same project.
in particular, this can be useful in the
following scenarios:
the advantage of using multiple flutter instances is that each
instance is independent and maintains its own internal navigation
stack, UI, and application states. this simplifies the overall application code’s
responsibility for state keeping and improves modularity. more details on the
scenarios motivating the usage of multiple flutters can be found at
flutter.dev/go/multiple-flutters.
flutter is optimized for this scenario, with a low incremental
memory cost (~180kb) for adding additional flutter instances. this fixed cost
reduction allows the multiple flutter instance pattern to be used more liberally
in your add-to-app integration.
<topic_end>
<topic_start>
components
the primary API for adding multiple flutter instances on both android and iOS
is based on a new FlutterEngineGroup class (android API, iOS API)
to construct FlutterEngines, rather than the FlutterEngine
constructors used previously.
whereas the FlutterEngine API was direct and easier to consume, the
FlutterEngine spawned from the same FlutterEngineGroup have the performance
advantage of sharing many of the common, reusable resources such as the GPU
context, font metrics, and isolate group snapshot, leading to a faster initial
rendering latency and lower memory footprint.
FlutterEngines spawned from FlutterEngineGroup can be used to
 connect to UI classes like FlutterActivity or FlutterViewController
 in the same way as normally constructed cached FlutterEngines.
the first FlutterEngine spawned from the FlutterEngineGroup doesn’t need
to continue surviving in order for subsequent FlutterEngines to share
resources as long as there’s at least 1 living FlutterEngine at all
times.
creating the very first FlutterEngine from a FlutterEngineGroup has
the same performance characteristics as constructing a
FlutterEngine using the constructors did previously.
when all FlutterEngines from a FlutterEngineGroup are destroyed, the next
FlutterEngine created has the same performance characteristics as the very
first engine.
the FlutterEngineGroup itself doesn’t need to live beyond all of the spawned
engines. destroying the FlutterEngineGroup doesn’t affect existing spawned
FlutterEngines but does remove the ability to spawn additional
FlutterEngines that share resources with existing spawned engines.
<topic_end>
<topic_start>
communication
communication between flutter instances is handled using platform channels
(or pigeon) through the host platform. to see our roadmap on communication,
or other planned work on enhancing multiple flutter instances, check out
issue 72009.
<topic_end>
<topic_start>
samples
you can find a sample demonstrating how to use FlutterEngineGroup
on both android and iOS on GitHub.
<topic_end>
<topic_start>
load sequence, performance, and memory
this page describes the breakdown of the steps involved
to show a flutter UI. knowing this, you can make better,
more informed decisions about when to pre-warm the flutter engine,
which operations are possible at which stage,
and the latency and memory costs of those operations.
<topic_end>
<topic_start>
loading flutter
android and iOS apps (the two supported platforms for
integrating into existing apps), full flutter apps,
and add-to-app patterns have a similar sequence of
conceptual loading steps when displaying the flutter UI.
<topic_end>
<topic_start>
finding the flutter resources
flutter’s engine runtime and your application’s compiled
dart code are both bundled as shared libraries on android
and iOS. the first step of loading flutter is to find those
resources in your .apk/.ipa/.app (along with other flutter
assets such as images, fonts, and JIT code, if applicable).
this happens when you construct a FlutterEngine for the
first time on both android
and iOS APIs.
<topic_end>
<topic_start>
loading the flutter library
after it’s found, the engine’s shared libraries are memory loaded
once per process.
on android, this also happens when the
FlutterEngine is constructed because the
JNI connectors need to reference the flutter c++ library.
on iOS, this happens when the
FlutterEngine is first run,
such as by running runWithEntrypoint:.
<topic_end>
<topic_start>
starting the dart VM
the dart runtime is responsible for managing dart memory and
concurrency for your dart code. in JIT mode,
it’s additionally responsible for compiling
the dart source code into machine code during runtime.
a single dart runtime exists per application session on
android and iOS.
a one-time dart VM start is done when constructing the
FlutterEngine for the first time on
android and when running a dart entrypoint
for the first time on iOS.
at this point, your dart code’s snapshot
is also loaded into memory from your application’s files.
this is a generic process that also occurs if you used the
dart SDK directly, without the flutter engine.
the dart VM never shuts down after it’s started.
<topic_end>
<topic_start>
creating and running a dart isolate
after the dart runtime is initialized,
the flutter engine’s usage of the dart
runtime is the next step.
this is done by starting a dart isolate in the dart runtime.
the isolate is dart’s container for memory and threads.
a number of auxiliary threads on the host platform are
also created at this point to support the isolate, such
as a thread for offloading GPU handling and another for image decoding.
one isolate exists per FlutterEngine instance, and multiple isolates
can be hosted by the same dart VM.
on android, this happens when you call
DartExecutor.executeDartEntrypoint()
on a FlutterEngine instance.
on iOS, this happens when you call runWithEntrypoint:
on a FlutterEngine.
at this point, your dart code’s selected entrypoint
(the main() function of your dart library’s main.dart file,
by default) is executed. if you called the
flutter function runApp() in your main() function,
then your flutter app or your library’s widget tree is also created
and built. if you need to prevent certain functionalities from executing
in your flutter code, then the AppLifecycleState.detached
enum value indicates that the FlutterEngine isn’t attached
to any UI components such as a FlutterViewController
on iOS or a FlutterActivity on android.
<topic_end>
<topic_start>
attaching a UI to the flutter engine
a standard, full flutter app moves to reach this state as
soon as the app is launched.
in an add-to-app scenario,
this happens when you attach a FlutterEngine
to a UI component such as by calling startActivity()
with an intent built using FlutterActivity.withCachedEngine()
on android. or, by presenting a FlutterViewController
initialized by using initWithEngine: nibName: bundle:
on iOS.
this is also the case if a flutter UI component was launched without
pre-warming a FlutterEngine such as with
FlutterActivity.createDefaultIntent() on android,
or with FlutterViewController initWithProject: nibName: bundle:
on iOS. an implicit FlutterEngine is created in these cases.
behind the scene, both platform’s UI components provide the
FlutterEngine with a rendering surface such as a
surface on android or a CAEAGLLayer or CAMetalLayer
on iOS.
at this point, the layer tree generated by your flutter
program, per frame, is converted into
OpenGL (or vulkan or metal) GPU instructions.
<topic_end>
<topic_start>
memory and latency
showing a flutter UI has a non-trivial latency cost.
this cost can be lessened by starting the flutter engine
ahead of time.
the most relevant choice for add-to-app scenarios is for you
to decide when to pre-load a FlutterEngine
(that is, to load the flutter library, start the dart VM,
and run entrypoint in an isolate), and what the memory and latency
cost is of that pre-warm. you also need to know how the pre-warm
affects the memory and latency cost of rendering a first flutter
frame when the UI component is subsequently attached
to that FlutterEngine.
as of flutter v1.10.3, and testing on a low-end 2015 class device
in release-AOT mode, pre-warming the FlutterEngine costs:
a flutter UI can be attached during the pre-warm.
the remaining time is joined to the time-to-first-frame latency.
memory-wise, a cost sample (variable,
depending on the use case) could be:
latency-wise,
a cost sample (variable, depending on the use case) could be:
the FlutterEngine should be pre-warmed late enough to delay the
memory consumption needed but early enough to avoid combining the
flutter engine start-up time with the first frame latency of
showing flutter.
the exact timing depends on the app’s structure and heuristics.
an example would be to load the flutter engine in the screen
before the screen is drawn by flutter.
given an engine pre-warm, the first frame cost on UI attach is:
memory-wise, the cost is primarily the graphical memory buffer used for
rendering and is dependent on the screen size.
latency-wise, the cost is primarily waiting for the OS callback to provide
flutter with a rendering surface and compiling the remaining shader programs
that are not pre-emptively predictable. this is a one-time cost.
when the flutter UI component is released, the UI-related memory is freed.
this doesn’t affect the flutter state, which lives in the FlutterEngine
(unless the FlutterEngine is also released).
for performance details on creating more than one FlutterEngine,
see multiple flutters.
<topic_end>
<topic_start>
android studio and IntelliJ
<topic_end>
<topic_start>
installation and setup
follow the set up an editor
instructions to install the dart and flutter plugins.
<topic_end>
<topic_start>
updating the plugins
updates to the plugins are shipped on a regular basis.
you should be prompted in the IDE when an update is available.
to check for updates manually:
<topic_end>
<topic_start>
creating projects
you can create a new project in one of several ways.
<topic_end>
<topic_start>
creating a new project
creating a new flutter project from the flutter starter app template
differs between android studio and IntelliJ.
in android studio:
in IntelliJ:
<topic_end>
<topic_start>
setting the company domain
when creating a new app, some flutter IDE plugins ask for an
  organization name in reverse domain order,
  something like com.example. along with the name of the app,
  this is used as the package name for android, and the bundle ID for iOS
  when the app is released. if you think you might ever release this app,
  it is better to specify these now. they cannot be changed once the app
  is released. your organization name should be unique.
<topic_end>
<topic_start>
opening a project from existing source code
to open an existing flutter project:
click open.
error important
  do not use the new > project from existing sources
  option for flutter projects.
<topic_end>
<topic_start>
editing code and viewing issues
the flutter plugin performs code analysis that enables the following:
<topic_end>
<topic_start>
running and debugging
info note
  you can debug your app in a few ways.
the instructions below describe features available in android
  studio and IntelliJ. for information on launching DevTools,
  see running DevTools from android studio in the
  DevTools docs.
running and debugging are controlled from the main toolbar:
<topic_end>
<topic_start>
selecting a target
when a flutter project is open in the IDE, you should see a set of
flutter-specific buttons on the right-hand side of the toolbar.
info note
  if the run and debug buttons are disabled, and no targets are listed,
  flutter has not been able to discover any connected iOS or
  android devices or simulators.
  you need to connect a device, or start a simulator, to proceed.
<topic_end>
<topic_start>
run app without breakpoints
<topic_end>
<topic_start>
run app with breakpoints
<topic_end>
<topic_start>
fast edit and refresh development cycle
flutter offers a best-in-class developer cycle enabling you to see the effect
of your changes almost instantly with the stateful hot reload feature.
to learn more, check out hot reload.
<topic_end>
<topic_start>
show performance data
info note
  to examine performance issues in flutter, see the
  timeline view.
to view the performance data, including the widget rebuild
information, start the app in debug mode, and then open
the performance tool window using
view > tool windows > flutter performance.
to see the stats about which widgets are being rebuilt, and how often,
click show widget rebuild information in the performance pane.
the exact count of the rebuilds for this frame displays in the second
column from the right. for a high number of rebuilds, a yellow spinning
circle displays. the column to the far right shows how many times a
widget was rebuilt since entering the current screen.
for widgets that aren’t rebuilt, a solid grey circle displays.
otherwise, a grey spinning circle displays.
the app shown in this screenshot has been designed to deliver
  poor performance, and the rebuild profiler gives you a clue
  about what is happening in the frame that might cause poor
  performance. the widget rebuild profiler is not a diagnostic
  tool, by itself, about poor performance.
the purpose of this feature is to make you aware when widgets are
rebuilding—you might not realize that this is happening when just
looking at the code. if widgets are rebuilding that you didn’t expect,
it’s probably a sign that you should refactor your code by splitting
up large build methods into multiple widgets.
this tool can help you debug at least four common performance issues:
the whole screen (or large pieces of it) are built by a single
StatefulWidget, causing unnecessary UI building. split up the
UI into smaller widgets with smaller build() functions.
offscreen widgets are being rebuilt. this can happen, for example,
when a ListView is nested in a tall column that extends offscreen.
or when the RepaintBoundary is not set for a list that extends
offscreen, causing the whole list to be redrawn.
the build() function for an AnimatedBuilder draws a subtree that
does not need to be animated, causing unnecessary rebuilds of static
objects.
an opacity widget is placed unnecessarily high in the widget tree.
or, an opacity animation is created by directly manipulating the
opacity property of the opacity widget, causing the widget itself
and its subtree to rebuild.
you can click on a line in the table to navigate to the line
in the source where the widget is created. as the code runs,
the spinning icons also display in the code pane to help you
visualize which rebuilds are happening.
note that numerous rebuilds doesn’t necessarily indicate a problem.
typically you should only worry about excessive rebuilds if you have
already run the app in profile mode and verified that the performance
is not what you want.
and remember, the widget rebuild information is only available in
a debug build. test the app’s performance on a real device in a profile
build, but debug performance issues in a debug build.
<topic_end>
<topic_start>
editing tips for flutter code
if you have additional tips we should share, let us know!
<topic_end>
<topic_start>
assists & quick fixes
assists are code changes related to a certain code identifier.
a number of these are available when the cursor is placed on a
flutter widget identifier, as indicated by the yellow lightbulb icon.
the assist can be invoked by clicking the lightbulb, or by using the
keyboard shortcut (alt+enter on linux and windows,
Option+Return on macOS), as illustrated here:
quick fixes are similar, only they are shown with a piece of code has an error
and they can assist in correcting it. they are indicated with a red lightbulb.
<topic_end>
<topic_start>
wrap with new widget assist
this can be used when you have a widget that you want to wrap in a surrounding
widget, for example if you want to wrap a widget in a row or column.
<topic_end>
<topic_start>
wrap widget list with new widget assist
similar to the assist above, but for wrapping an existing list of
widgets rather than an individual widget.
<topic_end>
<topic_start>
convert child to children assist
changes a child argument to a children argument,
and wraps the argument value in a list.
<topic_end>
<topic_start>
live templates
live templates can be used to speed up entering typical code structures.
they are invoked by typing their prefix, and then selecting it in the code
completion window:
the flutter plugin includes the following templates:
you can also define custom templates in settings > editor > live templates.
<topic_end>
<topic_start>
keyboard shortcuts
hot reload
on linux (keymap default for XWin) and windows the keyboard shortcuts
are Control+Alt+; and Control+Backslash.
on macOS (keymap mac OS x 10.5+ copy) the keyboard shortcuts are
Command+Option and Command+Backslash.
keyboard mappings can be changed in the IDE Preferences/Settings: select
keymap, then enter flutter into the search box in the upper right corner.
right click the binding you want to change and add keyboard shortcut.
<topic_end>
<topic_start>
hot reload vs. hot restart
hot reload works by injecting updated source code files into the running
dart VM (virtual machine). this includes not only adding new classes,
but also adding methods and fields to existing classes,
and changing existing functions.
a few types of code changes cannot be hot reloaded though:
for these changes you can fully restart your application,
without having to end your debugging session. to perform a hot restart,
don’t click the stop button, simply re-click the run button (if in a run
session) or debug button (if in a debug session), or shift-click the ‘hot
reload’ button.
<topic_end>
<topic_start>
editing android code in android studio with full IDE support
opening the root directory of a flutter project doesn’t expose all the android
files to the IDE. flutter apps contain a subdirectory named android. if you
open this subdirectory as its own separate project in android studio, the IDE
will be able to fully support editing and refactoring all android files (like
gradle scripts).
if you already have the entire project opened as a flutter app in android
studio, there are two equivalent ways to open the android files on their own
for editing in the IDE. before trying this, make sure that you’re on the latest
version of android studio and the flutter plugins.
for both options, android studio gives you the option to use separate windows or
to replace the existing window with the new project when opening a second
project. either option is fine.
if you don’t already have the flutter project opened in android studio,
you can open the android files as their own project from the start:
if you haven’t run your flutter app yet, you might see android studio report a
build error when you open the android project. run flutter pub get in
the app’s root directory and rebuild the project by selecting build > make
to fix it.
<topic_end>
<topic_start>
editing android code in IntelliJ IDEA
to enable editing of android code in IntelliJ IDEA, you need to configure the
location of the android SDK:
<topic_end>
<topic_start>
tips and tricks
<topic_end>
<topic_start>
troubleshooting
<topic_end>
<topic_start>
known issues and feedback
important known issues that might impact your experience are documented
in the flutter plugin README file.
all known bugs are tracked in the issue trackers:
we welcome feedback, both on bugs/issues and feature requests.
prior to filing new issues:
when filing new issues, include the output of flutter doctor.
<topic_end>
<topic_start>
visual studio code
<topic_end>
<topic_start>
installation and setup
follow the set up an editor instructions to
install the dart and flutter extensions
(also called plugins).
<topic_end>
<topic_start>
updating the extension
updates to the extensions are shipped on a regular basis.
by default, VS code automatically updates extensions when
updates are available.
to install updates yourself:
<topic_end>
<topic_start>
creating projects
there are a couple ways to create a new project.
<topic_end>
<topic_start>
creating a new project
to create a new flutter project from the flutter
starter app template:
go to view >
command palette….
you can also press ctrl / cmd +
shift + p.
<topic_end>
<topic_start>
opening a project from existing source code
to open an existing flutter project:
go to file > open.
you can also press ctrl / cmd + o
<topic_end>
<topic_start>
editing code and viewing issues
the flutter extension performs code analysis.
the code analysis can:
navigate to type declarations
find type usages.
view all current source code problems.
<topic_end>
<topic_start>
running and debugging
info note
  you can debug your app in a couple of ways.
the instructions below describe features available in VS code.
  for information on using launching DevTools, see
  running DevTools from VS code in the DevTools docs.
start debugging by clicking run > start debugging
from the main IDE window, or press f5.
<topic_end>
<topic_start>
selecting a target device
when a flutter project is open in VS code,
you should see a set of flutter specific entries in the status bar,
including a flutter SDK version and a
device name (or the message no devices):
info note
the flutter extension automatically selects the last device connected.
however, if you have multiple devices/simulators connected, click
device in the status bar to see a pick-list
at the top of the screen. select the device you want to use for
running or debugging.
are you developing for macOS or iOS remotely using
  visual studio code remote? if so, you might need to manually
  unlock the keychain. for more information, see this
  question on StackExchange.
<topic_end>
<topic_start>
run app without breakpoints
go to run > start without debugging.
you can also press ctrl + f5.
<topic_end>
<topic_start>
run app with breakpoints
click run > start debugging.
you can also press f5.
the status bar turns orange to show you are in a debug session.
<topic_end>
<topic_start>
run app in debug, profile, or release mode
flutter offers many different build modes to run your app in. 
you can read more about them in flutter’s build modes.
open the launch.json file in VS code.
if you don’t have a launch.json file:
go to view > run.
you can also press ctrl / cmd +
shift + d
the run and debug panel displays.
click create a launch.json file.
in the configurations section,
change the flutterMode property to
the build mode you want to target.
for example, if you want to run in debug mode,
your launch.json might look like this:
run the app through the run panel.
<topic_end>
<topic_start>
fast edit and refresh development cycle
flutter offers a best-in-class developer cycle enabling you
to see the effect of your changes almost instantly with the
stateful hot reload feature.
to learn more, check out hot reload.
<topic_end>
<topic_start>
advanced debugging
you might find the following advanced debugging tips useful:
<topic_end>
<topic_start>
debugging visual layout issues
during a debug session,
several additional debugging commands are added to the
command palette and to the flutter inspector.
when space is limited, the icon is used as the visual
version of the label.
<topic_end>
<topic_start>
debugging external libraries
by default, debugging an external library is disabled
in the flutter extension. to enable:
<topic_end>
<topic_start>
editing tips for flutter code
if you have additional tips we should share, let us know!
<topic_end>
<topic_start>
assists & quick fixes
assists are code changes related to a certain code identifier.
a number of these are available when the cursor is placed on a
flutter widget identifier, as indicated by the yellow lightbulb icon.
to invoke the assist, click the lightbulb as shown in the following screenshot:
you can also press ctrl / cmd + .
quick fixes are similar,
only they are shown with a piece of code has an error and they
can assist in correcting it.
<topic_end>
<topic_start>
snippets
snippets can be used to speed up entering typical code structures.
they are invoked by typing their prefix,
and then selecting from the code completion window:
the flutter extension includes the following snippets:
you can also define custom snippets by executing
configure user snippets from the command palette.
<topic_end>
<topic_start>
keyboard shortcuts
you can also press ctrl + f5
(cmd + f5  on macOS).
keyboard mappings can be changed by executing the
open keyboard shortcuts command from the command palette.
<topic_end>
<topic_start>
hot reload vs. hot restart
hot reload works by injecting updated source code files into the
running dart VM (virtual machine). this includes not only
adding new classes, but also adding methods and fields to
existing classes, and changing existing functions.
a few types of code changes cannot be hot reloaded though:
for these changes, restart your app without
ending your debugging session. to perform a hot restart,
run the flutter: hot restart command from the command palette.
you can also press
ctrl + shift + f5
or cmd + shift + f5 on macOS.
<topic_end>
<topic_start>
troubleshooting
<topic_end>
<topic_start>
known issues and feedback
all known bugs are tracked in the issue tracker:
dart and flutter extensions GitHub issue tracker.
we welcome feedback,
both on bugs/issues and feature requests.
prior to filing new issues:
when filing new issues, include flutter doctor output.
<topic_end>
<topic_start>
DevTools
<topic_end>
<topic_start>
what is DevTools?
DevTools is a suite of performance and debugging tools
for dart and flutter.
for a video introduction to DevTools, check out
the following deep dive and use case walkthrough:
dive in to DevTools
<topic_end>
<topic_start>
what can i do with DevTools?
here are some of the things you can do with DevTools:
we expect you to use DevTools in conjunction with
your existing IDE or command-line based development workflow.
<topic_end>
<topic_start>
how to start DevTools
see the VS code, android Studio/IntelliJ, or
command line pages for instructions on how to start DevTools.
<topic_end>
<topic_start>
troubleshooting some standard issues
question: my app looks janky or stutters.
  how do i fix it?
answer: performance issues can cause UI frames
  to be janky and/or slow down some operations.
for more information, check out the
performance page.
question: i see a lot of garbage collection (gc) events occurring.
  is this a problem?
answer: frequent GC events might display on
  the DevTools > memory > memory chart. in most cases,
  it’s not a problem.
if your app has frequent background activity with some idle time,
flutter might use that opportunity to collect the created objects
without performance impact.
<topic_end>
<topic_start>
providing feedback
please give DevTools a try, provide feedback, and file issues
in the DevTools issue tracker. thanks!
<topic_end>
<topic_start>
other resources
for more information on debugging and profiling
flutter apps, see the debugging page and,
in particular, its list of other resources.
for more information on using DevTools with dart command-line apps, see the
DevTools documentation on dart.dev.
<topic_end>
<topic_start>
DevTools
<topic_end>
<topic_start>
what is DevTools?
DevTools is a suite of performance and debugging tools
for dart and flutter.
for a video introduction to DevTools, check out
the following deep dive and use case walkthrough:
dive in to DevTools
<topic_end>
<topic_start>
what can i do with DevTools?
here are some of the things you can do with DevTools:
we expect you to use DevTools in conjunction with
your existing IDE or command-line based development workflow.
<topic_end>
<topic_start>
how to start DevTools
see the VS code, android Studio/IntelliJ, or
command line pages for instructions on how to start DevTools.
<topic_end>
<topic_start>
troubleshooting some standard issues
question: my app looks janky or stutters.
  how do i fix it?
answer: performance issues can cause UI frames
  to be janky and/or slow down some operations.
for more information, check out the
performance page.
question: i see a lot of garbage collection (gc) events occurring.
  is this a problem?
answer: frequent GC events might display on
  the DevTools > memory > memory chart. in most cases,
  it’s not a problem.
if your app has frequent background activity with some idle time,
flutter might use that opportunity to collect the created objects
without performance impact.
<topic_end>
<topic_start>
providing feedback
please give DevTools a try, provide feedback, and file issues
in the DevTools issue tracker. thanks!
<topic_end>
<topic_start>
other resources
for more information on debugging and profiling
flutter apps, see the debugging page and,
in particular, its list of other resources.
for more information on using DevTools with dart command-line apps, see the
DevTools documentation on dart.dev.
<topic_end>
<topic_start>
install and run DevTools from android studio
<topic_end>
<topic_start>
install the flutter plugin
install the flutter plugin if you don’t already have it installed.
this can be done using the normal plugins page in the IntelliJ
and android studio settings. once that page is open,
you can search the marketplace for the flutter plugin.
<topic_end>
<topic_start>
start an app to debug
to open DevTools, you first need to run a flutter app.
this can be accomplished by opening a flutter project,
ensuring that you have a device connected,
and clicking the run or debug toolbar buttons.
<topic_end>
<topic_start>
launch DevTools from the toolbar/menu
once an app is running,
you can start DevTools using one of the following:
<topic_end>
<topic_start>
launch DevTools from an action
you can also open DevTools from an IntelliJ action.
open the find action… dialog
(on macOS, press cmd + shift + a),
and search for the open DevTools action.
when you select that action,
DevTools is installed (if it isn’t already), the DevTools server
launches, and a browser instance opens pointing to the DevTools app.
when opened with an IntelliJ action, DevTools is not connected
to a flutter app. you’ll need to provide a service protocol port
for a currently running app. you can do this using the inline
connect to a running app dialog.
<topic_end>
<topic_start>
install and run DevTools from VS code
<topic_end>
<topic_start>
install the VS code extensions
to use the DevTools from VS code, you need the dart extension.
if you’re debugging flutter applications, you should also install
the flutter extension.
<topic_end>
<topic_start>
start an application to debug
start a debug session for your application by opening the root
folder of your project (the one containing pubspec.yaml)
in VS code and clicking run > start debugging (f5).
<topic_end>
<topic_start>
launch DevTools
once the debug session is active and the application has started,
the open DevTools commands become available in the
VS code command palette (f1):
the chosen tool will be opened embedded inside VS code.
you can choose to have DevTools always opened in a browser with the
dart.embedDevTools setting, and control whether it opens as a full window or
in a new column next to your current editor with the dart.devToolsLocation
setting.
a full list of Dart/Flutter settings are available
here or in the
VS code settings editor.
some recommendation settings for Dart/Flutter in VS code can be found
here.
you can also see whether DevTools is running and launch it in a browser from the
language status area (the {} icon next to dart in the status bar).
<topic_end>
<topic_start>
install and run DevTools from the command line
to run dart DevTools from the CLI, you must have dart on your path. then
you can run the following command to launch DevTools:
to upgrade DevTools, upgrade your dart SDK. if a newer dart SDK
includes a newer version of DevTools, dart devtools will automatically
launch this version. if which dart points to the dart SDK included in
your flutter SDK, then DevTools will be upgraded when you upgrade your
flutter SDK to a newer version.
when you run DevTools from the command line, you should see output that
looks something like:
<topic_end>
<topic_start>
start an application to debug
next, start an app to connect to.
this can be either a flutter application
or a dart command-line application.
the command below specifies a flutter app:
you need to have a device connected, or a simulator open,
for flutter run to work. once the app starts, you’ll see a
message in your terminal that looks like the following:
open the DevTools instance connected to your app
by opening the second link in chrome.
this URL contains a security token, 
so it’s different for each run of your app. 
this means that if you stop your application and re-run it, 
you need to connect to DevTools again with the new URL.
<topic_end>
<topic_start>
connect to a new app instance
if your app stops running
or you opened DevTools manually,
you should see a connect dialog:
you can manually connect DevTools to a new app instance
by copying the observatory link you got from running your app,
such as http://127.0.0.1:52129/QjqebSY4lQ8=/
and pasting it into the connect dialog:
<topic_end>
<topic_start>
using the flutter inspector
info note
  the inspector works with all flutter applications.
<topic_end>
<topic_start>
what is it?
the flutter widget inspector is a powerful tool for visualizing and
exploring flutter widget trees. the flutter framework uses widgets
as the core building block for anything from controls
(such as text, buttons, and toggles),
to layout (such as centering, padding, rows, and columns).
the inspector helps you visualize and explore flutter widget
trees, and can be used for the following:
<topic_end>
<topic_start>
get started
to debug a layout issue, run the app in debug mode and
open the inspector by clicking the flutter inspector
tab on the DevTools toolbar.
info note
  you can still access the flutter inspector directly from
  android Studio/IntelliJ, but you might prefer the
  more spacious view when running it from DevTools
  in a browser.
<topic_end>
<topic_start>
debugging layout issues visually
the following is a guide to the features available in the
inspector’s toolbar. when space is limited, the icon is
used as the visual version of the label.
enable this button in order to select
    a widget on the device to inspect it. for more information,
    see inspecting a widget.
<topic_end>
<topic_start>
inspecting a widget
you can browse the interactive widget tree to view nearby
widgets and see their field values.
to locate individual UI elements in the widget tree,
click the select widget mode button in the toolbar.
this puts the app on the device into a “widget select” mode.
click any widget in the app’s UI; this selects the widget on the
app’s screen, and scrolls the widget tree to the corresponding node.
toggle the select widget mode button again to exit
widget select mode.
when debugging layout issues, the key fields to look at are the
size and constraints fields. the constraints flow down the tree,
and the sizes flow back up. for more information on how this works,
see understanding constraints.
<topic_end>
<topic_start>
flutter layout explorer
the flutter layout explorer helps you to better understand
flutter layouts.
for an overview of what you can do with this tool, see
the flutter explorer video:
you might also find the following step-by-step article useful:
<topic_end>
<topic_start>
using the layout explorer
from the flutter inspector, select a widget. the layout explorer
supports both flex layouts and fixed size layouts, and has
specific tooling for both kinds.
<topic_end>
<topic_start>
flex layouts
when you select a flex widget (for example, row, column, flex)
or a direct child of a flex widget, the flex layout tool will
appear in the layout explorer.
the layout explorer visualizes how flex widgets and their
children are laid out. the explorer identifies the main axis
and cross axis, as well as the current alignment for each
(for example, start, end, and spaceBetween).
it also shows details like flex factor, flex fit, and layout
constraints.
additionally, the explorer shows layout constraint violations
and render overflow errors. violated layout constraints
are colored red, and overflow errors are presented in the
standard  “yellow-tape” pattern, as you might see on a running
device. these visualizations aim to improve understanding of
why overflow errors occur as well as how to fix them.
clicking a widget in the layout explorer mirrors
the selection on the on-device inspector. select widget mode
needs to be enabled for this. to enable it,
click on the select widget mode button in the inspector.
for some properties, like flex factor, flex fit, and alignment,
you can modify the value via dropdown lists in the explorer.
when modifying a widget property, you see the new value reflected
not only in the layout explorer, but also on the
device running your flutter app. the explorer animates
on property changes so that the effect of the change is clear.
widget property changes made from the layout explorer don’t
modify your source code and are reverted on hot reload.
<topic_end>
<topic_start>
interactive properties
layout explorer supports modifying mainAxisAlignment,
crossAxisAlignment, and FlexParentData.flex.
in the future, we may add support for additional properties
such as mainAxisSize, textDirection, and
FlexParentData.fit.
<topic_end>
<topic_start>
mainAxisAlignment
supported values:
<topic_end>
<topic_start>
crossAxisAlignment
supported values:
<topic_end>
<topic_start>
FlexParentData.flex
layout explorer supports 7 flex options in the UI
(null, 0, 1, 2, 3, 4, 5), but technically the flex
factor of a flex widget’s child can be any int.
<topic_end>
<topic_start>
flexible.fit
layout explorer supports the two different types of
FlexFit: loose and tight.
<topic_end>
<topic_start>
fixed size layouts
when you select a fixed size widget that is not a child
of a flex widget, fixed size layout information will appear
in the layout explorer. you can see size, constraint, and padding
information for both the selected widget and its nearest upstream
RenderObject.
<topic_end>
<topic_start>
visual debugging
the flutter inspector provides several options for visually debugging your app.
<topic_end>
<topic_start>
slow animations
when enabled, this option runs animations 5 times slower for easier visual
inspection.
this can be useful if you want to carefully observe and tweak an animation that
doesn’t look quite right.
this can also be set in code:
<code_start>
import 'package:flutter/scheduler.dart';
void setSlowAnimations() {
  timeDilation = 5.0;
}
<code_end>
this slows the animations by 5x.
<topic_end>
<topic_start>
see also
the following links provide more info.
the following screen recordings show before and after slowing an animation.
<topic_end>
<topic_start>
show guidelines
this feature draws guidelines over your app that display render boxes, alignments,
paddings, scroll views, clippings and spacers.
this tool can be used for better understanding your layout. for instance,
by finding unwanted padding or understanding widget alignment.
you can also enable this in code:
<code_start>
import 'package:flutter/rendering.dart';
void showLayoutGuidelines() {
  debugPaintSizeEnabled = true;
}
<code_end>
<topic_end>
<topic_start>
render boxes
widgets that draw to the screen create a render box, the
building blocks of flutter layouts. they’re shown with a bright blue border:
<topic_end>
<topic_start>
alignments
alignments are shown with yellow arrows. these arrows show the vertical
and horizontal offsets of a widget relative to its parent.
for example, this button’s icon is shown as being centered by the four arrows:
<topic_end>
<topic_start>
padding
padding is shown with a semi-transparent blue background:
<topic_end>
<topic_start>
scroll views
widgets with scrolling contents (such as list views) are shown with green arrows:
<topic_end>
<topic_start>
clipping
clipping, for example when using the ClipRect widget, are shown
with a dashed pink line with a scissors icon:
<topic_end>
<topic_start>
spacers
spacer widgets are shown with a grey background,
such as this SizedBox without a child:
<topic_end>
<topic_start>
show baselines
this option makes all baselines visible.
baselines are horizontal lines used to position text.
this can be useful for checking whether text is precisely aligned vertically.
for example, the text baselines in the following screenshot are slightly misaligned:
the baseline widget can be used to adjust baselines.
a line is drawn on any render box that has a baseline set;
alphabetic baselines are shown as green and ideographic as yellow.
you can also enable this in code:
<code_start>
import 'package:flutter/rendering.dart';
void showBaselines() {
  debugPaintBaselinesEnabled = true;
}
<code_end>
<topic_end>
<topic_start>
highlight repaints
this option draws a border around all render boxes
that changes color every time that box repaints.
this rotating rainbow of colors is useful for finding parts of your app
that are repainting too often and potentially harming performance.
for example, one small animation could be causing an entire page
to repaint on every frame.
wrapping the animation in a RepaintBoundary widget limits
the repainting to just the animation.
here the progress indicator causes its container to repaint:
<code_start>
class EverythingRepaintsPage extends StatelessWidget {
  const EverythingRepaintsPage({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Repaint example')),
      body: const center(
        child: CircularProgressIndicator(),
      ),
    );
  }
}
<code_end>
wrapping the progress indicator in a RepaintBoundary causes
only that section of the screen to repaint:
<code_start>
class AreaRepaintsPage extends StatelessWidget {
  const AreaRepaintsPage({super.key});
  @override
  widget build(BuildContext context) {
    return scaffold(
      appBar: AppBar(title: const Text('Repaint example')),
      body: const center(
        child: RepaintBoundary(
          child: CircularProgressIndicator(),
        ),
      ),
    );
  }
}
<code_end>
RepaintBoundary widgets have tradeoffs. they can help with performance,
but they also have an overhead of creating a new canvas,
which uses additional memory.
you can also enable this option in code:
<code_start>
import 'package:flutter/rendering.dart';
void highlightRepaints() {
  debugRepaintRainbowEnabled = true;
}
<code_end>
<topic_end>
<topic_start>
highlight oversized images
this option highlights images that are too large by both inverting their colors
and flipping them vertically:
the highlighted images use more memory than is required;
for example, a large 5mb image displayed at 100 by 100 pixels.
such images can cause poor performance, especially on lower-end devices
and when you have many images, as in a list view,
this performance hit can add up.
information about each image is printed in the debug console:
images are deemed too large if they use at least 128kb more than required.
<topic_end>
<topic_start>
fixing images
wherever possible, the best way to fix this problem is resizing
the image asset file so it’s smaller.
if this isn’t possible, you can use the cacheHeight and cacheWidth
parameters on the image constructor:
<code_start>
class ResizedImage extends StatelessWidget {
  const ResizedImage({super.key});
  @override
  widget build(BuildContext context) {
    return image.asset(
      'dash.png',
      cacheHeight: 213,
      cacheWidth: 392,
    );
  }
}
<code_end>
this makes the engine decode this image at the specified size,
and reduces memory usage (decoding and storage is still more expensive
than if the image asset itself was shrunk).
the image is rendered to the constraints of the layout or width and height
regardless of these parameters.
this property can also be set in code:
<code_start>
void showOversizedImages() {
  debugInvertOversizedImages = true;
}
<code_end>
<topic_end>
<topic_start>
more information
you can learn more at the following link:
<topic_end>
<topic_start>
details tree
select the widget details tree tab to display the details tree for the
selected widget. from here, you can gather useful information about a
widget’s properties, render object, and children.
<topic_end>
<topic_start>
track widget creation
part of the functionality of the flutter inspector is based on
instrumenting the application code in order to better understand
the source locations where widgets are created. the source
instrumentation allows the flutter inspector to present the
widget tree in a manner similar to how the UI was defined
in your source code. without it, the tree of nodes in the
widget tree are much deeper, and it can be more difficult to
understand how the runtime widget hierarchy corresponds to
your application’s UI.
you can disable this feature by passing --no-track-widget-creation to
the flutter run command.
here are examples of what your widget tree might look like
with and without track widget creation enabled.
track widget creation enabled (default):
track widget creation disabled (not recommended):
this feature prevents otherwise-identical const widgets from
being considered equal in debug builds. for more details, see
the discussion on common problems when debugging.
<topic_end>
<topic_start>
inspector settings
<topic_end>
<topic_start>
enable hover inspection
hovering over any widget displays its properties and values.
toggling this value enables or disables the hover inspection functionality.
<topic_end>
<topic_start>
package directories
by default, DevTools limits the widgets displayed in the widget tree
to those from the project’s root directory, and those from flutter. this
filtering only applies to the widgets in the inspector widget tree (left side
of the inspector) – not the widget details tree (right side of the inspector
in the same tab view as the layout explorer). in the widget details tree, you
will be able to see all widgets in the tree from all packages.
in order to show other widgets, a parent directory of theirs must be added to the package directories.
for example, consider the following directory structure:
running your app from project_foo_app displays only widgets from
project_foo/pkgs/project_foo_app in the widget inspector tree.
to show widgets from widgets_A in the widget tree,
add project_foo/pkgs/widgets_A to the package directories.
to display all widgets from your project root in the widget tree,
add project_foo to the package directories.
changes to your package directories persist the next time the
widget inspector is opened for the app.
<topic_end>
<topic_start>
other resources
for a demonstration of what’s generally possible with the inspector,
see the DartConf 2018 talk demonstrating the IntelliJ version
of the flutter inspector.
to learn how to visually debug layout issues
using DevTools, check out a guided
flutter inspector tutorial.
<topic_end>
<topic_start>
using the performance view
info note
  the DevTools performance view works for flutter mobile and desktop apps.
  for web apps, flutter adds timeline events to the
  performance panel of chrome DevTools instead.
  to learn about profiling web apps, check out debugging web performance.
the performance page can help you diagnose performance
problems and UI jank in your application.
this page offers timing and performance information
for activity in your application.
it consists of several tools to help you identify
the cause of poor performance in your app:
use a profile build of your application to analyze performance.
  frame rendering times aren’t indicative of release performance
  when running in debug mode. run your app in profile mode,
  which still preserves useful debugging information.
the performance view also supports importing and exporting of
data snapshots. for more information,
check out the import and export section.
<topic_end>
<topic_start>
what is a frame in flutter?
flutter is designed to render its UI at 60 frames per second
(fps), or 120 fps on devices capable of 120hz updates.
each render is called a frame.
this means that, approximately every 16ms, the UI updates
to reflect animations or other changes to the UI. a frame
that takes longer than 16ms to render causes jank
(jerky motion) on the display device.
<topic_end>
<topic_start>
flutter frames chart
this chart contains flutter frame information for your application.
each bar set in the chart represents a single flutter frame.
the bars are color-coded to highlight the different portions
of work that occur when rendering a flutter frame: work from
the UI thread and work from the raster thread (previously known
as the GPU thread).
this chart contains flutter frame timing information for your
application. each pair of bars in the chart represents a single
flutter frame. selecting a frame from this chart updates the data
that is displayed below in the frame analysis tab
or the timeline events tab.
(as of DevTools 2.23.1, the raster stats
is a standalone feature without data per frame).
the flutter frames chart updates when new frames
are drawn in your app. to pause updates to this chart,
click the pause button to the right of the chart.
this chart can be collapsed to provide more viewing space
for data below by clicking the flutter frames button above the chart.
the pair of bars representing each flutter frame are color-coded
to highlight the different portions of work that occur when rendering
a flutter frame: work from the UI thread and work from the raster thread
(previously known as the GPU thread).
<topic_end>
<topic_start>
UI
the UI thread executes dart code in the dart VM. this includes
code from your application as well as the flutter framework.
when your app creates and displays a scene, the UI thread creates
a layer tree, a lightweight object containing device-agnostic
painting commands, and sends the layer tree to the raster thread
to be rendered on the device. do not block this thread.
<topic_end>
<topic_start>
raster
the raster thread (previously known as the GPU thread)
executes graphics code from the flutter engine.
this thread takes the layer tree and displays it by talking to
the GPU (graphic processing unit). you can’t directly access
the raster thread or its data, but if this thread is slow,
it’s a result of something you’ve done in the dart code.
skia, the graphics library, runs on this thread.
impeller (in the stable channel for iOS)
also uses this thread.
sometimes a scene results in a layer tree that is easy to construct,
but expensive to render on the raster thread. in this case, you
need to figure out what your code is doing that is causing
rendering code to be slow. specific kinds of workloads are more
difficult for the GPU. they might involve unnecessary calls to
saveLayer(), intersecting opacities with multiple objects,
and clips or shadows in specific situations.
for more information on profiling, check out
identifying problems in the GPU graph.
<topic_end>
<topic_start>
jank (slow frame)
the frame rendering chart shows jank with a red overlay.
a frame is considered to be janky if it takes more than
~16 ms to complete (for 60 FPS devices). to achieve a frame rendering rate of
60 FPS (frames per second), each frame must render in
~16 ms or less. when this target is missed, you may
experience UI jank or dropped frames.
for more information on how to analyze your app’s performance,
check out flutter performance profiling.
<topic_end>
<topic_start>
shader compilation
shader compilation occurs when a shader is first used in your flutter
app. frames that perform shader compilation are marked in dark
red:
for more information on how to reduce shader compilation jank,
check out reduce shader compilation jank on mobile.
<topic_end>
<topic_start>
frame analysis tab
selecting a janky frame (slow, colored in red)
from the flutter frames chart above shows debugging hints
in the frame analysis tab. these hints help you diagnose
jank in your app, and notify you of any expensive operations
that we have detected that might have contributed to the slow frame time.
<topic_end>
<topic_start>
raster stats tab
info note
  for best results, this tool should be used with
  the impeller rendering engine. when using skia,
  the raster stats reported might be inconsistent
  due to the timing of when shaders are compiled.
if you have flutter frames that are janking with
slow raster thread times, this tool might be able
to help you diagnose the source of the slow performance.
to generate raster stats:
if you see an expensive layer, find the dart code in your app
that is producing this layer and investigate further.
you can make changes to your code, hot reload,
and take new snapshots to see if the performance of a layer
was improved by your change.
<topic_end>
<topic_start>
timeline events tab
the timeline events chart shows all event tracing from your application.
the flutter framework emits timeline events as it works to build frames,
draw scenes, and track other activity such as HTTP request timings
and garbage collection. these events show up here in the timeline.
you can also send your own timeline events using the dart:developer
timeline and TimelineTask APIs.
for help with navigating and using the trace viewer,
click the ? button at the top right of the timeline
events tab bar. to refresh the timeline with new events from
your application, click the refresh button
(also in the upper right corner of the tab controls).
<topic_end>
<topic_start>
advanced debugging tools
<topic_end>
<topic_start>
enhance tracing
to view more detailed tracing in the timeline events chart,
use the options in the enhance tracing dropdown:
info note
  frame times might be negatively affected when these options are enabled.
to see the new timeline events, reproduce the activity
in your app that you are interested in tracing,
and then select a frame to inspect the timeline.
<topic_end>
<topic_start>
track widget builds
to see the build() method events in the timeline,
enable the track widget builds option.
the name of the widget is shown in the timeline event.
watch this video for an example of tracking widget builds
<topic_end>
<topic_start>
track layouts
to see render object layout events in the timeline,
enable the track layouts option:
watch this video for an example of tracking layouts
<topic_end>
<topic_start>
track paints
to see render object paint events in the timeline,
enable the track paints option:
watch this video for an example of tracking paints
<topic_end>
<topic_start>
more debugging options
to diagnose performance problems related to rendering layers,
toggle off a rendering layer.
these options are enabled by default.
to see the effects on your app’s performance,
reproduce the activity in your app.
then select the new frames in the frames chart
to inspect the timeline events
with the layers disabled.
if raster time has significantly decreased,
excessive use of the effects you disabled might be contributing
to the jank you saw in your app.
<topic_end>
<topic_start>
import and export
DevTools supports importing and exporting performance snapshots.
clicking the export button (upper-right corner above the
frame rendering chart) downloads a snapshot of the current data on the
performance page. to import a performance snapshot, you can drag and drop the
snapshot into DevTools from any page. note that DevTools only
supports importing files that were originally exported from DevTools.
<topic_end>
<topic_start>
other resources
to learn how to monitor an app’s performance and
detect jank using DevTools, check out a guided
performance view tutorial.
<topic_end>
<topic_start>
using the CPU profiler view
info note
  the CPU profiler view works with dart CLI and mobile apps only.
  use chrome DevTools to analyze performance
  of a web app.
the CPU profiler view allows you to record and profile a
session from your dart or flutter application.
the profiler can help you solve performance problems
or generally understand your app’s CPU activity.
the dart VM collects CPU samples
(a snapshot of the CPU call stack at a single point in time)
and sends the data to DevTools for visualization.
by aggregating many CPU samples together,
the profiler can help you understand where the CPU
spends most of its time.
info note
if you are running a flutter application,
  use a profile build to analyze performance.
  CPU profiles are not indicative of release performance
  unless your flutter application is run in profile mode.
<topic_end>
<topic_start>
CPU profiler
start recording a CPU profile by clicking record.
when you are done recording, click stop. at this point,
CPU profiling data is pulled from the VM and displayed
in the profiler views (call tree, bottom up, method table,
and flame chart).
to load all available CPU samples without manually
recording and stopping, you can click load all CPU samples,
which pulls all CPU samples that the VM has recorded and
stored in its ring buffer, and then displays those
CPU samples in the profiler views.
<topic_end>
<topic_start>
bottom up
this table provides a bottom-up representation
of a CPU profile. this means that each top-level method,
or root, in the bottom up table is actually the
top method in the call stack for one or more CPU samples.
in other words, each top-level method in a bottom up
table is a leaf node from the top down table
(the call tree).
in this table, a method can be expanded to show its callers.
this view is useful for identifying expensive methods
in a CPU profile. when a root node in this table
has a high self time, that means that many CPU samples
in this profile ended with that method on top of the call stack.
see the guidelines section below to learn how to
enable the blue and green vertical lines seen in this image.
tooltips can help you understand the values in each column:
for top-level methods in the bottom-up tree
    (stack frames that were at the top of at least one
    CPU sample), this is the time the method spent executing
    its own code, as well as the code for any methods that
    it called.
for top-level methods in the bottom-up tree
    (stack frames that were at the top of at least one CPU
    sample), this is the time the method spent executing only
    its own code.
    for children methods in the bottom-up tree (the callers),
    this is the self time of the top-level method (the callee)
    when called through the child method (the caller).
table element (self time)
<topic_end>
<topic_start>
call tree
this table provides a top-down representation of a CPU profile.
this means that each top-level method in the call tree is a root
of one or more CPU samples. in this table,
a method can be expanded to show its callees.
this view is useful for identifying expensive paths in a CPU profile.
when a root node in this table has a high total time,
that means that many CPU samples in this profile started
with that method on the bottom of the call stack.
see the guidelines section below to learn how to
enable the blue and green vertical lines seen in this image.
tooltips can help you understand the values in each column:
<topic_end>
<topic_start>
method table
the method table provides CPU statistics for each method
contained in a CPU profile. in the table on the left,
all available methods are listed with their total and
self time.
total time is the combined time that a method spent
anywhere on the call stack, or in other words,
the time a method spent executing its own code and
any code for methods that it called.
self time is the combined time that a method spent
on top of the call stack, or in other words,
the time a method spent executing only its own code.
selecting a method from the table on the left shows
the call graph for that method. the call graph shows
a method’s callers and callees and their respective
caller / callee percentages.
<topic_end>
<topic_start>
flame chart
the flame chart view is a graphical representation of
the call tree. this is a top-down view
of a CPU profile, so in this chart,
the top-most method calls the one below it.
the width of each flame chart element represents the
amount of time that a method spent on the call stack.
like the call tree, this view is useful for identifying
expensive paths in a CPU profile.
the help menu, which can be opened by clicking the ? icon
next to the search bar, provides information about how to
navigate and zoom within the chart and a color-coded legend.
<topic_end>
<topic_start>
CPU sampling rate
DevTools sets a default rate at which the VM collects CPU samples:
1 sample / 250 μs (microseconds). this is selected by default on
the CPU profiler page as “cpu sampling rate: medium”.
this rate can be modified using the selector at the top
of the page.
the low, medium, and high sampling rates are
1,000 hz, 4,000 hz, and 20,000 hz, respectively.
it’s important to know the trade-offs
of modifying this setting.
a profile that was recorded with a higher sampling rate
yields a more fine-grained CPU profile with more samples.
this might affect performance of your app since the VM
is being interrupted more often to collect samples.
this also causes the VM’s CPU sample buffer to overflow more quickly.
the VM has limited space where it can store CPU sample information.
at a higher sampling rate, the space fills up and begins
to overflow sooner than it would have if a lower sampling
rate was used.
this means that you might not have access to CPU samples
from the beginning of the recorded profile, depending
on whether the buffer overflows during the time of recording.
a profile that was recorded with a lower sampling rate
yields a more coarse-grained CPU profile with fewer samples.
this affects your app’s performance less,
but you might have access to less information about what
the CPU was doing during the time of the profile.
the VM’s sample buffer also fills more slowly, so you can see
CPU samples for a longer period of app run time.
this means that you have a better chance of viewing CPU
samples from the beginning of the recorded profile.
<topic_end>
<topic_start>
filtering
when viewing a CPU profile, you can filter the data by
library, method name, or UserTag.
<topic_end>
<topic_start>
guidelines
when looking at a call tree or bottom up view,
sometimes the trees can be very deep.
to help with viewing parent-child relationships in a deep tree,
enable the display guidelines option.
this adds vertical guidelines between parent and child in the tree.
<topic_end>
<topic_start>
other resources
to learn how to use DevTools to analyze
the CPU usage of a compute-intensive mandelbrot app,
check out a guided CPU profiler view tutorial.
also, learn how to analyze CPU usage when the app
uses isolates for parallel computing.
<topic_end>
<topic_start>
using the memory view
the memory view provides insights into details
of the application’s memory allocation and
tools to detect and debug specific issues.
info note
  this page is up to date for DevTools 2.23.0.
for information on how to locate DevTools screens in different IDEs,
check out the DevTools overview.
to better understand the insights found on this page,
the first section explains how dart manages memory.
if you already understand dart’s memory management,
you can skip to the memory view guide.
<topic_end>
<topic_start>
reasons to use the memory view
use the memory view for preemptive memory optimization or when
your application experiences one of the following conditions:
<topic_end>
<topic_start>
basic memory concepts
dart objects created using a class constructor
(for example, by using MyClass()) live in a
portion of memory called the heap. the memory
in the heap is managed by the dart VM (virtual machine).
the dart VM allocates memory for the object at the moment of the object creation,
and releases (or deallocates) the memory when the object
is no longer used (see dart garbage collection).
<topic_end>
<topic_start>
object types
<topic_end>
<topic_start>
disposable object
a disposable object is any dart object that defines a dispose() method.
to avoid memory leaks, invoke dispose when the object isn’t needed anymore.
<topic_end>
<topic_start>
memory-risky object
a memory-risky object is an object that might cause a memory leak,
if it is not disposed properly or disposed but not GCed.
<topic_end>
<topic_start>
root object, retaining path, and reachability
<topic_end>
<topic_start>
root object
every dart application creates a root object that references,
directly or indirectly, all other objects the application allocates.
<topic_end>
<topic_start>
reachability
if, at some moment of the application run,
the root object stops referencing an allocated object,
the object becomes unreachable,
which is a signal for the garbage collector (gc)
to deallocate the object’s memory.
<topic_end>
<topic_start>
retaining path
the sequence of references from root to an object
is called the object’s retaining path,
as it retains the object’s memory from the garbage collection.
one object can have many retaining paths.
objects with at least one retaining path are
called reachable objects.
<topic_end>
<topic_start>
example
the following example illustrates the concepts:
<topic_end>
<topic_start>
shallow size vs retained size
shallow size includes only the size of the object
and its references, while retained size also includes
the size of the retained objects.
the retained size of the root object includes
all reachable dart objects.
in the following example, the size of myHugeInstance
isn’t part of the parent’s or child’s shallow sizes,
but is part of their retained sizes:
in DevTools calculations, if an object has more
than one retaining path, its size is assigned as
retained only to the members of the shortest retaining path.
in this example the object x has two retaining paths:
only members of the shortest path (d and e) will include
x into their retaining size.
<topic_end>
<topic_start>
memory leaks happen in dart?
garbage collector cannot prevent all types of memory leaks, and developers
still need to watch objects to have leak-free lifecycle.
<topic_end>
<topic_start>
why can’t the garbage collector prevent all leaks?
while the garbage collector takes care of all
unreachable objects, it’s the responsibility
of the application to ensure that unneeded objects
are no longer reachable (referenced from the root).
so, if non-needed objects are left referenced
(in a global or static variable,
or as a field of a long-living object),
the garbage collector can’t recognize them,
the memory allocation grows progressively,
and the app eventually crashes with an out-of-memory error.
<topic_end>
<topic_start>
why closures require extra attention
one hard-to-catch leak pattern relates to using closures.
in the following code, a reference to the
designed-to-be short-living myHugeObject is implicitly
stored in the closure context and passed to setHandler.
as a result, myHugeObject won’t be garbage collected
as long as handler is reachable.
<topic_end>
<topic_start>
why BuildContext requires extra attention
an example of a large, short-living object that
might squeeze into a long-living area and thus cause leaks,
is the context parameter passed to flutter’s
build method.
the following code is leak prone,
as useHandler might store the handler
in a long-living area:
<topic_end>
<topic_start>
how to fix leak prone code?
the following code is not leak prone,
because:
<topic_end>
<topic_start>
general rule for BuildContext
in general, use the following rule for a
BuildContext: if the closure doesn’t outlive
the widget, it’s ok to pass the context to the closure.
stateful widgets require extra attention.
they consist of two classes: the widget and the
widget state,
where the widget is short living,
and the state is long living. the build context,
owned by the widget, should never be referenced
from the state’s fields, as the state won’t be garbage
collected together with the widget, and can significantly outlive it.
<topic_end>
<topic_start>
memory leak vs memory bloat
in a memory leak, an application progressively uses memory,
for example, by repeatedly creating a listener,
but not disposing it.
memory bloat uses more memory than is necessary for
optimal performance, for example, by using overly large
images or keeping streams open through their lifetime.
both leaks and bloats, when large,
cause an application to crash with an out-of-memory error.
however, leaks are more likely to cause memory issues,
because even a small leak,
if repeated many times, leads to a crash.
<topic_end>
<topic_start>
memory view guide
the DevTools memory view helps you investigate
memory allocations (both in the heap and external),
memory leaks, memory bloat, and more. the view
has the following features:
<topic_end>
<topic_start>
expandable chart
the expandable chart provides the following features:
<topic_end>
<topic_start>
memory anatomy
a timeseries graph visualizes the state of
flutter memory at successive intervals of time.
each data point on the chart corresponds to the
timestamp (x-axis) of measured quantities (y-axis)
of the heap. for example, usage, capacity, external,
garbage collection, and resident set size are captured.
<topic_end>
<topic_start>
memory overview chart
the memory overview chart is a timeseries graph
of collected memory statistics. it visually presents
the state of the dart or flutter heap and dart’s
or flutter’s native memory over time.
the chart’s x-axis is a timeline of events (timeseries).
the data plotted in the y-axis all has a timestamp of
when the data was collected. in other words,
it shows the polled state (capacity, used, external,
RSS (resident set size), and GC (garbage collection))
of the memory every 500 ms. this helps provide a live
appearance on the state of the memory as the application is running.
clicking the legend button displays the
collected measurements, symbols, and colors
used to display the data.
the memory size scale y-axis automatically
adjusts to the range of data collected in the
current visible chart range.
the quantities plotted on the y-axis are as follows:
<topic_end>
<topic_start>
profile memory tab
use the profile memory tab to see current memory
allocation by class and memory type. for a
deeper analysis in google sheets or other tools,
download the data in CSV format.
toggle refresh on GC, to see allocation in real time.
<topic_end>
<topic_start>
diff snapshots tab
use the diff snapshots tab to investigate a feature’s
memory management. follow the guidance on the tab
to take snapshots before and after interaction
with the application, and diff the snapshots:
tap the filter classes and packages button,
to narrow the data:
for a deeper analysis in google sheets
or other tools, download the data in CSV format.
<topic_end>
<topic_start>
trace instances tab
use the trace instances tab to investigate what methods
allocate memory for a set of classes during feature execution:
<topic_end>
<topic_start>
bottom up vs call tree view
switch between bottom-up and call tree views
depending on specifics of your tasks.
the call tree view shows the method allocations
for each instance. the view is a top-down representation
of the call stack, meaning that a method can be expanded
to show its callees.
the bottom-up view shows the list of different
call stacks that have allocated the instances.
<topic_end>
<topic_start>
other resources
for more information, check out the following resources:
<topic_end>
<topic_start>
using the debug console
the DevTools debug console allows you to watch an
application’s standard output (stdout),
evaluate expressions for a paused or running
app in debug mode, and analyze inbound and outbound
references for objects.
info note
  this page is up to date for DevTools 2.23.0.
the debug console is available from the inspector,
debugger, and memory views.
<topic_end>
<topic_start>
watch application output
the console shows the application’s standard output (stdout):
<topic_end>
<topic_start>
explore inspected widgets
if you click a widget on the inspector screen,
the variable for this widget displays in the console:
<topic_end>
<topic_start>
evaluate expressions
in the console, you can evaluate expressions for a paused
or running application, assuming that you are running
your app in debug mode:
to assign an evaluated object to a variable,
use $0, $1 (through $5) in the form of var x = $0:
<topic_end>
<topic_start>
browse heap snapshot
to drop a variable to the console from a heap snapshot,
do the following:
the console screen displays both live and static
inbound and outbound references, as well as field values:
<topic_end>
<topic_start>
using the network view
info note
  the network view works with all flutter and dart applications.
<topic_end>
<topic_start>
what is it?
the network view allows you to inspect HTTP, HTTPS, and web socket traffic from
your dart or flutter application.
<topic_end>
<topic_start>
how to use it
network traffic should be recording by default when you open the network page.
if it is not, click the resume button in the upper left to
begin polling.
select a network request from the table (left) to view details (right). you can
inspect general and timing information about the request, as well as the content
of response and request headers and bodies.
<topic_end>
<topic_start>
search and filtering
you can use the search and filter controls to find a specific request or filter
requests out of the request table.
to apply a filter, press the filter button (right of the search bar). you will
see a filter dialog pop up:
the filter query syntax is described in the dialog. you can filter network
requests by the following keys:
any text that is not paired with an available filter key will be queried against
all categories (method, uri, status, type).
example filter queries:
<topic_end>
<topic_start>
other resources
HTTP and HTTPs requests are also surfaced in the timeline as
asynchronous timeline events. viewing network activity in the timeline can be
useful if you want to see how HTTP traffic aligns with other events happening
in your app or in the flutter framework.
to learn how to monitor an app’s network traffic and inspect
different types of requests using the DevTools,
check out a guided network view tutorial.
the tutorial also uses the view to identify network activity that
causes poor app performance.
<topic_end>
<topic_start>
using the debugger
info note
  DevTools hides the debugger tab if the app was launched
  from VS code because VS code has a built-in debugger.
<topic_end>
<topic_start>
getting started
DevTools includes a full source-level debugger, supporting
breakpoints, stepping, and variable inspection.
info note
  the debugger works with all flutter and dart applications.
  if you are looking for a way to use GDB to remotely debug the
  flutter engine running within an android app process,
  check out flutter_gdb.
when you open the debugger tab, you should see the source for the main
entry-point for your app loaded in the debugger.
in order to browse around more of your application sources, click libraries
(top right) or press ctrl / cmd + p.
this opens the libraries window and allows you
to search for other source files.
<topic_end>
<topic_start>
setting breakpoints
to set a breakpoint, click the left margin (the line number ruler)
in the source area. clicking once sets a breakpoint, which should
also show up in the breakpoints area on the left. clicking
again removes the breakpoint.
<topic_end>
<topic_start>
the call stack and variable areas
when your application encounters a breakpoint, it pauses there,
and the DevTools debugger shows the paused execution location
in the source area. in addition, the call stack and variables
areas populate with the current call stack for the paused isolate,
and the local variables for the selected frame. selecting other
frames in the call stack area changes the contents of the variables.
within the variables area, you can inspect individual objects by
toggling them open to see their fields. hovering over an object
in the variables area calls toString() for that object and
displays the result.
<topic_end>
<topic_start>
stepping through source code
when paused, the three stepping buttons become active.
in addition, the resume button continues regular
execution of the application.
<topic_end>
<topic_start>
console output
console output for the running app (stdout and stderr) is
displayed in the console, below the source code area.
you can also see the output in the logging view.
<topic_end>
<topic_start>
breaking on exceptions
to adjust the stop-on-exceptions behavior, toggle the
ignore dropdown at the top of the debugger view.
breaking on unhandled excepts only pauses execution if the
breakpoint is considered uncaught by the application code.
breaking on all exceptions causes the debugger to pause
whether or not the breakpoint was caught by application code.
<topic_end>
<topic_start>
known issues
when performing a hot restart for a flutter application,
user breakpoints are cleared.
<topic_end>
<topic_start>
other resources
for more information on debugging and profiling, see the
debugging page.
<topic_end>
<topic_start>
using the logging view
info note
  the logging view works with all flutter and dart applications.
<topic_end>
<topic_start>
what is it?
the logging view displays events from the dart runtime,
application frameworks (like flutter), and application-level
logging events.
<topic_end>
<topic_start>
standard logging events
by default, the logging view shows:
<topic_end>
<topic_start>
logging from your application
to implement logging in your code,
see the logging section in the
debugging flutter apps programmatically
page.
<topic_end>
<topic_start>
clearing logs
to clear the log entries in the logging view,
click the clear logs button.
<topic_end>
<topic_start>
other resources
to learn about different methods of logging
and how to effectively use DevTools to
analyze and debug flutter apps faster,
check out a guided logging view tutorial.
<topic_end>
<topic_start>
using the app size tool
<topic_end>
<topic_start>
what is it?
the app size tool allows you to analyze the total size of your app.
you can view a single snapshot of “size information”
using the analysis tab, or compare two different
snapshots of “size information” using the diff tab.
<topic_end>
<topic_start>
what is “size information”?
“size information” contains size data for dart code,
native code, and non-code elements of your app,
like the application package, assets and fonts. a “size
information” file contains data for the total picture
of your application size.
<topic_end>
<topic_start>
dart size information
the dart AOT compiler performs tree-shaking on your code
when compiling your application (profile or release mode
only—the AOT compiler is not used for debug builds,
which are JIT compiled). this means that the compiler
attempts to optimize your app’s size by removing
pieces of code that are unused or unreachable.
after the compiler optimizes your code as much as it can,
the end result can be summarized as the collection of packages,
libraries, classes, and functions that exist in the binary output,
along with their size in bytes. this is the dart portion of
“size information” we can analyze in the app size tool to further
optimize dart code and track down size issues.
<topic_end>
<topic_start>
how to use it
if DevTools is already connected to a running application,
navigate to the “app size” tab.
if DevTools is not connected to a running application, you can
access the tool from the landing page that appears once you have launched
DevTools (see installation instructions).
<topic_end>
<topic_start>
analysis tab
the analysis tab allows you to inspect a single snapshot
of size information.  you can view the hierarchical structure
of the size data using the treemap and table,
and you can view code attribution data
(for example, why a piece of code is included in your compiled
application) using the dominator tree and call graph.
<topic_end>
<topic_start>
loading a size file
when you open the analysis tab, you’ll see instructions
to load an app size file. drag and drop an app size
file into the dialog, and click “analyze size”.
see generating size files below for information on
generating size files.
<topic_end>
<topic_start>
treemap and table
the treemap and table show the hierarchical data for your app’s size.
<topic_end>
<topic_start>
using the treemap
a treemap is a visualization for hierarchical data.
the space is broken up into rectangles,
where each rectangle is sized and ordered by some quantitative
variable (in this case, size in bytes).
the area of each rectangle is proportional to the size
the node occupies in the compiled application. inside
of each rectangle (call one a), there are additional
rectangles that exist one level deeper in the data
hierarchy (children of a).
to drill into a cell in the treemap, select the cell.
this re-roots the tree so that the selected cell becomes
the visual root of the treemap.
to navigate back, or up a level, use the breadcrumb
navigator at the top of the treemap.
<topic_end>
<topic_start>
dominator tree and call graph
this section of the page shows code size attribution data
(for example, why a piece of code is included in your
compiled application). this data is visible
in the form of a dominator tree as well as a call graph.
<topic_end>
<topic_start>
using the dominator tree
a dominator tree is a tree where each node’s
children are those nodes it immediately dominates.
a node a is said to “dominate” a node b if
every path to b must go through a.
to put it in context of app size analysis,
imagine package:a imports both package:b and package:c,
and both package:b and package:c import package:d.
in this example, package:a dominates package:d,
so the dominator tree for this data would look like:
this information is helpful for understanding why certain
pieces of code are present in your compiled application.
for example, if you are analyzing your app size and find
an unexpected package included in your compiled app, you can
use the dominator tree to trace the package to its root source.
<topic_end>
<topic_start>
using the call graph
a call graph provides similar information to the dominator
tree in regards to helping you understand why code exists
in a compiled application. however, instead of showing
the one-to-many dominant relationships between nodes of code
size data like the dominator tree, the call graph shows the many-to-many
relationships that existing between nodes of code size data.
again, using the following example:
the call graph for this data would link package:d
to its direct callers, package:b and package:c,
instead of its “dominator”, package:a.
this information is useful for understanding the
fine-grained dependencies of between pieces of your code
(packages, libraries, classes, functions).
<topic_end>
<topic_start>
should i use the dominator tree or the call graph?
use the dominator tree if you want to understand the
root cause for why a piece of code is included in your
application. use the call graph if you want to understand
all the call paths to and from a piece of code.
a dominator tree is an analysis or slice of call graph data,
where nodes are connected by “dominance” instead of
parent-child hierarchy. in the case where a parent node
dominates a child, the relationship in the call graph and the
dominator tree would be identical, but this is not always the case.
in the scenario where the call graph is complete
(an edge exists between every pair of nodes),
the dominator tree would show the that root is the
dominator for every node in the graph.
this is an example where the call graph would give
you a better understanding around why a piece of code is
included in your application.
<topic_end>
<topic_start>
diff tab
the diff tab allows you to compare two snapshots of
size information. the two size information files
you are comparing should be generated from two different
versions of the same app; for example,
the size file generated before and after
changes to your code. you can visualize the
difference between the two data sets
using the treemap and table.
<topic_end>
<topic_start>
loading size files
when you open the diff tab,
you’ll see instructions to load “old” and “new” size
files. again, these files need to be generated from
the same application. drag and drop these files into
their respective dialogs, and click analyze diff.
see generating size files below for information
on generating these files.
<topic_end>
<topic_start>
treemap and table
in the diff view, the treemap and tree table show
only data that differs between the two imported size files.
for questions about using the treemap, see using the treemap above.
<topic_end>
<topic_start>
generating size files
to use the app size tool, you’ll need to generate a
flutter size analysis file. this file contains size
information for your entire application (native code,
dart code, assets, fonts, etc.), and you can generate it using the
--analyze-size flag:
this builds your application, prints a size summary
to the command line, and prints a line
telling you where to find the size analysis file.
in this example, import the build/apk-code-size-analysis_01.json
file into the app size tool to analyze further.
for more information, see app size documentation.
<topic_end>
<topic_start>
other resources
to learn how to perform a step-by-step size analysis of
the wonderous app using DevTools, check out the
app size tool tutorial. various strategies
to reduce an app’s size are also discussed.
<topic_end>
<topic_start>
DevTools extensions
<topic_end>
<topic_start>
what are DevTools extensions?
DevTools extensions are developer
tools provided by third-party packages that are tightly integrated into the
DevTools tooling suite. extensions are distributed as part of a pub package,
and they are dynamically loaded into DevTools when a user is debugging their app.
<topic_end>
<topic_start>
use a DevTools extension
if your app depends on a package that provides a DevTools extension, the
extension automatically shows up in a new tab when you open DevTools.
<topic_end>
<topic_start>
configure extension enablement states
you need to manually enable the extension before it loads for the first time.
make sure the extension is provided by a source you trust before enabling it.
extension enablement states are stored in a devtools_options.yaml file in the
root of the user’s project (similar to analysis_options.yaml). this file
stores per-project (or optionally, per user) settings for DevTools.
if this file is checked into source control, the specified options are
configured for the project. this means that anyone who pulls a project’s
source code and works on the project uses the same settings.
if this file is omitted from source control, for example by adding
devtools_options.yaml as an entry in the .gitignore file, then the specified
options are configured separately for each user. since each user or
contributor to the project uses a local copy of the devtools_options.yaml
file in this case, the specified options might differ between project contributors.
<topic_end>
<topic_start>
build a DevTools extension
for an in-depth guide on how to build a DevTools extension, check out 
dart and flutter DevTools extensions, a free article on medium.
<topic_end>
<topic_start>
DevTools release notes
this page summarizes the changes in official stable releases of DevTools.
to view a complete list of changes, check out the
DevTools git log.
the dart and flutter SDKs include DevTools.
to check your current version of DevTools,
run the following on your command line:
<topic_end>
<topic_start>
release notes
<topic_end>
<topic_start>
flutter SDK overview
the flutter SDK has the packages and command-line tools that you need to develop
flutter apps across platforms. to get the flutter SDK, see install.
<topic_end>
<topic_start>
what’s in the flutter SDK
the following is available through the flutter SDK:
note: for more information about the flutter SDK, see its
README file.
<topic_end>
<topic_start>
flutter command-line tool
the flutter CLI tool (flutter/bin/flutter) is how developers
(or IDEs on behalf of developers) interact with flutter.
<topic_end>
<topic_start>
dart command-line tool
the dart CLI tool is available with the flutter SDK at flutter/bin/dart.
<topic_end>
<topic_start>
flutter and the pubspec file
info note
  this page is primarily aimed at folks who write
  flutter apps. if you write packages or plugins, 
  (perhaps you want to create a federated plugin),
  you should check out the
  developing packages and plugins page.
every flutter project includes a pubspec.yaml file,
often referred to as the pubspec.
a basic pubspec is generated when you create
a new flutter project. it’s located at the top
of the project tree and contains metadata about
the project that the dart and flutter tooling
needs to know. the pubspec is written in
YAML, which is human readable, but be aware
that white space (tabs v spaces) matters.
the pubspec file specifies dependencies
that the project requires, such as particular packages
(and their versions), fonts, or image files.
it also specifies other requirements, such as 
dependencies on developer packages (like
testing or mocking packages), or particular
constraints on the version of the flutter SDK.
fields common to both dart and flutter projects
are described in the pubspec file on dart.dev.
this page lists flutter-specific fields
that are only valid for a flutter project.
info note
  the first time you build your project, it
  creates a pubspec.lock file that contains
  specific versions of the included packages.
  this ensures that you get the same version
  the next time the project is built.
when you create a new project with the
flutter create command (or by using the
equivalent button in your IDE), it creates
a pubspec for a basic flutter app.
here is an example of a flutter project pubspec file.
the flutter only fields are highlighted.
<topic_end>
<topic_start>
assets
common types of assets include static data
(for example, JSON files), configuration files,
icons, and images (jpeg, WebP, GIF,
animated WebP/GIF, PNG, BMP, and WBMP).
besides listing the images that are included in the
app package, an image asset can also refer to one or more
resolution-specific “variants”. for more information,
see the resolution aware section of the
assets and images page.
for information on adding assets from package
dependencies, see the
asset images in package dependencies
section in the same page.
<topic_end>
<topic_start>
fonts
as shown in the above example,
each entry in the fonts section should have a
family key with the font family name,
and a fonts key with a list specifying the
asset and other descriptors for the font.
for examples of using fonts
see the use a custom font and
export fonts from a package recipes in the
flutter cookbook.
<topic_end>
<topic_start>
more information
for more information on packages, plugins,
and pubspec files, see the following:
<topic_end>
<topic_start>
flutter fix
as flutter continues to evolve, we provide a tool to help you clean up
deprecated APIs from your codebase. the tool ships as part of flutter, and
suggests changes that you might want to make to your code. the tool is available
from the command line, and is also integrated into the IDE plugins for android
studio and visual studio code.
lightbulb tip
  these automated updates are called quick-fixes in IntelliJ and android
  studio, and code actions in VS code.
<topic_end>
<topic_start>
applying individual fixes
you can use any supported IDE
to apply a single fix at a time.
<topic_end>
<topic_start>
IntelliJ and android studio
when the analyzer detects a deprecated API,
a light bulb appears on that line of code.
clicking the light bulb displays the suggested fix
that updates that code to the new API.
clicking the suggested fix performs the update.
a sample quick-fix in IntelliJ
<topic_end>
<topic_start>
VS code
when the analyzer detects a deprecated API,
it presents an error.
you can do any of the following:
hover over the error and then click the
quick fix link.
this presents a filtered list showing
only fixes.
put the caret in the code with the error and click
the light bulb icon that appears.
this shows a list of all actions, including
refactors.
put the caret in the code with the error and
press the shortcut
(command+. on macOS, control+. elsewhere)
this shows a list of all actions, including
refactors.
a sample code action in VS code
<topic_end>
<topic_start>
applying project-wide fixes
dart fix decoding flutter
to see or apply changes to an entire project,
you can use the command-line tool, dart fix.
this tool has two options:
to see a full list of available changes, run
the following command:
to apply all changes in bulk, run the
following command:
for more information on flutter deprecations, see
deprecation lifetime in flutter, a free article
on flutter’s medium publication.
<topic_end>
<topic_start>
code formatting
while your code might follow any preferred style—in our
experience—teams of developers might find it more productive to:
the alternative is often tiring formatting debates during code reviews,
where time might be better spent on code behavior rather than code style.
<topic_end>
<topic_start>
automatically formatting code in VS code
install the flutter extension (see
editor setup)
to get automatic formatting of code in VS code.
to automatically format the code in the current source code window,
right-click in the code window and select format document.
you can add a keyboard shortcut to this VS code preferences.
to automatically format code whenever you save a file, set the
editor.formatOnSave setting to true.
<topic_end>
<topic_start>
automatically formatting code in android studio and IntelliJ
install the dart plugin (see
editor setup)
to get automatic formatting of code in android studio and IntelliJ.
to format your code in the current source code window:
android studio and IntelliJ also provide a checkbox named
format code on save on the flutter page in preferences
on macOS or settings on windows and linux.
this option corrects formatting in the current file when you save it.
<topic_end>
<topic_start>
automatically formatting code with the dart command
to correct code formatting in the command line interface (cli),
run the dart format command:
<topic_end>
<topic_start>
using trailing commas
flutter code often involves building fairly deep tree-shaped data structures,
for example in a build method. to get good automatic formatting,
we recommend you adopt the optional trailing commas.
the guideline for adding a trailing comma is simple: always
add a trailing comma at the end of a parameter list in
functions, methods, and constructors where you care about
keeping the formatting you crafted.
this helps the automatic formatter to insert an appropriate
amount of line breaks for flutter-style code.
here is an example of automatically formatted code with trailing commas:
and the same code automatically formatted code without trailing commas:
<topic_end>
<topic_start>
flutter architectural overview
this article is intended to provide a high-level overview of the architecture of
flutter, including the core principles and concepts that form its design.
flutter is a cross-platform UI toolkit that is designed to allow code reuse
across operating systems such as iOS and android, while also allowing
applications to interface directly with underlying platform services. the goal
is to enable developers to deliver high-performance apps that feel natural on
different platforms, embracing differences where they exist while sharing as
much code as possible.
during development, flutter apps run in a VM that offers stateful hot reload of
changes without needing a full recompile. for release, flutter apps are compiled
directly to machine code, whether intel x64 or ARM instructions, or to
JavaScript if targeting the web. the framework is open source, with a permissive
BSD license, and has a thriving ecosystem of third-party packages that
supplement the core library functionality.
this overview is divided into a number of sections:
<topic_end>
<topic_start>
architectural layers
flutter is designed as an extensible, layered system. it exists as a series of
independent libraries that each depend on the underlying layer. no layer has
privileged access to the layer below, and every part of the framework level is
designed to be optional and replaceable.
to the underlying operating system, flutter applications are packaged in the
same way as any other native application. a platform-specific embedder provides
an entrypoint; coordinates with the underlying operating system for access to
services like rendering surfaces, accessibility, and input; and manages the
message event loop. the embedder is written in a language that is appropriate
for the platform: currently java and c++ for android, Objective-C/Objective-C++
for iOS and macOS, and c++ for windows and linux. using the embedder, flutter
code can be integrated into an existing application as a module, or the code may
be the entire content of the application. flutter includes a number of embedders
for common target platforms, but other embedders also
exist.
at the core of flutter is the flutter engine,
which is mostly written in c++ and supports
the primitives necessary to support all flutter applications.
the engine is responsible for rasterizing composited scenes
whenever a new frame needs to be painted.
it provides the low-level implementation of flutter’s core API,
including graphics (through impeller on iOS and coming to android,
and skia on other platforms) text layout,
file and network I/O, accessibility support,
plugin architecture, and a dart runtime
and compile toolchain.
the engine is exposed to the flutter framework through
dart:ui,
which wraps the underlying c++ code in dart classes. this library
exposes the lowest-level primitives, such as classes for driving input,
graphics, and text rendering subsystems.
typically, developers interact with flutter through the flutter framework,
which provides a modern, reactive framework written in the dart language. it
includes a rich set of platform, layout, and foundational libraries, composed of
a series of layers. working from the bottom to the top, we have:
the flutter framework is relatively small; many higher-level features that
developers might use are implemented as packages, including platform plugins
like camera and
webview, as well as platform-agnostic
features like characters,
http, and
animations that build upon the core dart and
flutter libraries. some of these packages come from the broader ecosystem,
covering services like in-app
payments, apple
authentication, and
animations.
the rest of this overview broadly navigates down the layers, starting with the
reactive paradigm of UI development. then, we describe how widgets are composed
together and converted into objects that can be rendered as part of an
application. we describe how flutter interoperates with other code at a platform
level, before giving a brief summary of how flutter’s web support differs from
other targets.
<topic_end>
<topic_start>
anatomy of an app
the following diagram gives an overview of the pieces
that make up a regular flutter app generated by flutter create.
it shows where the flutter engine sits in this stack,
highlights API boundaries, and identifies the repositories
where the individual pieces live. the legend below clarifies
some of the terminology commonly used to describe the
pieces of a flutter app.
dart app
framework (source code)
engine (source code)
embedder (source code)
runner
<topic_end>
<topic_start>
reactive user interfaces
on the surface, flutter is a reactive, declarative UI framework,
in which the developer provides a mapping from application state to interface
state, and the framework takes on the task of updating the interface at runtime
when the application state changes. this model is inspired by
work that came from facebook for their own react framework,
which includes a rethinking of many traditional design principles.
in most traditional UI frameworks, the user interface’s initial state is
described once and then separately updated by user code at runtime, in response
to events. one challenge of this approach is that, as the application grows in
complexity, the developer needs to be aware of how state changes cascade
throughout the entire UI. for example, consider the following UI:
there are many places where the state can be changed: the color box, the hue
slider, the radio buttons. as the user interacts with the UI, changes must be
reflected in every other place. worse, unless care is taken, a minor change to
one part of the user interface can cause ripple effects to seemingly unrelated
pieces of code.
one solution to this is an approach like MVC, where you push data changes to the
model via the controller, and then the model pushes the new state to the view
via the controller. however, this also is problematic, since creating and
updating UI elements are two separate steps that can easily get out of sync.
flutter, along with other reactive frameworks, takes an alternative approach to
this problem, by explicitly decoupling the user interface from its underlying
state. with react-style APIs, you only create the UI description, and the
framework takes care of using that one configuration to both create and/or
update the user interface as appropriate.
in flutter, widgets (akin to components in react) are represented by immutable
classes that are used to configure a tree of objects. these widgets are used to
manage a separate tree of objects for layout, which is then used to manage a
separate tree of objects for compositing. flutter is, at its core, a series of
mechanisms for efficiently walking the modified parts of trees, converting trees
of objects into lower-level trees of objects, and propagating changes across
these trees.
a widget declares its user interface by overriding the build() method, which
is a function that converts state to UI:
the build() method is by design fast to execute and should be free of side
effects, allowing it to be called by the framework whenever needed (potentially
as often as once per rendered frame).
this approach relies on certain characteristics of a language runtime (in
particular, fast object instantiation and deletion). fortunately, dart is
particularly well suited for this
task.
<topic_end>
<topic_start>
widgets
as mentioned, flutter emphasizes widgets as a unit of composition. widgets are
the building blocks of a flutter app’s user interface, and each widget is an
immutable declaration of part of the user interface.
widgets form a hierarchy based on composition. each widget nests inside its
parent and can receive context from the parent. this structure carries all the
way up to the root widget (the container that hosts the flutter app, typically
MaterialApp or CupertinoApp), as this trivial example shows:
<code_start>
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      home: scaffold(
        appBar: AppBar(
          title: const Text('My home page'),
        ),
        body: center(
          child: builder(
            builder: (context) {
              return column(
                children: [
                  const Text('Hello world'),
                  const SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      print('Click!');
                    },
                    child: const Text('A button'),
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }
}
<code_end>
in the preceding code, all instantiated classes are widgets.
apps update their user interface in response to events (such as a user
interaction) by telling the framework to replace a widget in the hierarchy with
another widget. the framework then compares the new and old widgets, and
efficiently updates the user interface.
flutter has its own implementations of each UI control, rather than deferring to
those provided by the system: for example, there is a pure dart
implementation of both the
iOS toggle
control
and the one for the
android equivalent.
this approach provides several benefits:
<topic_end>
<topic_start>
composition
widgets are typically composed of many other small, single-purpose widgets that
combine to produce powerful effects.
where possible, the number of design concepts is kept to a minimum while
allowing the total vocabulary to be large. for example, in the widgets layer,
flutter uses the same core concept (a widget) to represent drawing to the
screen, layout (positioning and sizing), user interactivity, state management,
theming, animations, and navigation. in the animation layer, a pair of concepts,
animations and tweens, cover most of the design space. in the rendering
layer, RenderObjects are used to describe layout, painting, hit testing, and
accessibility. in each of these cases, the corresponding vocabulary ends up
being large: there are hundreds of widgets and render objects, and dozens of
animation and tween types.
the class hierarchy is deliberately shallow and broad to maximize the possible
number of combinations, focusing on small, composable widgets that each do one
thing well. core features are abstract, with even basic features like padding
and alignment being implemented as separate components rather than being built
into the core. (this also contrasts with more traditional APIs where features
like padding are built in to the common core of every layout component.) so, for
example, to center a widget, rather than adjusting a notional align property,
you wrap it in a center
widget.
there are widgets for padding, alignment, rows, columns, and grids. these layout
widgets do not have a visual representation of their own. instead, their sole
purpose is to control some aspect of another widget’s layout. flutter also
includes utility widgets that take advantage of this compositional approach.
for example, container, a
commonly used widget, is made up of several widgets responsible for layout,
painting, positioning, and sizing. specifically, container is made up of the
LimitedBox,
ConstrainedBox,
align,
padding,
DecoratedBox, and
transform widgets, as you
can see by reading its source code. a defining characteristic of flutter is that
you can drill down into the source for any widget and examine it. so, rather
than subclassing container to produce a customized effect, you can compose it
and other widgets in novel ways, or just create a new widget using
container as inspiration.
<topic_end>
<topic_start>
building widgets
as mentioned earlier, you determine the visual representation of a widget by
overriding the
build() function to
return a new element tree. this tree represents the widget’s part of the user
interface in more concrete terms. for example, a toolbar widget might have a
build function that returns a horizontal
layout of some
text and
various
buttons. as needed,
the framework recursively asks each widget to build until the tree is entirely
described by concrete renderable
objects. the
framework then stitches together the renderable objects into a renderable object
tree.
a widget’s build function should be free of side effects. whenever the function
is asked to build, the widget should return a new tree of widgets1, regardless of what the widget previously returned. the
framework does the heavy lifting work to determine which build methods need to
be called based on the render object tree (described in more detail later). more
information about this process can be found in the inside flutter
topic.
on each rendered frame, flutter can recreate just the parts of the UI where the
state has changed by calling that widget’s build() method. therefore it is
important that build methods should return quickly, and heavy computational work
should be done in some asynchronous manner and then stored as part of the state
to be used by a build method.
while relatively naïve in approach, this automated comparison is quite
effective, enabling high-performance, interactive apps. and, the design of the
build function simplifies your code by focusing on declaring what a widget is
made of, rather than the complexities of updating the user interface from one
state to another.
<topic_end>
<topic_start>
widget state
the framework introduces two major classes of widget: stateful and stateless
widgets.
many widgets have no mutable state: they don’t have any properties that change
over time (for example, an icon or a label). these widgets subclass
StatelessWidget.
however, if the unique characteristics of a widget need to change based on user
interaction or other factors, that widget is stateful. for example, if a
widget has a counter that increments whenever the user taps a button, then the
value of the counter is the state for that widget. when that value changes, the
widget needs to be rebuilt to update its part of the UI. these widgets subclass
StatefulWidget, and
(because the widget itself is immutable) they store mutable state in a separate
class that subclasses state.
StatefulWidgets don’t have a build method; instead, their user interface is
built through their state object.
whenever you mutate a state object (for example, by incrementing the counter),
you must call setState()
to signal the framework to update the user interface by calling the state’s
build method again.
having separate state and widget objects lets other widgets treat both stateless
and stateful widgets in exactly the same way, without being concerned about
losing state. instead of needing to hold on to a child to preserve its state,
the parent can create a new instance of the child at any time without losing the
child’s persistent state. the framework does all the work of finding and reusing
existing state objects when appropriate.
<topic_end>
<topic_start>
state management
so, if many widgets can contain state, how is state managed and passed around
the system?
as with any other class, you can use a constructor in a widget to initialize its
data, so a build() method can ensure that any child widget is instantiated
with the data it needs:
as widget trees get deeper, however, passing state information up and down the
tree hierarchy becomes cumbersome. so, a third widget type,
InheritedWidget,
provides an easy way to grab data from a shared ancestor. you can use
InheritedWidget to create a state widget that wraps a common ancestor in the
widget tree, as shown in this example:
whenever one of the ExamWidget or GradeWidget objects needs data from
StudentState, it can now access it with a command such as:
the of(context) call takes the build context (a handle to the current widget
location), and returns the nearest ancestor in the
tree
that matches the StudentState type. InheritedWidgets also offer an
updateShouldNotify() method, which flutter calls to determine whether a state
change should trigger a rebuild of child widgets that use it.
flutter itself uses InheritedWidget extensively as part of the framework for
shared state, such as the application’s visual theme, which includes
properties like color and type
styles that are
pervasive throughout an application. the MaterialApp build() method inserts
a theme in the tree when it builds, and then deeper in the hierarchy a widget
can use the .of() method to look up the relevant theme data, for example:
<code_start>
container(
  color: Theme.of(context).secondaryHeaderColor,
  child: text(
    'text with a background color',
    style: Theme.of(context).textTheme.titleLarge,
  ),
);
<code_end>
this approach is also used for
navigator, which provides
page routing; and
MediaQuery, which provides
access to screen metrics such as orientation, dimensions, and brightness.
as applications grow, more advanced state management approaches that reduce the
ceremony of creating and using stateful widgets become more attractive. many
flutter apps use utility packages like
provider, which provides a wrapper around
InheritedWidget. flutter’s layered architecture also enables alternative
approaches to implement the transformation of state into UI, such as the
flutter_hooks package.
<topic_end>
<topic_start>
rendering and layout
this section describes the rendering pipeline, which is the series of steps that
flutter takes to convert a hierarchy of widgets into the actual pixels painted
onto a screen.
<topic_end>
<topic_start>
flutter’s rendering model
you may be wondering: if flutter is a cross-platform framework, then how can it
offer comparable performance to single-platform frameworks?
it’s useful to start by thinking about how traditional
android apps work. when drawing,
you first call the java code of the android framework.
the android system libraries provide the components
responsible for drawing themselves to a canvas object,
which android can then render with skia,
a graphics engine written in C/C++ that calls the
CPU or GPU to complete the drawing on the device.
cross-platform frameworks typically work by creating
an abstraction layer over the underlying native
android and iOS UI libraries, attempting to smooth out the
inconsistencies of each platform representation.
app code is often written in an interpreted language like JavaScript,
which must in turn interact with the java-based
android or Objective-C-based iOS system libraries to display UI.
all this adds overhead that can be significant,
particularly where there is a lot of
interaction between the UI and the app logic.
by contrast, flutter minimizes those abstractions,
bypassing the system UI widget libraries in favor
of its own widget set. the dart code that paints
flutter’s visuals is compiled into native code,
which uses skia (or, in the future, impeller) for rendering.
flutter also embeds its own copy of skia as part of the engine,
allowing the developer to upgrade their app to stay
updated with the latest performance improvements
even if the phone hasn’t been updated with a new android version.
the same is true for flutter on other native platforms,
such as windows or macOS.
info note
  flutter 3.10 set impeller as the default
  rendering engine on iOS. it’s in preview
  for android behind a flag.
<topic_end>
<topic_start>
from user input to the GPU
the overriding principle that flutter applies to its rendering pipeline is that
simple is fast. flutter has a straightforward pipeline for how data flows to
the system, as shown in the following sequencing diagram:
let’s take a look at some of these phases in greater detail.
<topic_end>
<topic_start>
build: from widget to element
consider this code fragment that demonstrates a widget hierarchy:
<code_start>
container(
  color: colors.blue,
  child: row(
    children: [
      image.network('https://www.example.com/1.png'),
      const Text('A'),
    ],
  ),
);
<code_end>
when flutter needs to render this fragment, it calls the build() method, which
returns a subtree of widgets that renders UI based on the current app state.
during this process, the build() method can introduce new widgets, as
necessary, based on its state. as an example, in the preceding code
fragment, container has color and child properties. from looking at the
source
code
for container, you can see that if the color is not null, it inserts a
ColoredBox representing the color:
correspondingly, the image and text widgets might insert child widgets such
as RawImage and RichText during the build process. the eventual widget
hierarchy may therefore be deeper than what the code represents, as in this
case2:
this explains why, when you examine the tree through a debug tool such as the
flutter inspector, part of the
dart DevTools, you might see a structure that is considerably deeper than what
is in your original code.
during the build phase, flutter translates the widgets expressed in code into a
corresponding element tree, with one element for every widget. each element
represents a specific instance of a widget in a given location of the tree
hierarchy. there are two basic types of elements:
RenderObjectElements are an intermediary between their widget analog and the
underlying RenderObject, which we’ll come to later.
the element for any widget can be referenced through its BuildContext, which
is a handle to the location of a widget in the tree. this is the context in a
function call such as theme.of(context), and is supplied to the build()
method as a parameter.
because widgets are immutable, including the parent/child relationship between
nodes, any change to the widget tree (such as changing Text('A') to
Text('B') in the preceding example) causes a new set of widget objects to be
returned. but that doesn’t mean the underlying representation must be rebuilt.
the element tree is persistent from frame to frame, and therefore plays a
critical performance role, allowing flutter to act as if the widget hierarchy is
fully disposable while caching its underlying representation. by only walking
through the widgets that changed, flutter can rebuild just the parts of the
element tree that require reconfiguration.
<topic_end>
<topic_start>
layout and rendering
it would be a rare application that drew only a single widget. an important part
of any UI framework is therefore the ability to efficiently lay out a hierarchy
of widgets, determining the size and position of each element before they are
rendered on the screen.
the base class for every node in the render tree is
RenderObject, which
defines an abstract model for layout and painting. this is extremely general: it
does not commit to a fixed number of dimensions or even a cartesian coordinate
system (demonstrated by this example of a polar coordinate
system). each
RenderObject knows its parent, but knows little about its children other than
how to visit them and their constraints. this provides RenderObject with
sufficient abstraction to be able to handle a variety of use cases.
during the build phase, flutter creates or updates an object that inherits from
RenderObject for each RenderObjectElement in the element tree.
RenderObjects are primitives:
RenderParagraph
renders text,
RenderImage renders
an image, and
RenderTransform
applies a transformation before painting its child.
most flutter widgets are rendered by an object that inherits from the
RenderBox subclass, which represents a RenderObject of fixed size in a 2d
cartesian space. RenderBox provides the basis of a box constraint model,
establishing a minimum and maximum width and height for each widget to be
rendered.
to perform layout, flutter walks the render tree in a depth-first traversal and
passes down size constraints from parent to child. in determining its size,
the child must respect the constraints given to it by its parent. children
respond by passing up a size to their parent object within the constraints
the parent established.
at the end of this single walk through the tree, every object has a defined size
within its parent’s constraints and is ready to be painted by calling the
paint()
method.
the box constraint model is very powerful as a way to layout objects in o(n)
time:
this model works even when a child object needs to know how much space it has
available to decide how it will render its content. by using a
LayoutBuilder widget,
the child object can examine the passed-down constraints and use those to
determine how it will use them, for example:
<code_start>
widget build(BuildContext context) {
  return LayoutBuilder(
    builder: (context, constraints) {
      if (constraints.maxwidth < 600) {
        return const OneColumnLayout();
      } else {
        return const TwoColumnLayout();
      }
    },
  );
}
<code_end>
more information about the constraint and layout system,
along with working examples, can be found in the
understanding constraints topic.
the root of all RenderObjects is the RenderView, which represents the total
output of the render tree. when the platform demands a new frame to be rendered
(for example, because of a
vsync or because
a texture decompression/upload is complete), a call is made to the
compositeFrame() method, which is part of the RenderView object at the root
of the render tree. this creates a SceneBuilder to trigger an update of the
scene. when the scene is complete, the RenderView object passes the composited
scene to the window.render() method in dart:ui, which passes control to the
GPU to render it.
further details of the composition and rasterization stages of the pipeline are
beyond the scope of this high-level article, but more information can be found
in this talk on the flutter rendering
pipeline.
<topic_end>
<topic_start>
platform embedding
as we’ve seen, rather than being translated into the equivalent OS widgets,
flutter user interfaces are built, laid out, composited, and painted by flutter
itself. the mechanism for obtaining the texture and participating in the app
lifecycle of the underlying operating system inevitably varies depending on the
unique concerns of that platform. the engine is platform-agnostic, presenting a
stable ABI (application binary
interface)
that provides a platform embedder with a way to set up and use flutter.
the platform embedder is the native OS application that hosts all flutter
content, and acts as the glue between the host operating system and flutter.
when you start a flutter app, the embedder provides the entrypoint, initializes
the flutter engine, obtains threads for UI and rastering, and creates a texture
that flutter can write to. the embedder is also responsible for the app
lifecycle, including input gestures (such as mouse, keyboard, touch), window
sizing, thread management, and platform messages. flutter includes platform
embedders for android, iOS, windows, macOS, and linux; you can also create a
custom platform embedder, as in this worked
example that supports remoting
flutter sessions through a VNC-style framebuffer or this worked example for
raspberry pi.
each platform has its own set of APIs and constraints. some brief
platform-specific notes:
<topic_end>
<topic_start>
integrating with other code
flutter provides a variety of interoperability mechanisms, whether you’re
accessing code or APIs written in a language like kotlin or swift, calling a
native c-based API, embedding native controls in a flutter app, or embedding
flutter in an existing application.
<topic_end>
<topic_start>
platform channels
for mobile and desktop apps, flutter allows you to call into custom code through
a platform channel, which is a mechanism for communicating between your
dart code and the platform-specific code of your host app. by creating a common
channel (encapsulating a name and a codec), you can send and receive messages
between dart and a platform component written in a language like kotlin or
swift. data is serialized from a dart type like map into a standard format,
and then deserialized into an equivalent representation in kotlin (such as
HashMap) or swift (such as dictionary).
the following is a short platform channel example of a dart call to a receiving
event handler in kotlin (android) or swift (ios):
<code_start>
// dart side
const channel = MethodChannel('foo');
final greeting = await channel.invokeMethod('bar', 'world') as string;
print(greeting);
<code_end>
further examples of using platform channels, including examples for desktop
platforms, can be found in the flutter/packages
repository. there are also thousands of plugins
already available for flutter that cover many common
scenarios, ranging from firebase to ads to device hardware like camera and
bluetooth.
<topic_end>
<topic_start>
foreign function interface
for c-based APIs, including those that can be generated for code written in
modern languages like rust or go, dart provides a direct mechanism for binding
to native code using the dart:ffi library. the foreign function interface
(ffi) model can be considerably faster than platform channels, because no
serialization is required to pass data. instead, the dart runtime provides the
ability to allocate memory on the heap that is backed by a dart object and make
calls to statically or dynamically linked libraries. FFI is available for all
platforms other than web, where the js package
serves an equivalent purpose.
to use FFI, you create a typedef for each of the dart and unmanaged method
signatures, and instruct the dart VM to map between them. as an example,
here’s a fragment of code to call the traditional win32 MessageBox() API:
<code_start>
import 'dart:ffi';
import 'package:ffi/ffi.dart'; // contains .tonativeutf16() extension method
typedef MessageBoxNative = int32 function(
  IntPtr hWnd,
  Pointer<Utf16> lpText,
  Pointer<Utf16> lpCaption,
  int32 uType,
);
typedef MessageBoxDart = int function(
  int hWnd,
  Pointer<Utf16> lpText,
  Pointer<Utf16> lpCaption,
  int uType,
);
void exampleFfi() {
  final user32 = DynamicLibrary.open('user32.dll');
  final messageBox =
      user32.lookupFunction<MessageBoxNative, MessageBoxDart>('MessageBoxW');
  final result = messageBox(
    0, // no owner window
    'test message'.toNativeUtf16(), // message
    'window caption'.toNativeUtf16(), // window title
    0, // OK button only
  );
}
<code_end>
<topic_end>
<topic_start>
rendering native controls in a flutter app
because flutter content is drawn to a texture and its widget tree is entirely
internal, there’s no place for something like an android view to exist within
flutter’s internal model or render interleaved within flutter widgets. that’s a
problem for developers that would like to include existing platform components
in their flutter apps, such as a browser control.
flutter solves this by introducing platform view widgets
(androidview
and UiKitView)
that let you embed this kind of content on each platform. platform views can be
integrated with other flutter content3. each of
these widgets acts as an intermediary to the underlying operating system. for
example, on android, AndroidView serves three primary functions:
inevitably, there is a certain amount of overhead associated with this
synchronization. in general, therefore, this approach is best suited for complex
controls like google maps where reimplementing in flutter isn’t practical.
typically, a flutter app instantiates these widgets in a build() method based
on a platform test. as an example, from the
google_maps_flutter plugin:
communicating with the native code underlying the AndroidView or UiKitView
typically occurs using the platform channels mechanism, as previously described.
at present, platform views aren’t available for desktop platforms, but this is
not an architectural limitation; support might be added in the future.
<topic_end>
<topic_start>
hosting flutter content in a parent app
the converse of the preceding scenario is embedding a flutter widget in an
existing android or iOS app. as described in an earlier section, a newly created
flutter app running on a mobile device is hosted in an android activity or iOS
UIViewController. flutter content can be embedded into an existing android or
iOS app using the same embedding API.
the flutter module template is designed for easy embedding; you can either embed
it as a source dependency into an existing gradle or xcode build definition, or
you can compile it into an android archive or iOS framework binary for use
without requiring every developer to have flutter installed.
the flutter engine takes a short while to initialize, because it needs to load
flutter shared libraries, initialize the dart runtime, create and run a dart
isolate, and attach a rendering surface to the UI. to minimize any UI delays
when presenting flutter content, it’s best to initialize the flutter engine
during the overall app initialization sequence, or at least ahead of the first
flutter screen, so that users don’t experience a sudden pause while the first
flutter code is loaded. in addition, separating the flutter engine allows it to
be reused across multiple flutter screens and share the memory overhead involved
with loading the necessary libraries.
more information about how flutter is loaded into an existing android or iOS app
can be found at the load sequence, performance and memory
topic.
<topic_end>
<topic_start>
flutter web support
while the general architectural concepts apply to all platforms that flutter
supports, there are some unique characteristics of flutter’s web support that
are worthy of comment.
dart has been compiling to JavaScript for as long as the language has existed,
with a toolchain optimized for both development and production purposes. many
important apps compile from dart to JavaScript and run in production today,
including the advertiser tooling for google ads.
because the flutter framework is written in dart, compiling it to JavaScript was
relatively straightforward.
however, the flutter engine, written in c++,
is designed to interface with the
underlying operating system rather than a web browser.
a different approach is therefore required.
on the web, flutter provides a reimplementation of the
engine on top of standard browser APIs.
we currently have two options for
rendering flutter content on the web: HTML and WebGL.
in HTML mode, flutter uses HTML, CSS, canvas, and SVG.
to render to WebGL, flutter uses a version of skia
compiled to WebAssembly called
CanvasKit.
while HTML mode offers the best code size characteristics,
CanvasKit provides the fastest path to the
browser’s graphics stack,
and offers somewhat higher graphical fidelity with the
native mobile targets4.
the web version of the architectural layer diagram is as follows:
perhaps the most notable difference compared to other platforms on which flutter
runs is that there is no need for flutter to provide a dart runtime. instead,
the flutter framework (along with any code you write) is compiled to JavaScript.
it’s also worthy to note that dart has very few language semantic differences
across all its modes (jit versus AOT, native versus web compilation), and most
developers will never write a line of code that runs into such a difference.
during development time, flutter web uses
dartdevc, a compiler that supports
incremental compilation and therefore allows hot restart (although not currently
hot reload) for apps. conversely, when you are ready to create a production app
for the web, dart2js, dart’s
highly-optimized production JavaScript compiler is used, packaging the flutter
core and framework along with your application into a minified source file that
can be deployed to any web server. code can be offered in a single file or split
into multiple files through deferred imports.
<topic_end>
<topic_start>
further information
for those interested in more information about the internals of flutter, the
inside flutter whitepaper
provides a useful guide to the framework’s design philosophy.
footnotes:
1 while the build function returns a fresh tree,
you only need to return something different if there’s some new
configuration to incorporate. if the configuration is in fact the same, you can
just return the same widget.
2 this is a slight simplification for ease of
reading. in practice, the tree might be more complex.
3 there are some limitations with this approach, for
example, transparency doesn’t composite the same way for a platform view as it
would for other flutter widgets.
4 one example is shadows, which have to be
approximated with DOM-equivalent primitives at the cost of some fidelity.
<topic_end>
<topic_start>
inside flutter
this document describes the inner workings of the flutter toolkit that make
flutter’s API possible. because flutter widgets are built using aggressive
composition, user interfaces built with flutter have a large number of
widgets.  to support this workload, flutter uses sublinear algorithms for
layout and building widgets as well as data structures that make tree
surgery efficient and that have a number of constant-factor optimizations.
with some additional details, this design also makes it easy for developers
to create infinite scrolling lists using callbacks that build exactly those
widgets that are visible to the user.
<topic_end>
<topic_start>
aggressive composability
one of the most distinctive aspects of flutter is its aggressive
composability. widgets are built by composing other widgets,
which are themselves built out of progressively more basic widgets.
for example, padding is a widget rather than a property of other widgets.
as a result, user interfaces built with flutter consist of many,
many widgets.
the widget building recursion bottoms out in RenderObjectWidgets,
which are widgets that create nodes in the underlying render tree.
the render tree is a data structure that stores the geometry of the user
interface, which is computed during layout and used during painting and
hit testing. most flutter developers do not author render objects directly
but instead manipulate the render tree using widgets.
in order to support aggressive composability at the widget layer,
flutter uses a number of efficient algorithms and optimizations at
both the widget and render tree layers, which are described in the
following subsections.
<topic_end>
<topic_start>
sublinear layout
with a large number of widgets and render objects, the key to good
performance is efficient algorithms. of paramount importance is the
performance of layout, which is the algorithm that determines the
geometry (for example, the size and position) of the render objects.
some other toolkits use layout algorithms that are O(N²) or worse
(for example, fixed-point iteration in some constraint domain).
flutter aims for linear performance for initial layout, and sublinear
layout performance in the common case of subsequently updating an
existing layout. typically, the amount of time spent in layout should
scale more slowly than the number of render objects.
flutter performs one layout per frame, and the layout algorithm works
in a single pass. constraints are passed down the tree by parent
objects calling the layout method on each of their children.
the children recursively perform their own layout and then return
geometry up the tree by returning from their layout method. importantly,
once a render object has returned from its layout method, that render
object will not be visited again1
until the layout for the next frame. this approach combines what might
otherwise be separate measure and layout passes into a single pass and,
as a result, each render object is visited at most
twice2 during layout: once on the way
down the tree, and once on the way up the tree.
flutter has several specializations of this general protocol.
the most common specialization is RenderBox, which operates in
two-dimensional, cartesian coordinates. in box layout, the constraints
are a min and max width and a min and max height. during layout,
the child determines its geometry by choosing a size within these bounds.
after the child returns from layout, the parent decides the child’s
position in the parent’s coordinate system3.
note that the child’s layout cannot depend on its position,
as the position is not determined until after the child
returns from the layout. as a result, the parent is free to reposition
the child without needing to recompute its layout.
more generally, during layout, the only information that flows from
parent to child are the constraints and the only information that
flows from child to parent is the geometry. these invariants can reduce
the amount of work required during layout:
if the child has not marked its own layout as dirty, the child can
return immediately from layout, cutting off the walk, as long as the
parent gives the child the same constraints as the child received
during the previous layout.
whenever a parent calls a child’s layout method, the parent indicates
whether it uses the size information returned from the child. if,
as often happens, the parent does not use the size information,
then the parent need not recompute its layout if the child selects
a new size because the parent is guaranteed that the new size will
conform to the existing constraints.
tight constraints are those that can be satisfied by exactly one
valid geometry. for example, if the min and max widths are equal to
each other and the min and max heights are equal to each other,
the only size that satisfies those constraints is one with that
width and height. if the parent provides tight constraints,
then the parent need not recompute its layout whenever the child
recomputes its layout, even if the parent uses the child’s size
in its layout, because the child cannot change size without new
constraints from its parent.
a render object can declare that it uses the constraints provided
by the parent only to determine its geometry. such a declaration
informs the framework that the parent of that render object does
not need to recompute its layout when the child recomputes its layout
even if the constraints are not tight and even if the parent’s
layout depends on the child’s size, because the child cannot change
size without new constraints from its parent.
as a result of these optimizations, when the render object tree contains
dirty nodes, only those nodes and a limited part of the subtree around
them are visited during layout.
<topic_end>
<topic_start>
sublinear widget building
similar to the layout algorithm, flutter’s widget building algorithm
is sublinear. after being built, the widgets are held by the element
tree, which retains the logical structure of the user interface.
the element tree is necessary because the widgets themselves are
immutable, which means (among other things), they cannot remember their
parent or child relationships with other widgets. the element tree also
holds the state objects associated with stateful widgets.
in response to user input (or other stimuli), an element can become dirty,
for example if the developer calls setState() on the associated state
object. the framework keeps a list of dirty elements and jumps directly
to them during the build phase, skipping over clean elements. during
the build phase, information flows unidirectionally down the element
tree, which means each element is visited at most once during the build
phase.  once cleaned, an element cannot become dirty again because,
by induction, all its ancestor elements are also
clean4.
because widgets are immutable, if an element has not marked itself as
dirty, the element can return immediately from build, cutting off the walk,
if the parent rebuilds the element with an identical widget. moreover,
the element need only compare the object identity of the two widget
references in order to establish that the new widget is the same as
the old widget. developers exploit this optimization to implement the
reprojection pattern, in which a widget includes a prebuilt child
widget stored as a member variable in its build.
during build, flutter also avoids walking the parent chain using
InheritedWidgets. if widgets commonly walked their parent chain,
for example to determine the current theme color, the build phase
would become O(N²) in the depth of the tree, which can be quite
large due to aggressive composition. to avoid these parent walks,
the framework pushes information down the element tree by maintaining
a hash table of InheritedWidgets at each element. typically, many
elements will reference the same hash table, which changes only at
elements that introduce a new InheritedWidget.
<topic_end>
<topic_start>
linear reconciliation
contrary to popular belief, flutter does not employ a tree-diffing
algorithm. instead, the framework decides whether to reuse elements by
examining the child list for each element independently using an O(N)
algorithm. the child list reconciliation algorithm optimizes for the
following cases:
the general approach is to match up the beginning and end of both child
lists by comparing the runtime type and key of each widget,
potentially finding a non-empty range in the middle of each list
that contains all the unmatched children. the framework then places
the children in the range in the old child list into a hash table
based on their keys. next, the framework walks the range in the new
child list and queries the hash table by key for matches. unmatched
children are discarded and rebuilt from scratch whereas matched children
are rebuilt with their new widgets.
<topic_end>
<topic_start>
tree surgery
reusing elements is important for performance because elements own
two critical pieces of data: the state for stateful widgets and the
underlying render objects. when the framework is able to reuse an element,
the state for that logical part of the user interface is preserved
and the layout information computed previously can be reused,
often avoiding entire subtree walks. in fact, reusing elements is
so valuable that flutter supports non-local tree mutations that
preserve state and layout information.
developers can perform a non-local tree mutation by associating a GlobalKey
with one of their widgets. each global key is unique throughout the
entire application and is registered with a thread-specific hash table.
during the build phase, the developer can move a widget with a global
key to an arbitrary location in the element tree. rather than building
a fresh element at that location, the framework will check the hash
table and reparent the existing element from its previous location to
its new location, preserving the entire subtree.
the render objects in the reparented subtree are able to preserve
their layout information because the layout constraints are the only
information that flows from parent to child in the render tree.
the new parent is marked dirty for layout because its child list has
changed, but if the new parent passes the child the same layout
constraints the child received from its old parent, the child can
return immediately from layout, cutting off the walk.
global keys and non-local tree mutations are used extensively by
developers to achieve effects such as hero transitions and navigation.
<topic_end>
<topic_start>
constant-factor optimizations
in addition to these algorithmic optimizations, achieving aggressive
composability also relies on several important constant-factor
optimizations. these optimizations are most important at the leaves of
the major algorithms discussed above.
child-model agnostic. unlike most toolkits, which use child lists,
flutter’s render tree does not commit to a specific child model.
for example, the RenderBox class has an abstract visitChildren()
method rather than a concrete firstChild and nextSibling interface.
many subclasses support only a single child, held directly as a member
variable, rather than a list of children. for example, RenderPadding
supports only a single child and, as a result, has a simpler layout
method that takes less time to execute.
visual render tree, logical widget tree. in flutter, the render
tree operates in a device-independent, visual coordinate system,
which means smaller values in the x coordinate are always towards
the left, even if the current reading direction is right-to-left.
the widget tree typically operates in logical coordinates, meaning
with start and end values whose visual interpretation depends
on the reading direction. the transformation from logical to visual
coordinates is done in the handoff between the widget tree and the
render tree. this approach is more efficient because layout and
painting calculations in the render tree happen more often than the
widget-to-render tree handoff and can avoid repeated coordinate conversions.
text handled by a specialized render object. the vast majority
of render objects are ignorant of the complexities of text. instead,
text is handled by a specialized render object, RenderParagraph,
which is a leaf in the render tree. rather than subclassing a
text-aware render object, developers incorporate text into their
user interface using composition. this pattern means RenderParagraph
can avoid recomputing its text layout as long as its parent supplies
the same layout constraints, which is common, even during tree surgery.
observable objects. flutter uses both the model-observation and
the reactive paradigms. obviously, the reactive paradigm is dominant,
but flutter uses observable model objects for some leaf data structures.
for example, animations notify an observer list when their value changes.
flutter hands off these observable objects from the widget tree to the
render tree, which observes them directly and invalidates only the
appropriate stage of the pipeline when they change. for example,
a change to an Animation<Color> might trigger only the paint phase
rather than both the build and paint phases.
taken together and summed over the large trees created by aggressive
composition, these optimizations have a substantial effect on performance.
<topic_end>
<topic_start>
separation of the element and RenderObject trees
the RenderObject and element (widget) trees in flutter are isomorphic
(strictly speaking, the RenderObject tree is a subset of the element
tree). an obvious simplification would be to combine these trees into
one tree. however, in practice there are a number of benefits to having
these trees be separate:
performance. when the layout changes, only the relevant parts of
the layout tree need to be walked. due to composition, the element
tree frequently has many additional nodes that would have to be skipped.
clarity. the clearer separation of concerns allows the widget
protocol and the render object protocol to each be specialized to
their specific needs, simplifying the API surface and thus lowering
the risk of bugs and the testing burden.
type safety. the render object tree can be more type safe since it
can guarantee at runtime that children will be of the appropriate type
(each coordinate system, e.g. has its own type of render object).
composition widgets can be agnostic about the coordinate system used
during layout (for example, the same widget exposing a part of the app
model could be used in both a box layout and a sliver layout), and thus
in the element tree, verifying the type of render objects would require
a tree walk.
<topic_end>
<topic_start>
infinite scrolling
infinite scrolling lists are notoriously difficult for toolkits.
flutter supports infinite scrolling lists with a simple interface
based on the builder pattern, in which a ListView uses a callback
to build widgets on demand as they become visible to the user during
scrolling. supporting this feature requires viewport-aware layout
and building widgets on demand.
<topic_end>
<topic_start>
viewport-aware layout
like most things in flutter, scrollable widgets are built using
composition. the outside of a scrollable widget is a viewport,
which is a box that is “bigger on the inside,” meaning its children
can extend beyond the bounds of the viewport and can be scrolled into
view. however, rather than having RenderBox children, a viewport has
RenderSliver children, known as slivers, which have a viewport-aware
layout protocol.
the sliver layout protocol matches the structure of the box layout
protocol in that parents pass constraints down to their children and
receive geometry in return. however, the constraint and geometry data
differs between the two protocols. in the sliver protocol, children
are given information about the viewport, including the amount of
visible space remaining. the geometry data they return enables a
variety of scroll-linked effects, including collapsible headers and
parallax.
different slivers fill the space available in the viewport in different
ways. for example, a sliver that produces a linear list of children lays
out  each child in order until the sliver either runs out of children or
runs out of space. similarly, a sliver that produces a two-dimensional
grid of children fills only the portion of its grid that is visible.
because they are aware of how much space is visible, slivers can produce
a finite number of children even if they have the potential to produce
an unbounded number of children.
slivers can be composed to create bespoke scrollable layouts and effects.
for example, a single viewport can have a collapsible header followed
by a linear list and then a grid. all three slivers will cooperate through
the sliver layout protocol to produce only those children that are actually
visible through the viewport, regardless of whether those children belong
to the header, the list, or the grid6.
<topic_end>
<topic_start>
building widgets on demand
if flutter had a strict build-then-layout-then-paint pipeline,
the foregoing would be insufficient to implement an infinite scrolling
list because the information about how much space is visible through
the viewport is available only during the layout phase. without
additional machinery, the layout phase is too late to build the
widgets necessary to fill the space. flutter solves this problem
by interleaving the build and layout phases of the pipeline. at any
point in the layout phase, the framework can start building new
widgets on demand as long as those widgets are descendants of the
render object currently performing layout.
interleaving build and layout is possible only because of the strict
controls on information propagation in the build and layout algorithms.
specifically, during the build phase, information can propagate only
down the tree. when a render object is performing layout, the layout
walk has not visited the subtree below that render object, which means
writes generated by building in that subtree cannot invalidate any
information that has entered the layout calculation thus far. similarly,
once layout has returned from a render object, that render object will
never be visited again during this layout, which means any writes
generated by subsequent layout calculations cannot invalidate the
information used to build the render object’s subtree.
additionally, linear reconciliation and tree surgery are essential
for efficiently updating elements during scrolling and for modifying
the render tree when elements are scrolled into and out of view at
the edge of the viewport.
<topic_end>
<topic_start>
API ergonomics
being fast only matters if the framework can actually be used effectively.
to guide flutter’s API design towards greater usability, flutter has been
repeatedly tested in extensive UX studies with developers. these studies
sometimes confirmed pre-existing design decisions, sometimes helped guide
the prioritization of features, and sometimes changed the direction of the
API design. for instance, flutter’s APIs are heavily documented; UX
studies confirmed the value of such documentation, but also highlighted
the need specifically for sample code and illustrative diagrams.
this section discusses some of the decisions made in flutter’s API design
in aid of usability.
<topic_end>
<topic_start>
specializing APIs to match the developer’s mindset
the base class for nodes in flutter’s widget, element, and RenderObject
trees does not define a child model. this allows each node to be
specialized for the child model that is applicable to that node.
most widget objects have a single child widget, and therefore only expose
a single child parameter. some widgets support an arbitrary number of
children, and expose a children parameter that takes a list.
some widgets don’t have any children at all and reserve no memory,
and have no parameters for them. similarly, RenderObjects expose APIs
specific to their child model. RenderImage is a leaf node, and has no
concept of children. RenderPadding takes a single child, so it has storage
for a single pointer to a single child. RenderFlex takes an arbitrary
number of children and manages it as a linked list.
in some rare cases, more complicated child models are used. the
RenderTable render object’s constructor takes an array of arrays of
children, the class exposes getters and setters that control the number
of rows and columns, and there are specific methods to replace
individual children by x,y coordinate, to add a row, to provide a
new array of arrays of children, and to replace the entire child list
with a single array and a column count. in the implementation,
the object does not use a linked list like most render objects but
instead uses an indexable array.
the chip widgets and InputDecoration objects have fields that match
the slots that exist on the relevant controls. where a one-size-fits-all
child model would force semantics to be layered on top of a list of
children, for example, defining the first child to be the prefix value
and the second to be the suffix, the dedicated child model allows for
dedicated named properties to be used instead.
this flexibility allows each node in these trees to be manipulated in
the way most idiomatic for its role. it’s rare to want to insert a cell
in a table, causing all the other cells to wrap around; similarly,
it’s rare to want to remove a child from a flex row by index instead
of by reference.
the RenderParagraph object is the most extreme case: it has a child of
an entirely different type, TextSpan. at the RenderParagraph boundary,
the RenderObject tree transitions into being a TextSpan tree.
the overall approach of specializing APIs to meet the developer’s
expectations is applied to more than just child models.
some rather trivial widgets exist specifically so that developers
will find them when looking for a solution to a problem. adding a
space to a row or column is easily done once one knows how, using
the expanded widget and a zero-sized SizedBox child, but discovering
that pattern is unnecessary because searching for space
uncovers the spacer widget, which uses expanded and SizedBox directly
to achieve the effect.
similarly, hiding a widget subtree is easily done by not including the
widget subtree in the build at all. however, developers typically expect
there to be a widget to do this, and so the visibility widget exists
to wrap this pattern in a trivial reusable widget.
<topic_end>
<topic_start>
explicit arguments
UI frameworks tend to have many properties, such that a developer is
rarely able to remember the semantic meaning of each constructor
argument of each class. as flutter uses the reactive paradigm,
it is common for build methods in flutter to have many calls to
constructors. by leveraging dart’s support for named arguments,
flutter’s API is able to keep such build methods clear and understandable.
this pattern is extended to any method with multiple arguments,
and in particular is extended to any boolean argument, so that isolated
true or false literals in method calls are always self-documenting.
furthermore, to avoid confusion commonly caused by double negatives
in APIs, boolean arguments and properties are always named in the
positive form (for example, enabled: true rather than disabled: false).
<topic_end>
<topic_start>
paving over pitfalls
a technique used in a number of places in the flutter framework is to
define the API such that error conditions don’t exist. this removes
entire classes of errors from consideration.
for example, interpolation functions allow one or both ends of the
interpolation to be null, instead of defining that as an error case:
interpolating between two null values is always null, and interpolating
from a null value or to a null value is the equivalent of interpolating
to the zero analog for the given type. this means that developers
who accidentally pass null to an interpolation function will not hit
an error case, but will instead get a reasonable result.
a more subtle example is in the flex layout algorithm. the concept of
this layout is that the space given to the flex render object is
divided among its children, so the size of the flex should be the
entirety of the available space. in the original design, providing
infinite space would fail: it would imply that the flex should be
infinitely sized, a useless layout configuration. instead, the API
was adjusted so that when infinite space is allocated to the flex
render object, the render object sizes itself to fit the desired
size of the children, reducing the possible number of error cases.
the approach is also used to avoid having constructors that allow
inconsistent data to be created. for instance, the PointerDownEvent
constructor does not allow the down property of PointerEvent to
be set to false (a situation that would be self-contradictory);
instead, the constructor does not have a parameter for the down
field and always sets it to true.
in general, the approach is to define valid interpretations for all
values in the input domain. the simplest example is the color constructor.
instead of taking four integers, one for red, one for green,
one for blue, and one for alpha, each of which could be out of range,
the default constructor takes a single integer value, and defines
the meaning of each bit (for example, the bottom eight bits define the
red component), so that any input value is a valid color value.
a more elaborate example is the paintImage() function. this function
takes eleven arguments, some with quite wide input domains, but they
have been carefully designed to be mostly orthogonal to each other,
such that there are very few invalid combinations.
<topic_end>
<topic_start>
reporting error cases aggressively
not all error conditions can be designed out. for those that remain,
in debug builds, flutter generally attempts to catch the errors very
early and immediately reports them. asserts are widely used.
constructor arguments are sanity checked in detail. lifecycles are
monitored and when inconsistencies are detected they immediately
cause an exception to be thrown.
in some cases, this is taken to extremes: for example, when running
unit tests, regardless of what else the test is doing, every RenderBox
subclass that is laid out aggressively inspects whether its intrinsic
sizing methods fulfill the intrinsic sizing contract. this helps catch
errors in APIs that might otherwise not be exercised.
when exceptions are thrown, they include as much information as
is available. some of flutter’s error messages proactively probe the
associated stack trace to determine the most likely location of the
actual bug. others walk the relevant trees to determine the source
of bad data. the most common errors include detailed instructions
including in some cases sample code for avoiding the error, or links
to further documentation.
<topic_end>
<topic_start>
reactive paradigm
mutable tree-based APIs suffer from a dichotomous access pattern:
creating the tree’s original state typically uses a very different
set of operations than subsequent updates. flutter’s rendering layer
uses this paradigm, as it is an effective way to maintain a persistent tree,
which is key for efficient layout and painting. however, it means
that direct interaction with the rendering layer is awkward at best
and bug-prone at worst.
flutter’s widget layer introduces a composition mechanism using the
reactive paradigm7 to manipulate the
underlying rendering tree.
this API abstracts out the tree manipulation by combining the tree
creation and tree mutation steps into a single tree description (build)
step, where, after each change to the system state, the new configuration
of the user interface is described by the developer and the framework
computes the series of tree mutations necessary to reflect this new
configuration.
<topic_end>
<topic_start>
interpolation
since flutter’s framework encourages developers to describe the interface
configuration matching the current application state, a mechanism exists
to implicitly animate between these configurations.
for example, suppose that in state s1 the interface consists
of a circle, but in state s2 it consists of a square.
without an animation mechanism, the state change would have a jarring
interface change. an implicit animation allows the circle to be smoothly
squared over several frames.
each feature that can be implicitly animated has a stateful widget that
keeps a record of the current value of the input, and begins an animation
sequence whenever the input value changes, transitioning from the current
value to the new value over a specified duration.
this is implemented using lerp (linear interpolation) functions using
immutable objects. each state (circle and square, in this case)
is represented as an immutable object that is configured with
appropriate settings (color, stroke width, etc) and knows how to paint
itself. when it is time to draw the intermediate steps during the animation,
the start and end values are passed to the appropriate lerp function
along with a t value representing the point along the animation,
where 0.0 represents the start and 1.0 represents the
end8,
and the function returns a third immutable object representing the
intermediate stage.
for the circle-to-square transition, the lerp function would return
an object representing a “rounded square” with a radius described as
a fraction derived from the t value, a color interpolated using the
lerp function for colors, and a stroke width interpolated using the
lerp function for doubles. that object, which implements the
same interface as circles and squares, would then be able to paint
itself when requested to.
this technique allows the state machinery, the mapping of states to
configurations, the animation machinery, the interpolation machinery,
and the specific logic relating to how to paint each frame to be
entirely separated from each other.
this approach is broadly applicable. in flutter, basic types like
color and shape can be interpolated, but so can much more elaborate
types such as decoration, TextStyle, or theme. these are
typically constructed from components that can themselves be interpolated,
and interpolating the more complicated objects is often as simple as
recursively interpolating all the values that describe the complicated
objects.
some interpolatable objects are defined by class hierarchies. for example,
shapes are represented by the ShapeBorder interface, and there exists a
variety of shapes, including BeveledRectangleBorder, BoxBorder,
CircleBorder, RoundedRectangleBorder, and StadiumBorder. a single
lerp function can’t anticipate all possible types,
and therefore the interface instead defines lerpFrom and lerpTo methods,
which the static lerp method defers to. when told to interpolate from
a shape a to a shape b, first b is asked if it can lerpFrom a, then,
if it cannot, a is instead asked if it can lerpTo b. (if neither is
possible, then the function returns a from values of t less than 0.5,
and returns b otherwise.)
this allows the class hierarchy to be arbitrarily extended, with later
additions being able to interpolate between previously-known values
and themselves.
in some cases, the interpolation itself cannot be described by any of
the available classes, and a private class is defined to describe the
intermediate stage. this is the case, for instance, when interpolating
between a CircleBorder and a RoundedRectangleBorder.
this mechanism has one further added advantage: it can handle interpolation
from intermediate stages to new values. for example, half-way through
a circle-to-square transition, the shape could be changed once more,
causing the animation to need to interpolate to a triangle. so long as
the triangle class can lerpFrom the rounded-square intermediate class,
the transition can be seamlessly performed.
<topic_end>
<topic_start>
conclusion
flutter’s slogan, “everything is a widget,” revolves around building
user interfaces by composing widgets that are, in turn, composed of
progressively more basic widgets. the result of this aggressive
composition is a large number of widgets that require carefully
designed algorithms and data structures to process efficiently.
with some additional design, these data structures also make it
easy for developers to create infinite scrolling lists that build
widgets on demand when they become visible.
footnotes:
1 for layout, at least. it might be revisited
  for painting, for building the accessibility tree if necessary,
  and for hit testing if necessary.
2 reality, of course, is a bit more
  complicated. some layouts involve intrinsic dimensions or baseline
  measurements, which do involve an additional walk of the relevant subtree
  (aggressive caching is used to mitigate the potential for quadratic
  performance in the worst case). these cases, however, are surprisingly
  rare. in particular, intrinsic dimensions are not required for the
  common case of shrink-wrapping.
3 technically, the child’s position is not
  part of its RenderBox geometry and therefore need not actually be
  calculated during layout. many render objects implicitly position
  their single child at 0,0 relative to their own origin, which
  requires no computation or storage at all. some render objects
  avoid computing the position of their children until the last
  possible moment (for example, during the paint phase), to avoid
  the computation entirely if they are not subsequently painted.
4  there exists one exception to this rule.
  as discussed in the building widgets on demand
  section, some widgets can be rebuilt as a result of a change in layout
  constraints. if a widget marked itself dirty for unrelated reasons in
  the same frame that it also is affected by a change in layout constraints,
  it will be updated twice. this redundant build is limited to the
  widget itself and does not impact its descendants.
5 a key is an opaque object optionally
  associated with a widget whose equality operator is used to influence
  the reconciliation algorithm.
6  for accessibility, and to give applications
  a few extra milliseconds between when a widget is built and when it
  appears on the screen, the viewport creates (but does not paint)
  widgets for a few hundred pixels before and after the visible widgets.
7  this approach was first made popular by
  facebook’s react library.
8  in practice, the t value is allowed
  to extend past the 0.0-1.0 range, and does so for some curves. for
  example, the “elastic” curves overshoot briefly in order to represent
  a bouncing effect. the interpolation logic typically can extrapolate
  past the start or end as appropriate. for some types, for example,
  when interpolating colors, the t value is effectively clamped to
  the 0.0-1.0 range.
<topic_end>
<topic_start>
understanding constraints
info note
  if you are experiencing specific layout errors,
  you might check out common flutter errors.
when someone learning flutter asks you why some widget
with width: 100 isn’t 100 pixels wide,
the default answer is to tell them to put that widget
inside of a center, right?
don’t do that.
if you do, they’ll come back again and again,
asking why some FittedBox isn’t working,
why that column is overflowing, or what
IntrinsicWidth is supposed to be doing.
instead, first tell them that flutter layout is very different
from HTML layout (which is probably where they’re coming from),
and then make them memorize the following rule:
flutter layout can’t really be understood without knowing
this rule, so flutter developers should learn it early on.
in more detail:
for example, if a composed widget contains a column
with some padding, and wants to lay out its two children
as follows:
the negotiation goes something like this:
widget: “hey parent, what are my constraints?”
parent: “you must be from 0 to 300 pixels wide,
   and 0 to 85 tall.”
widget: “hmmm, since i want to have 5 pixels of padding,
   then my children can have at most 290 pixels of width
   and 75 pixels of height.”
widget: “hey first child, you must be from 0 to 290
   pixels wide, and 0 to 75 tall.”
first child: “ok, then i wish to be 290 pixels wide,
   and 20 pixels tall.”
widget: “hmmm, since i want to put my second child below the
   first one, this leaves only 55 pixels of height for
   my second child.”
widget: “hey second child, you must be from 0 to 290 wide,
   and 0 to 55 tall.”
second child: “ok, i wish to be 140 pixels wide,
   and 30 pixels tall.”
widget: “very well. my first child has position x: 5 and y: 5,
   and my second child has x: 80 and y: 25.”
widget: “hey parent, i’ve decided that my size is going to be 300
   pixels wide, and 60 pixels tall.”
<topic_end>
<topic_start>
limitations
flutter’s layout engine is designed to be a one-pass process.
this means that flutter lays out its widgets very efficiently,
but does result in a few limitations:
a widget can decide its own size only within the
constraints given to it by its parent.
this means a widget usually
can’t have any size it wants.
a widget can’t know and doesn’t decide its own position
in the screen, since it’s the widget’s parent who decides
the position of the widget.
since the parent’s size and position, in its turn,
also depends on its own parent, it’s impossible to
precisely define the size and position of any widget
without taking into consideration the tree as a whole.
if a child wants a different size from its parent and
the parent doesn’t have enough information to align it,
then the child’s size might be ignored.
be specific when defining alignment.
in flutter, widgets are rendered by their underlying
RenderBox objects. many boxes in flutter,
especially those that just take a single child,
pass their constraint on to their children.
generally, there are three kinds of boxes,
in terms of how they handle their constraints:
some widgets, for example container,
vary from type to type based on their constructor arguments.
the container constructor defaults
to trying to be as big as possible, but if you give it a width,
for instance, it tries to honor that and be that particular size.
others, for example row and column (flex boxes)
vary based on the constraints they are given,
as described in the flex section.
<topic_end>
<topic_start>
examples
for an interactive experience, use the following DartPad.
use the numbered horizontal scrolling bar to switch between
29 different examples.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const HomePage());
const red = colors.red;
const green = colors.green;
const blue = colors.blue;
const big = TextStyle(fontSize: 30);
//////////////////////////////////////////////////
class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  widget build(BuildContext context) {
    return const FlutterLayoutArticle([
      example1(),
      example2(),
      example3(),
      example4(),
      example5(),
      example6(),
      example7(),
      example8(),
      example9(),
      example10(),
      example11(),
      example12(),
      example13(),
      example14(),
      example15(),
      example16(),
      example17(),
      example18(),
      example19(),
      example20(),
      example21(),
      example22(),
      example23(),
      example24(),
      example25(),
      example26(),
      example27(),
      example28(),
      example29(),
    ]);
  }
}
//////////////////////////////////////////////////
abstract class example extends StatelessWidget {
  const example({super.key});
  string get code;
  string get explanation;
}
//////////////////////////////////////////////////
class FlutterLayoutArticle extends StatefulWidget {
  const FlutterLayoutArticle(
    this.examples, {
    super.key,
  });
  final List<Example> examples;
  @override
  State<FlutterLayoutArticle> createState() => _FlutterLayoutArticleState();
}
//////////////////////////////////////////////////
class _FlutterLayoutArticleState extends State<FlutterLayoutArticle> {
  late int count;
  late widget example;
  late string code;
  late string explanation;
  @override
  void initState() {
    count = 1;
    code = const example1().code;
    explanation = const example1().explanation;
    super.initState();
  }
  @override
  void didUpdateWidget(FlutterLayoutArticle oldWidget) {
    super.didUpdateWidget(oldWidget);
    var example = widget.examples[count - 1];
    code = example.code;
    explanation = example.explanation;
  }
  @override
  widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'flutter layout article',
      home: SafeArea(
        child: material(
          color: colors.black,
          child: FittedBox(
            child: container(
              width: 400,
              height: 670,
              color: const Color(0xFFCCCCCC),
              child: column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  expanded(
                      child: ConstrainedBox(
                          constraints: const BoxConstraints.tightFor(
                              width: double.infinity, height: double.infinity),
                          child: widget.examples[count - 1])),
                  container(
                    height: 50,
                    width: double.infinity,
                    color: colors.black,
                    child: SingleChildScrollView(
                      scrollDirection: axis.horizontal,
                      child: row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          for (int i = 0; i < widget.examples.length; i++)
                            container(
                              width: 58,
                              padding: const EdgeInsets.only(left: 4, right: 4),
                              child: button(i + 1),
                            ),
                        ],
                      ),
                    ),
                  ),
                  container(
                    height: 273,
                    color: colors.grey[50],
                    child: scrollbar(
                      child: SingleChildScrollView(
                        key: ValueKey(count),
                        child: padding(
                          padding: const EdgeInsets.all(10),
                          child: column(
                            children: [
                              center(child: text(code)),
                              const SizedBox(height: 15),
                              text(
                                explanation,
                                style: TextStyle(
                                    color: colors.blue[900],
                                    fontStyle: FontStyle.italic),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
  widget button(int exampleNumber) {
    return button(
      key: ValueKey('button$exampleNumber'),
      isSelected: count == exampleNumber,
      exampleNumber: exampleNumber,
      onPressed: () {
        showExample(
          exampleNumber,
          widget.examples[exampleNumber - 1].code,
          widget.examples[exampleNumber - 1].explanation,
        );
      },
    );
  }
  void showExample(int exampleNumber, string code, string explanation) {
    setState(() {
      count = exampleNumber;
      this.code = code;
      this.explanation = explanation;
    });
  }
}
//////////////////////////////////////////////////
class button extends StatelessWidget {
  final bool isSelected;
  final int exampleNumber;
  final VoidCallback onPressed;
  const button({
    super.key,
    required this.isSelected,
    required this.exampleNumber,
    required this.onPressed,
  });
  @override
  widget build(BuildContext context) {
    return TextButton(
      style: TextButton.styleFrom(
        foregroundColor: colors.white,
        backgroundColor: isSelected ? colors.grey : colors.grey[800],
      ),
      child: Text(exampleNumber.toString()),
      onPressed: () {
        Scrollable.ensureVisible(
          context,
          duration: const duration(milliseconds: 350),
          curve: Curves.easeOut,
          alignment: 0.5,
        );
        onPressed();
      },
    );
  }
}
//////////////////////////////////////////////////
class example1 extends example {
  const example1({super.key});
  @override
  final code = 'container(color: red)';
  @override
  final explanation = 'the screen is the parent of the container, '
      'and it forces the container to be exactly the same size as the screen.'
      '\n\n'
      'so the container fills the screen and paints it red.';
  @override
  widget build(BuildContext context) {
    return container(color: red);
  }
}
//////////////////////////////////////////////////
class example2 extends example {
  const example2({super.key});
  @override
  final code = 'container(width: 100, height: 100, color: red)';
  @override
  final string explanation =
      'the red container wants to be 100x100, but it can\'t, '
      'because the screen forces it to be exactly the same size as the screen.'
      '\n\n'
      'so the container fills the screen.';
  @override
  widget build(BuildContext context) {
    return container(width: 100, height: 100, color: red);
  }
}
//////////////////////////////////////////////////
class example3 extends example {
  const example3({super.key});
  @override
  final code = 'center(\n'
      '   child: container(width: 100, height: 100, color: red))';
  @override
  final string explanation =
      'the screen forces the center to be exactly the same size as the screen, '
      'so the center fills the screen.'
      '\n\n'
      'the center tells the container that it can be any size it wants, but not bigger than the screen.'
      'now the container can indeed be 100x100.';
  @override
  widget build(BuildContext context) {
    return center(
      child: container(width: 100, height: 100, color: red),
    );
  }
}
//////////////////////////////////////////////////
class example4 extends example {
  const example4({super.key});
  @override
  final code = 'align(\n'
      '   alignment: Alignment.bottomRight,\n'
      '   child: container(width: 100, height: 100, color: red))';
  @override
  final string explanation =
      'this is different from the previous example in that it uses align instead of center.'
      '\n\n'
      'align also tells the container that it can be any size it wants, but if there is empty space it won\'t center the container. '
      'instead, it aligns the container to the bottom-right of the available space.';
  @override
  widget build(BuildContext context) {
    return align(
      alignment: Alignment.bottomRight,
      child: container(width: 100, height: 100, color: red),
    );
  }
}
//////////////////////////////////////////////////
class example5 extends example {
  const example5({super.key});
  @override
  final code = 'center(\n'
      '   child: container(\n'
      '              color: red,\n'
      '              width: double.infinity,\n'
      '              height: double.infinity))';
  @override
  final string explanation =
      'the screen forces the center to be exactly the same size as the screen, '
      'so the center fills the screen.'
      '\n\n'
      'the center tells the container that it can be any size it wants, but not bigger than the screen.'
      'the container wants to be of infinite size, but since it can\'t be bigger than the screen, it just fills the screen.';
  @override
  widget build(BuildContext context) {
    return center(
      child: container(
          width: double.infinity, height: double.infinity, color: red),
    );
  }
}
//////////////////////////////////////////////////
class example6 extends example {
  const example6({super.key});
  @override
  final code = 'center(child: container(color: red))';
  @override
  final string explanation =
      'the screen forces the center to be exactly the same size as the screen, '
      'so the center fills the screen.'
      '\n\n'
      'the center tells the container that it can be any size it wants, but not bigger than the screen.'
      '\n\n'
      'since the container has no child and no fixed size, it decides it wants to be as big as possible, so it fills the whole screen.'
      '\n\n'
      'but why does the container decide that? '
      'simply because that\'s a design decision by those who created the container widget. '
      'it could have been created differently, and you have to read the container documentation to understand how it behaves, depending on the circumstances. ';
  @override
  widget build(BuildContext context) {
    return center(
      child: container(color: red),
    );
  }
}
//////////////////////////////////////////////////
class example7 extends example {
  const example7({super.key});
  @override
  final code = 'center(\n'
      '   child: container(color: red\n'
      '      child: container(color: green, width: 30, height: 30)))';
  @override
  final string explanation =
      'the screen forces the center to be exactly the same size as the screen, '
      'so the center fills the screen.'
      '\n\n'
      'the center tells the red container that it can be any size it wants, but not bigger than the screen.'
      'since the red container has no size but has a child, it decides it wants to be the same size as its child.'
      '\n\n'
      'the red container tells its child that it can be any size it wants, but not bigger than the screen.'
      '\n\n'
      'the child is a green container that wants to be 30x30.'
      '\n\n'
      'since the red `container` has no size but has a child, it decides it wants to be the same size as its child. '
      'the red color isn\'t visible, since the green container entirely covers all of the red container.';
  @override
  widget build(BuildContext context) {
    return center(
      child: container(
        color: red,
        child: container(color: green, width: 30, height: 30),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example8 extends example {
  const example8({super.key});
  @override
  final code = 'center(\n'
      '   child: container(color: red\n'
      '      padding: const EdgeInsets.all(20),\n'
      '      child: container(color: green, width: 30, height: 30)))';
  @override
  final string explanation =
      'the red container sizes itself to its children size, but it takes its own padding into consideration. '
      'so it is also 30x30 plus padding. '
      'the red color is visible because of the padding, and the green container has the same size as in the previous example.';
  @override
  widget build(BuildContext context) {
    return center(
      child: container(
        padding: const EdgeInsets.all(20),
        color: red,
        child: container(color: green, width: 30, height: 30),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example9 extends example {
  const example9({super.key});
  @override
  final code = 'constrainedbox(\n'
      '   constraints: BoxConstraints(\n'
      '              minWidth: 70, minHeight: 70,\n'
      '              maxWidth: 150, maxHeight: 150),\n'
      '      child: container(color: red, width: 10, height: 10)))';
  @override
  final string explanation =
      'you might guess that the container has to be between 70 and 150 pixels, but you would be wrong. '
      'the ConstrainedBox only imposes ADDITIONAL constraints from those it receives from its parent.'
      '\n\n'
      'here, the screen forces the ConstrainedBox to be exactly the same size as the screen, '
      'so it tells its child container to also assume the size of the screen, '
      'thus ignoring its \'constraints\' parameter.';
  @override
  widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: const BoxConstraints(
        minWidth: 70,
        minHeight: 70,
        maxWidth: 150,
        maxHeight: 150,
      ),
      child: container(color: red, width: 10, height: 10),
    );
  }
}
//////////////////////////////////////////////////
class example10 extends example {
  const example10({super.key});
  @override
  final code = 'center(\n'
      '   child: ConstrainedBox(\n'
      '      constraints: BoxConstraints(\n'
      '                 minWidth: 70, minHeight: 70,\n'
      '                 maxWidth: 150, maxHeight: 150),\n'
      '        child: container(color: red, width: 10, height: 10))))';
  @override
  final string explanation =
      'now, center allows ConstrainedBox to be any size up to the screen size.'
      '\n\n'
      'the ConstrainedBox imposes ADDITIONAL constraints from its \'constraints\' parameter onto its child.'
      '\n\n'
      'the container must be between 70 and 150 pixels. it wants to have 10 pixels, so it will end up having 70 (the MINIMUM).';
  @override
  widget build(BuildContext context) {
    return center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          minWidth: 70,
          minHeight: 70,
          maxWidth: 150,
          maxHeight: 150,
        ),
        child: container(color: red, width: 10, height: 10),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example11 extends example {
  const example11({super.key});
  @override
  final code = 'center(\n'
      '   child: ConstrainedBox(\n'
      '      constraints: BoxConstraints(\n'
      '                 minWidth: 70, minHeight: 70,\n'
      '                 maxWidth: 150, maxHeight: 150),\n'
      '        child: container(color: red, width: 1000, height: 1000))))';
  @override
  final string explanation =
      'center allows ConstrainedBox to be any size up to the screen size.'
      'the ConstrainedBox imposes ADDITIONAL constraints from its \'constraints\' parameter onto its child'
      '\n\n'
      'the container must be between 70 and 150 pixels. it wants to have 1000 pixels, so it ends up having 150 (the MAXIMUM).';
  @override
  widget build(BuildContext context) {
    return center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          minWidth: 70,
          minHeight: 70,
          maxWidth: 150,
          maxHeight: 150,
        ),
        child: container(color: red, width: 1000, height: 1000),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example12 extends example {
  const example12({super.key});
  @override
  final code = 'center(\n'
      '   child: ConstrainedBox(\n'
      '      constraints: BoxConstraints(\n'
      '                 minWidth: 70, minHeight: 70,\n'
      '                 maxWidth: 150, maxHeight: 150),\n'
      '        child: container(color: red, width: 100, height: 100))))';
  @override
  final string explanation =
      'center allows ConstrainedBox to be any size up to the screen size.'
      'constrainedbox imposes ADDITIONAL constraints from its \'constraints\' parameter onto its child.'
      '\n\n'
      'the container must be between 70 and 150 pixels. it wants to have 100 pixels, and that\'s the size it has, since that\'s between 70 and 150.';
  @override
  widget build(BuildContext context) {
    return center(
      child: ConstrainedBox(
        constraints: const BoxConstraints(
          minWidth: 70,
          minHeight: 70,
          maxWidth: 150,
          maxHeight: 150,
        ),
        child: container(color: red, width: 100, height: 100),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example13 extends example {
  const example13({super.key});
  @override
  final code = 'unconstrainedbox(\n'
      '   child: container(color: red, width: 20, height: 50));';
  @override
  final string explanation =
      'the screen forces the UnconstrainedBox to be exactly the same size as the screen.'
      'however, the UnconstrainedBox lets its child container be any size it wants.';
  @override
  widget build(BuildContext context) {
    return UnconstrainedBox(
      child: container(color: red, width: 20, height: 50),
    );
  }
}
//////////////////////////////////////////////////
class example14 extends example {
  const example14({super.key});
  @override
  final code = 'unconstrainedbox(\n'
      '   child: container(color: red, width: 4000, height: 50));';
  @override
  final string explanation =
      'the screen forces the UnconstrainedBox to be exactly the same size as the screen, '
      'and UnconstrainedBox lets its child container be any size it wants.'
      '\n\n'
      'unfortunately, in this case the container has 4000 pixels of width and is too big to fit in the UnconstrainedBox, '
      'so the UnconstrainedBox displays the much dreaded "overflow warning".';
  @override
  widget build(BuildContext context) {
    return UnconstrainedBox(
      child: container(color: red, width: 4000, height: 50),
    );
  }
}
//////////////////////////////////////////////////
class example15 extends example {
  const example15({super.key});
  @override
  final code = 'overflowbox(\n'
      '   minWidth: 0,'
      '   minHeight: 0,'
      '   maxWidth: double.infinity,'
      '   maxHeight: double.infinity,'
      '   child: container(color: red, width: 4000, height: 50));';
  @override
  final string explanation =
      'the screen forces the OverflowBox to be exactly the same size as the screen, '
      'and OverflowBox lets its child container be any size it wants.'
      '\n\n'
      'overflowbox is similar to UnconstrainedBox, and the difference is that it won\'t display any warnings if the child doesn\'t fit the space.'
      '\n\n'
      'in this case the container is 4000 pixels wide, and is too big to fit in the OverflowBox, '
      'but the OverflowBox simply shows as much as it can, with no warnings given.';
  @override
  widget build(BuildContext context) {
    return OverflowBox(
      minWidth: 0,
      minHeight: 0,
      maxWidth: double.infinity,
      maxHeight: double.infinity,
      child: container(color: red, width: 4000, height: 50),
    );
  }
}
//////////////////////////////////////////////////
class example16 extends example {
  const example16({super.key});
  @override
  final code = 'unconstrainedbox(\n'
      '   child: container(color: colors.red, width: double.infinity, height: 100));';
  @override
  final string explanation =
      'this won\'t render anything, and you\'ll see an error in the console.'
      '\n\n'
      'the UnconstrainedBox lets its child be any size it wants, '
      'however its child is a container with infinite size.'
      '\n\n'
      'flutter can\'t render infinite sizes, so it throws an error with the following message: '
      '"boxconstraints forces an infinite width."';
  @override
  widget build(BuildContext context) {
    return UnconstrainedBox(
      child: container(color: colors.red, width: double.infinity, height: 100),
    );
  }
}
//////////////////////////////////////////////////
class example17 extends example {
  const example17({super.key});
  @override
  final code = 'unconstrainedbox(\n'
      '   child: LimitedBox(maxWidth: 100,\n'
      '      child: container(color: colors.red,\n'
      '                       width: double.infinity, height: 100));';
  @override
  final string explanation = 'here you won\'t get an error anymore, '
      'because when the LimitedBox is given an infinite size by the UnconstrainedBox, '
      'it passes a maximum width of 100 down to its child.'
      '\n\n'
      'if you swap the UnconstrainedBox for a center widget, '
      'the LimitedBox won\'t apply its limit anymore (since its limit is only applied when it gets infinite constraints), '
      'and the width of the container is allowed to grow past 100.'
      '\n\n'
      'this explains the difference between a LimitedBox and a ConstrainedBox.';
  @override
  widget build(BuildContext context) {
    return UnconstrainedBox(
      child: LimitedBox(
        maxWidth: 100,
        child: container(
          color: colors.red,
          width: double.infinity,
          height: 100,
        ),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example18 extends example {
  const example18({super.key});
  @override
  final code = 'fittedbox(\n'
      '   child: Text(\'Some example text.\'));';
  @override
  final string explanation =
      'the screen forces the FittedBox to be exactly the same size as the screen.'
      'the text has some natural width (also called its intrinsic width) that depends on the amount of text, its font size, and so on.'
      '\n\n'
      'the FittedBox lets the text be any size it wants, '
      'but after the text tells its size to the FittedBox, '
      'the FittedBox scales the text until it fills all of the available width.';
  @override
  widget build(BuildContext context) {
    return const FittedBox(
      child: Text('Some example text.'),
    );
  }
}
//////////////////////////////////////////////////
class example19 extends example {
  const example19({super.key});
  @override
  final code = 'center(\n'
      '   child: FittedBox(\n'
      '      child: Text(\'Some example text.\')));';
  @override
  final string explanation =
      'but what happens if you put the FittedBox inside of a center widget? '
      'the center lets the FittedBox be any size it wants, up to the screen size.'
      '\n\n'
      'the FittedBox then sizes itself to the text, and lets the text be any size it wants.'
      '\n\n'
      'since both FittedBox and the text have the same size, no scaling happens.';
  @override
  widget build(BuildContext context) {
    return const center(
      child: FittedBox(
        child: Text('Some example text.'),
      ),
    );
  }
}
////////////////////////////////////////////////////
class example20 extends example {
  const example20({super.key});
  @override
  final code = 'center(\n'
      '   child: FittedBox(\n'
      '      child: text(\'…\')));';
  @override
  final string explanation =
      'however, what happens if FittedBox is inside of a center widget, but the text is too large to fit the screen?'
      '\n\n'
      'fittedbox tries to size itself to the text, but it can\'t be bigger than the screen. '
      'it then assumes the screen size, and resizes text so that it fits the screen, too.';
  @override
  widget build(BuildContext context) {
    return const center(
      child: FittedBox(
        child: text(
            'this is some very very very large text that is too big to fit a regular screen in a single line.'),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example21 extends example {
  const example21({super.key});
  @override
  final code = 'center(\n'
      '   child: text(\'…\'));';
  @override
  final string explanation = 'if, however, you remove the FittedBox, '
      'the text gets its maximum width from the screen, '
      'and breaks the line so that it fits the screen.';
  @override
  widget build(BuildContext context) {
    return const center(
      child: text(
          'this is some very very very large text that is too big to fit a regular screen in a single line.'),
    );
  }
}
//////////////////////////////////////////////////
class example22 extends example {
  const example22({super.key});
  @override
  final code = 'fittedbox(\n'
      '   child: container(\n'
      '      height: 20, width: double.infinity));';
  @override
  final string explanation =
      'fittedbox can only scale a widget that is BOUNDED (has non-infinite width and height).'
      'otherwise, it won\'t render anything, and you\'ll see an error in the console.';
  @override
  widget build(BuildContext context) {
    return FittedBox(
      child: container(
        height: 20,
        width: double.infinity,
        color: colors.red,
      ),
    );
  }
}
//////////////////////////////////////////////////
class example23 extends example {
  const example23({super.key});
  @override
  final code = 'row(children:[\n'
      '   container(color: red, child: Text(\'Hello!\'))\n'
      '   container(color: green, child: Text(\'Goodbye!\'))]';
  @override
  final string explanation =
      'the screen forces the row to be exactly the same size as the screen.'
      '\n\n'
      'just like an UnconstrainedBox, the row won\'t impose any constraints onto its children, '
      'and instead lets them be any size they want.'
      '\n\n'
      'the row then puts them side-by-side, and any extra space remains empty.';
  @override
  widget build(BuildContext context) {
    return row(
      children: [
        container(color: red, child: const Text('Hello!', style: big)),
        container(color: green, child: const Text('Goodbye!', style: big)),
      ],
    );
  }
}
//////////////////////////////////////////////////
class example24 extends example {
  const example24({super.key});
  @override
  final code = 'row(children:[\n'
      '   container(color: red, child: text(\'…\'))\n'
      '   container(color: green, child: Text(\'Goodbye!\'))]';
  @override
  final string explanation =
      'since the row won\'t impose any constraints onto its children, '
      'it\'s quite possible that the children might be too big to fit the available width of the row.'
      'in this case, just like an UnconstrainedBox, the row displays the "overflow warning".';
  @override
  widget build(BuildContext context) {
    return row(
      children: [
        container(
          color: red,
          child: const text(
            'this is a very long text that '
            'won\'t fit the line.',
            style: big,
          ),
        ),
        container(color: green, child: const Text('Goodbye!', style: big)),
      ],
    );
  }
}
//////////////////////////////////////////////////
class example25 extends example {
  const example25({super.key});
  @override
  final code = 'row(children:[\n'
      '   expanded(\n'
      '       child: container(color: red, child: text(\'…\')))\n'
      '   container(color: green, child: Text(\'Goodbye!\'))]';
  @override
  final string explanation =
      'when a row\'s child is wrapped in an expanded widget, the row won\'t let this child define its own width anymore.'
      '\n\n'
      'instead, it defines the expanded width according to the other children, and only then the expanded widget forces the original child to have the expanded\'s width.'
      '\n\n'
      'in other words, once you use expanded, the original child\'s width becomes irrelevant, and is ignored.';
  @override
  widget build(BuildContext context) {
    return row(
      children: [
        expanded(
          child: center(
            child: container(
              color: red,
              child: const text(
                'this is a very long text that won\'t fit the line.',
                style: big,
              ),
            ),
          ),
        ),
        container(color: green, child: const Text('Goodbye!', style: big)),
      ],
    );
  }
}
//////////////////////////////////////////////////
class example26 extends example {
  const example26({super.key});
  @override
  final code = 'row(children:[\n'
      '   expanded(\n'
      '       child: container(color: red, child: text(\'…\')))\n'
      '   expanded(\n'
      '       child: container(color: green, child: Text(\'Goodbye!\'))]';
  @override
  final string explanation =
      'if all of row\'s children are wrapped in expanded widgets, each expanded has a size proportional to its flex parameter, '
      'and only then each expanded widget forces its child to have the expanded\'s width.'
      '\n\n'
      'in other words, expanded ignores the preferred width of its children.';
  @override
  widget build(BuildContext context) {
    return row(
      children: [
        expanded(
          child: container(
            color: red,
            child: const text(
              'this is a very long text that won\'t fit the line.',
              style: big,
            ),
          ),
        ),
        expanded(
          child: container(
            color: green,
            child: const text(
              'goodbye!',
              style: big,
            ),
          ),
        ),
      ],
    );
  }
}
//////////////////////////////////////////////////
class example27 extends example {
  const example27({super.key});
  @override
  final code = 'row(children:[\n'
      '   flexible(\n'
      '       child: container(color: red, child: text(\'…\')))\n'
      '   flexible(\n'
      '       child: container(color: green, child: Text(\'Goodbye!\'))]';
  @override
  final string explanation =
      'the only difference if you use flexible instead of expanded, '
      'is that flexible lets its child be SMALLER than the flexible width, '
      'while expanded forces its child to have the same width of the expanded.'
      '\n\n'
      'but both expanded and flexible ignore their children\'s width when sizing themselves.'
      '\n\n'
      'this means that it\'s IMPOSSIBLE to expand row children proportionally to their sizes. '
      'the row either uses the exact child\'s width, or ignores it completely when you use expanded or flexible.';
  @override
  widget build(BuildContext context) {
    return row(
      children: [
        flexible(
          child: container(
            color: red,
            child: const text(
              'this is a very long text that won\'t fit the line.',
              style: big,
            ),
          ),
        ),
        flexible(
          child: container(
            color: green,
            child: const text(
              'goodbye!',
              style: big,
            ),
          ),
        ),
      ],
    );
  }
}
//////////////////////////////////////////////////
class example28 extends example {
  const example28({super.key});
  @override
  final code = 'scaffold(\n'
      '   body: container(color: blue,\n'
      '   child: column(\n'
      '      children: [\n'
      '         Text(\'Hello!\'),\n'
      '         Text(\'Goodbye!\')])))';
  @override
  final string explanation =
      'the screen forces the scaffold to be exactly the same size as the screen, '
      'so the scaffold fills the screen.'
      '\n\n'
      'the scaffold tells the container that it can be any size it wants, but not bigger than the screen.'
      '\n\n'
      'when a widget tells its child that it can be smaller than a certain size, '
      'we say the widget supplies "loose" constraints to its child. more on that later.';
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: container(
        color: blue,
        child: const column(
          children: [
            Text('Hello!'),
            Text('Goodbye!'),
          ],
        ),
      ),
    );
  }
}
//////////////////////////////////////////////////
class example29 extends example {
  const example29({super.key});
  @override
  final code = 'scaffold(\n'
      '   body: container(color: blue,\n'
      '   child: SizedBox.expand(\n'
      '      child: column(\n'
      '         children: [\n'
      '            Text(\'Hello!\'),\n'
      '            Text(\'Goodbye!\')]))))';
  @override
  final string explanation =
      'if you want the scaffold\'s child to be exactly the same size as the scaffold itself, '
      'you can wrap its child with SizedBox.expand.'
      '\n\n'
      'when a widget tells its child that it must be of a certain size, '
      'we say the widget supplies "tight" constraints to its child. more on that later.';
  @override
  widget build(BuildContext context) {
    return scaffold(
      body: SizedBox.expand(
        child: container(
          color: blue,
          child: const column(
            children: [
              Text('Hello!'),
              Text('Goodbye!'),
            ],
          ),
        ),
      ),
    );
  }
}
//////////////////////////////////////////////////
<code_end>
if you prefer, you can grab the code from
this GitHub repo.
the examples are explained in the following sections.
<topic_end>
<topic_start>
example 1
<code_start>
container(color: red)
<code_end>
the screen is the parent of the container, and it
forces the container to be exactly the same size as the screen.
so the container fills the screen and paints it red.
<topic_end>
<topic_start>
example 2
<code_start>
container(width: 100, height: 100, color: red)
<code_end>
the red container wants to be 100 × 100,
but it can’t, because the screen forces it to be
exactly the same size as the screen.
so the container fills the screen.
<topic_end>
<topic_start>
example 3
<code_start>
center(
  child: container(width: 100, height: 100, color: red),
)
<code_end>
the screen forces the center to be exactly the same size
as the screen, so the center fills the screen.
the center tells the container that it can be any size it
wants, but not bigger than the screen. now the container
can indeed be 100 × 100.
<topic_end>
<topic_start>
example 4
<code_start>
align(
  alignment: Alignment.bottomRight,
  child: container(width: 100, height: 100, color: red),
)
<code_end>
this is different from the previous example in that it uses
align instead of center.
align also tells the container that it can be any size it
wants, but if there is empty space it won’t center the container.
instead, it aligns the container to the bottom-right of the
available space.
<topic_end>
<topic_start>
example 5
<code_start>
center(
  child: container(
      width: double.infinity, height: double.infinity, color: red),
)
<code_end>
the screen forces the center to be exactly the
same size as the screen, so the center fills the screen.
the center tells the container that it can be any size it wants,
but not bigger than the screen. the container wants to be
of infinite size, but since it can’t be bigger than the screen,
it just fills the screen.
<topic_end>
<topic_start>
example 6
<code_start>
center(
  child: container(color: red),
)
<code_end>
the screen forces the center to be exactly the
same size as the screen, so the center fills the screen.
the center tells the container that it can be any
size it wants, but not bigger than the screen.
since the container has no child and no fixed size,
it decides it wants to be as big as possible,
so it fills the whole screen.
but why does the container decide that?
simply because that’s a design decision by those who
created the container widget. it could have been
created differently, and you have to read the
container API documentation to understand
how it behaves, depending on the circumstances.
<topic_end>
<topic_start>
example 7
<code_start>
center(
  child: container(
    color: red,
    child: container(color: green, width: 30, height: 30),
  ),
)
<code_end>
the screen forces the center to be exactly the same
size as the screen, so the center fills the screen.
the center tells the red container that it can be any size
it wants, but not bigger than the screen. since the red
container has no size but has a child,
it decides it wants to be the same size as its child.
the red container tells its child that it can be any size
it wants, but not bigger than the screen.
the child is a green container that wants to
be 30 × 30. given that the red container sizes itself to
the size of its child, it is also 30 × 30.
the red color isn’t visible because the green container
entirely covers the red container.
<topic_end>
<topic_start>
example 8
<code_start>
center(
  child: container(
    padding: const EdgeInsets.all(20),
    color: red,
    child: container(color: green, width: 30, height: 30),
  ),
)
<code_end>
the red container sizes itself to its children’s size,
but it takes its own padding into consideration.
so it is also 30 × 30 plus padding.
the red color is visible because of the padding,
and the green container has the same size as
in the previous example.
<topic_end>
<topic_start>
example 9
<code_start>
ConstrainedBox(
  constraints: const BoxConstraints(
    minWidth: 70,
    minHeight: 70,
    maxWidth: 150,
    maxHeight: 150,
  ),
  child: container(color: red, width: 10, height: 10),
)
<code_end>
you might guess that the container has to be
between 70 and 150 pixels, but you would be wrong.
the ConstrainedBox only imposes additional constraints
from those it receives from its parent.
here, the screen forces the ConstrainedBox to be exactly
the same size as the screen, so it tells its child container
to also assume the size of the screen, thus ignoring its
constraints parameter.
<topic_end>
<topic_start>
example 10
<code_start>
center(
  child: ConstrainedBox(
    constraints: const BoxConstraints(
      minWidth: 70,
      minHeight: 70,
      maxWidth: 150,
      maxHeight: 150,
    ),
    child: container(color: red, width: 10, height: 10),
  ),
)
<code_end>
now, center allows ConstrainedBox to be any size up to
the screen size. the ConstrainedBox imposes additional
constraints from its constraints parameter onto its child.
the container must be between 70 and 150 pixels.
it wants to have 10 pixels,
so it ends up having 70 (the minimum).
<topic_end>
<topic_start>
example 11
<code_start>
center(
  child: ConstrainedBox(
    constraints: const BoxConstraints(
      minWidth: 70,
      minHeight: 70,
      maxWidth: 150,
      maxHeight: 150,
    ),
    child: container(color: red, width: 1000, height: 1000),
  ),
)
<code_end>
center allows ConstrainedBox to be any size up to the
screen size. the ConstrainedBox imposes additional
constraints from its constraints parameter onto its child.
the container must be between 70 and 150 pixels.
it wants to have 1000 pixels,
so it ends up having 150 (the maximum).
<topic_end>
<topic_start>
example 12
<code_start>
center(
  child: ConstrainedBox(
    constraints: const BoxConstraints(
      minWidth: 70,
      minHeight: 70,
      maxWidth: 150,
      maxHeight: 150,
    ),
    child: container(color: red, width: 100, height: 100),
  ),
)
<code_end>
center allows ConstrainedBox to be any size up to the
screen size. the ConstrainedBox imposes additional
constraints from its constraints parameter onto its child.
the container must be between 70 and 150 pixels.
it wants to have 100 pixels, and that’s the size it has,
since that’s between 70 and 150.
<topic_end>
<topic_start>
example 13
<code_start>
UnconstrainedBox(
  child: container(color: red, width: 20, height: 50),
)
<code_end>
the screen forces the UnconstrainedBox to be exactly
the same size as the screen. however, the UnconstrainedBox
lets its child container be any size it wants.
<topic_end>
<topic_start>
example 14
<code_start>
UnconstrainedBox(
  child: container(color: red, width: 4000, height: 50),
)
<code_end>
the screen forces the UnconstrainedBox to be exactly
the same size as the screen, and UnconstrainedBox
lets its child container be any size it wants.
unfortunately, in this case the container is
4000 pixels wide and is too big to fit in
the UnconstrainedBox, so the UnconstrainedBox displays
the much dreaded “overflow warning”.
<topic_end>
<topic_start>
example 15
<code_start>
OverflowBox(
  minWidth: 0,
  minHeight: 0,
  maxWidth: double.infinity,
  maxHeight: double.infinity,
  child: container(color: red, width: 4000, height: 50),
)
<code_end>
the screen forces the OverflowBox to be exactly the same
size as the screen, and OverflowBox lets its child container
be any size it wants.
OverflowBox is similar to UnconstrainedBox;
the difference is that it won’t display any warnings
if the child doesn’t fit the space.
in this case, the container has 4000 pixels of width,
and is too big to fit in the OverflowBox,
but the OverflowBox simply shows as much as it can,
with no warnings given.
<topic_end>
<topic_start>
example 16
<code_start>
UnconstrainedBox(
  child: container(color: colors.red, width: double.infinity, height: 100),
)
<code_end>
this won’t render anything, and you’ll see an error in the console.
the UnconstrainedBox lets its child be any size it wants,
however its child is a container with infinite size.
flutter can’t render infinite sizes, so it throws an error with
the following message: BoxConstraints forces an infinite width.
<topic_end>
<topic_start>
example 17
<code_start>
UnconstrainedBox(
  child: LimitedBox(
    maxWidth: 100,
    child: container(
      color: colors.red,
      width: double.infinity,
      height: 100,
    ),
  ),
)
<code_end>
here you won’t get an error anymore,
because when the LimitedBox is given an
infinite size by the UnconstrainedBox;
it passes a maximum width of 100 down to its child.
if you swap the UnconstrainedBox for a center widget,
the LimitedBox won’t apply its limit anymore
(since its limit is only applied when it gets infinite
constraints), and the width of the container
is allowed to grow past 100.
this explains the difference between a LimitedBox
and a ConstrainedBox.
<topic_end>
<topic_start>
example 18
<code_start>
const FittedBox(
  child: Text('Some example text.'),
)
<code_end>
the screen forces the FittedBox to be exactly the same
size as the screen. the text has some natural width
(also called its intrinsic width) that depends on the
amount of text, its font size, and so on.
the FittedBox lets the text be any size it wants,
but after the text tells its size to the FittedBox,
the FittedBox scales the text until it fills all of
the available width.
<topic_end>
<topic_start>
example 19
<code_start>
const center(
  child: FittedBox(
    child: Text('Some example text.'),
  ),
)
<code_end>
but what happens if you put the FittedBox inside of a
center widget? the center lets the FittedBox
be any size it wants, up to the screen size.
the FittedBox then sizes itself to the text,
and lets the text be any size it wants.
since both FittedBox and the text have the same size,
no scaling happens.
<topic_end>
<topic_start>
example 20
<code_start>
const center(
  child: FittedBox(
    child: text(
        'this is some very very very large text that is too big to fit a regular screen in a single line.'),
  ),
)
<code_end>
however, what happens if FittedBox is inside of a center
widget, but the text is too large to fit the screen?
FittedBox tries to size itself to the text,
but it can’t be bigger than the screen.
it then assumes the screen size,
and resizes text so that it fits the screen, too.
<topic_end>
<topic_start>
example 21
<code_start>
const center(
  child: text(
      'this is some very very very large text that is too big to fit a regular screen in a single line.'),
)
<code_end>
if, however, you remove the FittedBox, the text
gets its maximum width from the screen,
and breaks the line so that it fits the screen.
<topic_end>
<topic_start>
example 22
<code_start>
FittedBox(
  child: container(
    height: 20,
    width: double.infinity,
    color: colors.red,
  ),
)
<code_end>
FittedBox can only scale a widget that is bounded
(has non-infinite width and height). otherwise,
it won’t render anything,
and you’ll see an error in the console.
<topic_end>
<topic_start>
example 23
<code_start>
row(
  children: [
    container(color: red, child: const Text('Hello!', style: big)),
    container(color: green, child: const Text('Goodbye!', style: big)),
  ],
)
<code_end>
the screen forces the row to be exactly the same size
as the screen.
just like an UnconstrainedBox, the row won’t
impose any constraints onto its children,
and instead lets them be any size they want.
the row then puts them side-by-side,
and any extra space remains empty.
<topic_end>
<topic_start>
example 24
<code_start>
row(
  children: [
    container(
      color: red,
      child: const text(
        'this is a very long text that '
        'won\'t fit the line.',
        style: big,
      ),
    ),
    container(color: green, child: const Text('Goodbye!', style: big)),
  ],
)
<code_end>
since row won’t impose any constraints onto its children,
it’s quite possible that the children might be too big to fit
the available width of the row. in this case, just like an
UnconstrainedBox, the row displays the “overflow warning”.
<topic_end>
<topic_start>
example 25
<code_start>
row(
  children: [
    expanded(
      child: center(
        child: container(
          color: red,
          child: const text(
            'this is a very long text that won\'t fit the line.',
            style: big,
          ),
        ),
      ),
    ),
    container(color: green, child: const Text('Goodbye!', style: big)),
  ],
)
<code_end>
when a row’s child is wrapped in an expanded widget,
the row won’t let this child define its own width anymore.
instead, it defines the expanded width according to the
other children, and only then the expanded widget forces
the original child to have the expanded’s width.
in other words, once you use expanded,
the original child’s width becomes irrelevant, and is ignored.
<topic_end>
<topic_start>
example 26
<code_start>
row(
  children: [
    expanded(
      child: container(
        color: red,
        child: const text(
          'this is a very long text that won\'t fit the line.',
          style: big,
        ),
      ),
    ),
    expanded(
      child: container(
        color: green,
        child: const text(
          'goodbye!',
          style: big,
        ),
      ),
    ),
  ],
)
<code_end>
if all of row’s children are wrapped in expanded widgets,
each expanded has a size proportional to its flex parameter,
and only then each expanded widget forces its child to have
the expanded’s width.
in other words, expanded ignores the preferred width of
its children.
<topic_end>
<topic_start>
example 27
<code_start>
row(
  children: [
    flexible(
      child: container(
        color: red,
        child: const text(
          'this is a very long text that won\'t fit the line.',
          style: big,
        ),
      ),
    ),
    flexible(
      child: container(
        color: green,
        child: const text(
          'goodbye!',
          style: big,
        ),
      ),
    ),
  ],
)
<code_end>
the only difference if you use flexible instead of expanded,
is that flexible lets its child have the same or smaller
width than the flexible itself, while expanded forces
its child to have the exact same width of the expanded.
but both expanded and flexible ignore their children’s width
when sizing themselves.
info note
  this means that it’s impossible to expand row children
  proportionally to their sizes. the row either uses
  the exact child’s width, or ignores it completely
  when you use expanded or flexible.
<topic_end>
<topic_start>
example 28
<code_start>
scaffold(
  body: container(
    color: blue,
    child: const column(
      children: [
        Text('Hello!'),
        Text('Goodbye!'),
      ],
    ),
  ),
)
<code_end>
the screen forces the scaffold to be exactly the same size
as the screen, so the scaffold fills the screen.
the scaffold tells the container that it can be any size it wants,
but not bigger than the screen.
info note
  when a widget tells its child that it can be smaller than a
  certain size, we say the widget supplies loose constraints
  to its child. more on that later.
<topic_end>
<topic_start>
example 29
<code_start>
scaffold(
  body: SizedBox.expand(
    child: container(
      color: blue,
      child: const column(
        children: [
          Text('Hello!'),
          Text('Goodbye!'),
        ],
      ),
    ),
  ),
)
<code_end>
if you want the scaffold’s child to be exactly the same size
as the scaffold itself, you can wrap its child with
SizedBox.expand.
<topic_end>
<topic_start>
tight vs loose constraints
it’s very common to hear that some constraint is
“tight” or “loose”, so what does that mean?
<topic_end>
<topic_start>
tight constraints
a tight constraint offers a single possibility,
an exact size. in other words, a tight constraint
has its maximum width equal to its minimum width;
and has its maximum height equal to its minimum height.
an example of this is the app widget,
which is contained by the RenderView class:
the box used by the child returned by the
application’s build function is given a constraint
that forces it to exactly fill the application’s content area
(typically, the entire screen).
another example: if you nest a bunch of boxes inside
each other at the root of your application’s render tree,
they’ll all exactly fit in each other,
forced by the box’s tight constraints.
if you go to flutter’s box.dart file and search for
the BoxConstraints constructors,
you’ll find the following:
if you revisit example 2,
the screen forces the red container to be
exactly the same size as the screen.
the screen achieves that, of course, by passing tight
constraints to the container.
<topic_end>
<topic_start>
loose constraints
a loose constraint is one that has a minimum
of zero and a maximum non-zero.
some boxes loosen the incoming constraints,
meaning the maximum is maintained but the
minimum is removed, so the widget can have
a minimum width and height both equal to zero.
ultimately, center’s purpose is to transform
the tight constraints it received from its parent
(the screen) to loose constraints for its child
(the container).
if you revisit example 3,
the center allows the red container to be smaller,
but not bigger than the screen.
<topic_end>
<topic_start>
unbounded constraints
info note
  you might be directed here if the framework
  detects a problem involving box constraints.
  the flex section below might also apply.
in certain situations,
a box’s constraint is unbounded, or infinite.
this means that either the maximum width or
the maximum height is set to double.infinity.
a box that tries to be as big as possible won’t
function usefully when given an unbounded constraint and,
in debug mode, throws an exception.
the most common case where a render box ends up
with an unbounded constraint is within a flex box
(row or column),
and within a scrollable region
(such as ListView and other ScrollView subclasses).
ListView, for example,
tries to expand to fit the space available
in its cross-direction
(perhaps it’s a vertically-scrolling block and
tries to be as wide as its parent).
if you nest a vertically scrolling ListView
inside a horizontally scrolling ListView,
the inner list tries to be as wide as possible,
which is infinitely wide,
since the outer one is scrollable in that direction.
the next section describes the error you might
encounter with unbounded constraints in a flex widget.
<topic_end>
<topic_start>
flex
a flex box (row and column) behaves
differently depending on whether its
constraint is bounded or unbounded in
its primary direction.
a flex box with a bounded constraint in its
primary direction tries to be as big as possible.
a flex box with an unbounded constraint
in its primary direction tries to fit its children
in that space. each child’s flex value must be
set to zero, meaning that you can’t use
expanded when the flex box is inside
another flex box or a scrollable;
otherwise it throws an exception.
the cross direction
(width for column or height for row),
must never be unbounded,
or it can’t reasonably align its children.
<topic_end>
<topic_start>
learning the layout rules for specific widgets
knowing the general layout rule is necessary, but it’s not enough.
each widget has a lot of freedom when applying the general rule,
so there is no way of knowing how it behaves by just reading
the widget’s name.
if you try to guess, you’ll probably guess wrong.
you can’t know exactly how a widget behaves unless
you’ve read its documentation, or studied its source-code.
the layout source-code is usually complex,
so it’s probably better to just read the documentation.
however, if you decide to study the layout source-code,
you can easily find it by using the navigating capabilities
of your IDE.
here’s an example:
find a column in your code and navigate to its
source code. to do this, use command+B (macos)
or control+B (windows/linux) in android studio or IntelliJ.
you’ll be taken to the basic.dart file.
since column extends flex, navigate to the flex
source code (also in basic.dart).
scroll down until you find a method called
createRenderObject(). as you can see,
this method returns a RenderFlex.
this is the render-object for the column.
now navigate to the source-code of RenderFlex,
which takes you to the flex.dart file.
scroll down until you find a method called
performLayout(). this is the method that does
the layout for the column.
original article by marcelo glasberg
marcelo originally published this content as
flutter: the advanced layout rule even beginners must know
on medium. we loved it and asked that he allow us to publish
in on docs.flutter.dev, to which he graciously agreed. thanks, marcelo!
you can find marcelo on GitHub and pub.dev.
also, thanks to simon lightfoot for creating the
header image at the top of the article.
info note
  to better understand how flutter implements layout
  constraints, check out the following 5-minute video:
decoding flutter: unbounded height and width
<topic_end>
<topic_start>
hot reload
flutter’s hot reload feature helps you quickly and
easily experiment, build UIs, add features, and fix bugs.
hot reload works by injecting updated source code files
into the running dart virtual machine (vm).
after the VM updates classes with the new versions of fields and functions,
the flutter framework automatically rebuilds the widget tree,
allowing you to quickly view the effects of your changes.
<topic_end>
<topic_start>
how to perform a hot reload
to hot reload a flutter app:
if you’re working in an IDE/editor that supports flutter’s IDE tools,
select save all (cmd-s/ctrl-s),
or click the hot reload button on the toolbar.
if you’re running the app at the command line using flutter run,
enter r in the terminal window.
after a successful hot reload operation,
you’ll see a message in the console similar to:
the app updates to reflect your change,
and the current state of the app is preserved.
your app continues to execute from where it was prior
to run the hot reload command.
the code updates and execution continues.
what is the difference between hot reload, hot restart,
  and full restart?
flutter web currently supports hot restart but not
  hot reload.
controls for run, run debug, hot reload, and hot restart in android studio
a code change has a visible effect only if the modified
dart code is run again after the change. specifically,
a hot reload causes all the existing widgets to rebuild.
only code involved in the rebuilding of the widgets
is automatically re-executed. the main() and initState()
functions, for example, are not run again.
<topic_end>
<topic_start>
special cases
the next sections describe specific scenarios that involve
hot reload. in some cases, small changes to the dart code
enable you to continue using hot reload for your app.
in other cases, a hot restart, or a full restart is needed.
<topic_end>
<topic_start>
an app is killed
hot reload can break when the app is killed.
for example, if the app was in the background for too long.
<topic_end>
<topic_start>
compilation errors
when a code change introduces a compilation error,
hot reload generates an error message similar to:
in this situation, simply correct the errors on the
specified lines of dart code to keep using hot reload.
<topic_end>
<topic_start>
CupertinoTabView’s builder
hot reload won’t apply changes made to
a builder of a CupertinoTabView.
for more information, see issue 43574.
<topic_end>
<topic_start>
enumerated types
hot reload doesn’t work when enumerated types are
changed to regular classes or regular classes are
changed to enumerated types.
for example:
before the change:
<code_start>
enum color {
  red,
  green,
  blue,
}
<code_end>
after the change:
<code_start>
class color {
  color(this.i, this.j);
  final int i;
  final int j;
}
<code_end>
<topic_end>
<topic_start>
generic types
hot reload won’t work when generic type declarations
are modified. for example, the following won’t work:
before the change:
<code_start>
class A<T> {
  t? i;
}
<code_end>
after the change:
<code_start>
class A<T, v> {
  t? i;
  v? v;
}
<code_end>
<topic_end>
<topic_start>
native code
if you’ve changed native code (such as kotlin, java, swift,
or Objective-C), you must perform a full restart (stop and
restart the app) to see the changes take effect.
<topic_end>
<topic_start>
previous state is combined with new code
flutter’s stateful hot reload preserves the state of your app.
this approach enables you to view the effect of the most
recent change only, without throwing away the current state.
for example, if your app requires a user to log in,
you can modify and hot reload a page several levels down in
the navigation hierarchy, without re-entering your login credentials.
state is kept, which is usually the desired behavior.
if code changes affect the state of your app (or its dependencies),
the data your app has to work with might not be fully consistent
with the data it would have if it executed from scratch.
the result might be different behavior after a hot reload
versus a hot restart.
<topic_end>
<topic_start>
recent code change is included but app state is excluded
in dart, static fields are lazily initialized.
this means that the first time you run a flutter app and a
static field is read, it’s set to whatever value its
initializer was evaluated to.
global variables and static fields are treated as state,
and are therefore not reinitialized during hot reload.
if you change initializers of global variables and static fields,
a hot restart or restart the state where the initializers are hold
is necessary to see the changes.
for example, consider the following code:
<code_start>
final sampleTable = [
  table(
    children: const [
      TableRow(
        children: [text('t1')],
      )
    ],
  ),
  table(
    children: const [
      TableRow(
        children: [text('t2')],
      )
    ],
  ),
  table(
    children: const [
      TableRow(
        children: [text('t3')],
      )
    ],
  ),
  table(
    children: const [
      TableRow(
        children: [text('t4')],
      )
    ],
  ),
];
<code_end>
after running the app, you make the following change:
<code_start>
final sampleTable = [
  table(
    children: const [
      TableRow(
        children: [text('t1')],
      )
    ],
  ),
  table(
    children: const [
      TableRow(
        children: [text('t2')],
      )
    ],
  ),
  table(
    children: const [
      TableRow(
        children: [text('t3')],
      )
    ],
  ),
  table(
    children: const [
      TableRow(
        children: [text('t10')], // modified
      )
    ],
  ),
];
<code_end>
you hot reload, but the change is not reflected.
conversely, in the following example:
<code_start>
const foo = 1;
final bar = foo;
void onClick() {
  print(foo);
  print(bar);
}
<code_end>
running the app for the first time prints 1 and 1.
then, you make the following change:
<code_start>
const foo = 2; // modified
final bar = foo;
void onClick() {
  print(foo);
  print(bar);
}
<code_end>
while changes to const field values are always hot reloaded,
the static field initializer is not rerun. conceptually,
const fields are treated like aliases instead of state.
the dart VM detects initializer changes and flags when a set
of changes needs a hot restart to take effect.
the flagging mechanism is triggered for
most of the initialization work in the above example,
but not for cases like the following:
<code_start>
final bar = foo;
<code_end>
to update foo and view the change after hot reload,
consider redefining the field as const or using a getter to
return the value, rather than using final.
for example, either of the following solutions work:
<code_start>
const foo = 1;
const bar = foo; // convert foo to a const...
void onClick() {
  print(foo);
  print(bar);
}
<code_end>
<code_start>
const foo = 1;
int get bar => foo; // ...or provide a getter.
void onClick() {
  print(foo);
  print(bar);
}
<code_end>
for more information, read about the differences
between the const and final keywords in dart.
<topic_end>
<topic_start>
recent UI change is excluded
even when a hot reload operation appears successful and generates no
exceptions, some code changes might not be visible in the refreshed UI.
this behavior is common after changes to the app’s main() or
initState() methods.
as a general rule, if the modified code is downstream of the root
widget’s build() method, then hot reload behaves as expected.
however, if the modified code won’t be re-executed as a result
of rebuilding the widget tree, then you won’t
see its effects after hot reload.
for example, consider the following code:
<code_start>
import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  widget build(BuildContext context) {
    return GestureDetector(onTap: () => print('tapped'));
  }
}
<code_end>
after running this app, change the code as follows:
<code_start>
import 'package:flutter/widgets.dart';
void main() {
  runApp(const center(child: Text('Hello', textDirection: TextDirection.ltr)));
}
<code_end>
with a hot restart, the program starts from the beginning,
executes the new version of main(),
and builds a widget tree that displays the text hello.
however, if you hot reload the app after this change,
main() and initState() are not re-executed,
and the widget tree is rebuilt with the unchanged instance
of MyApp as the root widget.
this results in no visible change after hot reload.
<topic_end>
<topic_start>
how it works
when hot reload is invoked, the host machine looks
at the edited code since the last compilation.
the following libraries are recompiled:
the source code from those libraries is compiled into
kernel files and sent to the mobile device’s dart VM.
the dart VM re-loads all libraries from the new kernel file.
so far no code is re-executed.
the hot reload mechanism then causes the flutter framework
to trigger a rebuild/re-layout/repaint of all existing
widgets and render objects.
<topic_end>
<topic_start>
FAQ
<topic_end>
<topic_start>
introduction
this page collects some common questions asked about
flutter. you might also check out the following
specialized FAQs:
<topic_end>
<topic_start>
what is flutter?
flutter is google’s portable UI toolkit for crafting beautiful,
natively compiled applications for mobile, web,
and desktop from a single codebase.
flutter works with existing code,
is used by developers and organizations around
the world, and is free and open source.
<topic_end>
<topic_start>
who is flutter for?
for users, flutter makes beautiful apps come to life.
for developers, flutter lowers the bar to entry for building apps.
it speeds app development and reduces the cost and complexity
of app production across platforms.
for designers, flutter provides a canvas for
high-end user experiences. fast company described
flutter as one of the top design ideas of the decade for
its ability to turn concepts into production code
without the compromises imposed by typical frameworks.
it also acts as a productive prototyping tool
with drag-and-drop tools like FlutterFlow
and web-based IDEs like zapp!.
for engineering managers and businesses,
flutter allows the unification of app
developers into a single mobile, web,
and desktop app team, building branded
apps for multiple platforms out of a single codebase.
flutter speeds feature development and synchronizes
release schedules across the entire customer base.
<topic_end>
<topic_start>
how much development experience do i need to use flutter?
flutter is approachable to programmers familiar with
object-oriented concepts (classes, methods, variables,
etc) and imperative programming concepts (loops,
conditionals, etc).
we have seen people with very little programming
experience learn and use flutter for prototyping
and app development.
<topic_end>
<topic_start>
what kinds of apps can i build with flutter?
flutter is designed to support mobile apps that run
on both android and iOS, as well as interactive apps
that you want to run on your web pages or on the desktop.
apps that need to deliver highly branded designs
are particularly well suited for flutter.
however, you can also create pixel-perfect experiences
that match the android and iOS design languages with flutter.
flutter’s package ecosystem supports a wide
variety of hardware (such as camera, GPS, network,
and storage) and services (such as payments, cloud
storage, authentication, and ads).
<topic_end>
<topic_start>
who makes flutter?
flutter is an open source project,
with contributions from google and other
companies and individuals.
<topic_end>
<topic_start>
who uses flutter?
developers inside and outside of google use
flutter to build beautiful natively-compiled
apps for iOS and android. to learn about some
of these apps, visit the showcase.
<topic_end>
<topic_start>
what makes flutter unique?
flutter is different than most other options
for building mobile apps because it doesn’t rely
on web browser technology nor the set of widgets
that ship with each device. instead, flutter uses
its own high-performance rendering engine to draw widgets.
in addition, flutter is different because it only
has a thin layer of C/C++ code. flutter implements
most of its system (compositing, gestures, animation,
framework, widgets, etc) in dart (a modern,
concise, object-oriented language) that developers
can easily approach read, change, replace, or remove.
this gives developers tremendous control over the system,
as well as significantly lowers the bar to approachability
for the majority of the system.
<topic_end>
<topic_start>
should i build my next production app with flutter?
flutter 1 was launched on dec 4th, 2018,
flutter 2 on march 3rd, 2021, and
flutter 3 on may 10th, 2023.
as of may 2023, over one million apps have shipped using
flutter to many hundreds of millions of devices.
check out some sample apps in the showcase.
flutter ships updates on a roughly-quarterly
cadence that improve stability and performance
and address commonly-requested user features.
<topic_end>
<topic_start>
what does flutter provide?
<topic_end>
<topic_start>
what is inside the flutter SDK?
flutter includes:
<topic_end>
<topic_start>
does flutter work with any editors or IDEs?
we provide plugins for VS code,
android studio, and IntelliJ IDEA.
see editor configuration for setup details,
and VS code and android Studio/IntelliJ
for tips on how to use the plugins.
alternatively, you can use the flutter command
from a terminal, along with one
of the many editors that support editing dart.
<topic_end>
<topic_start>
does flutter come with a framework?
yes! flutter ships with a modern react-style framework.
flutter’s framework is designed to be layered and
customizable (and optional). developers can choose to
use only parts of the framework, or even replace
upper layers of the framework entirely.
<topic_end>
<topic_start>
does flutter come with widgets?
yes! flutter ships with a set of
high-quality material design and cupertino
(ios-style) widgets, layouts, and themes.
of course, these widgets are only a starting point.
flutter is designed to make it easy to create your own
widgets, or customize the existing widgets.
<topic_end>
<topic_start>
does flutter support material design?
yes! the flutter and material teams collaborate closely,
and material is fully supported. for more information,
check out the material 2 and material 3 widgets
in the widget catalog.
<topic_end>
<topic_start>
does flutter come with a testing framework?
yes, flutter provides APIs for writing unit and
integration tests. learn more about testing with flutter.
we use our own testing capabilities to test our SDK,
and we measure our test coverage on every commit.
<topic_end>
<topic_start>
does flutter come with debugging tools?
yes, flutter comes with flutter DevTools (also
called dart DevTools). for more information, see
debugging with flutter and the flutter DevTools docs.
<topic_end>
<topic_start>
does flutter come with a dependency injection framework?
we don’t ship with an opinionated solution,
but there are a variety of packages that offer
dependency injection and service location,
such as injectable, get_it, kiwi, and riverpod.
<topic_end>
<topic_start>
technology
<topic_end>
<topic_start>
what technology is flutter built with?
flutter is built with c, c++, dart,
skia (a 2d rendering engine),
and impeller (the default rendering engine on iOS).
see this architecture diagram
for a better picture of the main components.
for a more detailed description of the layered architecture
of flutter, read the architectural overview.
<topic_end>
<topic_start>
how does flutter run my code on android?
the engine’s c and c++ code are compiled with android’s NDK.
the dart code (both the SDK’s and yours)
are ahead-of-time (aot) compiled into native, ARM, and x86
libraries. those libraries are included in a “runner”
android project, and the whole thing is built into an .apk.
when launched, the app loads the flutter library.
any rendering, input, or event handling, and so on,
is delegated to the compiled flutter and app code.
this is similar to the way many game engines work.
during debug mode, flutter uses a virtual machine (vm)
to run its code in order to enable stateful hot reload,
a feature that lets you make changes to your running code
without recompilation. you’ll see a “debug” banner in
the top right-hand corner of your app when running in this mode,
to remind you that performance is not characteristic of
the finished release app.
<topic_end>
<topic_start>
how does flutter run my code on iOS?
the engine’s c and c++ code are compiled with LLVM.
the dart code (both the SDK’s and yours)
are ahead-of-time (aot) compiled into a native, ARM library.
that library is included in a “runner” iOS project,
and the whole thing is built into an .ipa.
when launched, the app loads the flutter library.
any rendering, input or event handling, and so on,
are delegated to the compiled flutter and app code.
this is similar to the way many game engines work.
during debug mode, flutter uses a virtual machine (vm)
to run its code in order to enable stateful hot reload,
a feature that lets you make changes to your
running code without recompilation. you’ll see
a “debug” banner in the top right-hand corner of
your app when running in this mode, to remind you that
performance is not characteristic of the finished release app.
<topic_end>
<topic_start>
does flutter use my operating system’s built-in platform widgets?
no. instead, flutter provides a set of widgets
(including material design and cupertino (ios-styled) widgets),
managed and rendered by flutter’s framework and engine.
you can browse a catalog of flutter’s widgets.
we believe that the end result is higher quality apps.
if we reused the built-in platform widgets,
the quality and performance of flutter apps would be limited
by the flexibility and quality of those widgets.
in android, for example, there’s a hard-coded set
of gestures and fixed rules for disambiguating them.
in flutter, you can write your own gesture recognizer
that is a first class participant in the gesture system.
moreover, two widgets authored by different people can
coordinate to disambiguate gestures.
modern app design trends point towards designers and
users wanting more motion-rich UIs and brand-first designs.
in order to achieve that level of customized, beautiful design,
flutter is architectured to drive pixels instead
of the built-in widgets.
by using the same renderer, framework, and set of widgets,
it’s easier to publish for multiple platforms from the same
codebase, without having to do careful and costly planning
to align different feature sets and API characteristics.
by using a single language, a single framework,
and a single set of libraries for all of your code
(regardless if your UI is different for each platform or not),
we also aim to help lower app development and maintenance costs.
<topic_end>
<topic_start>
what happens when my mobile OS updates and introduces new widgets?
the flutter team watches the adoption and demand for new mobile
widgets from iOS and android, and aims to work with the community
to build support for new widgets. this work might come in the form
of lower-level framework features, new composable widgets,
or new widget implementations.
flutter’s layered architecture is designed to support numerous
widget libraries, and we encourage and support the community in
building and maintaining widget libraries.
<topic_end>
<topic_start>
what happens when my mobile OS updates and introduces new platform capabilities?
flutter’s interop and plugin system is designed to allow
developers to access new mobile OS features and capabilities
immediately. developers don’t have to wait for the flutter team
to expose the new mobile OS capability.
<topic_end>
<topic_start>
what operating systems can i use to build a flutter app?
flutter supports development using linux, macOS, ChromeOS,
and windows.
<topic_end>
<topic_start>
what language is flutter written in?
dart, a fast-growing modern language optimized
for client apps. the underlying graphics framework
and the dart virtual machine are implemented in C/C++.
<topic_end>
<topic_start>
why did flutter choose to use dart?
during the initial development phase,
the flutter team looked at a lot of
languages and runtimes, and ultimately
adopted dart for the framework and widgets.
flutter used four primary dimensions for evaluation,
and considered the needs of framework authors,
developers, and end users. we found many languages
met some requirements, but dart scored highly on
all of our evaluation dimensions and met all our
requirements and criteria.
dart runtimes and compilers support the combination of
two critical features for flutter: a JIT-based fast
development cycle that allows for shape changing and
stateful hot reloads in a language with types,
plus an Ahead-of-Time compiler that emits efficient
ARM code for fast startup and predictable performance of
production deployments.
in addition, we have the opportunity to work closely
with the dart community, which is actively investing
resources in improving dart for use in flutter. for
example, when we adopted dart,
the language didn’t have an ahead-of-time
toolchain for producing native binaries,
which is instrumental in achieving predictable,
high performance, but now the language does because the dart team
built it for flutter. similarly, the dart VM has
previously been optimized for throughput but the
team is now optimizing the VM for latency, which is more
important for flutter’s workload.
dart scores highly for us on the following primary criteria:
<topic_end>
<topic_start>
can flutter run any dart code?
flutter can run dart code that doesn’t directly or
transitively import dart:mirrors or dart:html.
<topic_end>
<topic_start>
how big is the flutter engine?
in march 2021, we measured the download size of a
minimal flutter app (no material components,
just a single center widget, built with flutter build
apk --split-per-abi), bundled and compressed as a release APK,
to be approximately 4.3 MB for ARM32, and 4.8 MB for ARM64.
on ARM32, the core engine is approximately 3.4 MB
(compressed), the framework + app code is approximately
765 KB (compressed), the LICENSE file is 58 KB
(compressed), and necessary java code (classes.dex)
is 120 KB (compressed).
in ARM64, the core engine is approximately 4.0 MB 
(compressed), the framework + app code is approximately
659 KB (compressed), the LICENSE file is 58 KB
(compressed), and necessary java code (classes.dex)
is 120 KB (compressed).
these numbers were measured using apkanalyzer,
which is also built into android studio.
on iOS, a release IPA of the same app has a download
size of 10.9 MB on an iPhone x, as reported by apple’s
app store connect. the IPA is larger than the APK mainly
because apple encrypts binaries within the IPA, making the
compression less efficient (see the
iOS app store specific considerations
section of apple’s QA1795).
info note
  the release engine binary used to include LLVM IR (bitcode).
  however, apple deprecated bitcode in xcode 14 and removed support,
  so it has been removed from the flutter 3.7 release.
of course, we recommend that you measure your own app.
to do that, see measuring your app’s size.
<topic_end>
<topic_start>
how does flutter define a pixel?
flutter uses logical pixels,
and often refers to them merely as “pixels”.
flutter’s devicePixelRatio expresses the ratio
between physical pixels and logical CSS pixels.
<topic_end>
<topic_start>
capabilities
<topic_end>
<topic_start>
what kind of app performance can i expect?
you can expect excellent performance. flutter is
designed to help developers easily achieve a constant 60fps.
flutter apps run using natively compiled code—no
interpreters are involved.
this means that flutter apps start quickly.
<topic_end>
<topic_start>
what kind of developer cycles can i expect? how long between edit and refresh?
flutter implements a hot reload developer cycle. you can expect
sub-second reload times, on a device or an emulator/simulator.
flutter’s hot reload is stateful so the app state
is retained after a reload. this means you can quickly iterate
on a screen deeply nested in your app, without starting
from the home screen after every reload.
<topic_end>
<topic_start>
how is hot reload different from hot restart?
hot reload works by injecting updated source code files
into the running dart VM (virtual machine). this doesn’t
only add new classes, but also adds methods and fields
to existing classes, and changes existing functions.
hot restart resets the state to the app’s initial state.
for more information, see hot reload.
<topic_end>
<topic_start>
where can i deploy my flutter app?
you can compile and deploy your flutter app to iOS, android,
web, and desktop.
<topic_end>
<topic_start>
what devices and OS versions does flutter run on?
we support and test running flutter on a variety
of low-end to high-end platforms.  for a detailed list
of the platforms on which we test, see 
the list of supported platforms.
flutter supports building ahead-of-time (aot) compiled libraries
for x86_64, armeabi-v7a, and arm64-v8a.
apps built for ARMv7 or ARM64 run fine (using ARM emulation)
on many x86 android devices.
we support developing flutter apps on a range of platforms.
see the system requirements listed under each
development operating system.
<topic_end>
<topic_start>
does flutter run on the web?
yes, web support is available in the stable channel.
for more details, check out the web instructions.
<topic_end>
<topic_start>
can i use flutter to build desktop apps?
yes, desktop support is in stable for windows,
macOS, and linux.
<topic_end>
<topic_start>
can i use flutter inside of my existing native app?
yes, learn more in the add-to-app section of our website.
<topic_end>
<topic_start>
can i access platform services and APIs like sensors and local storage?
yes. flutter gives developers out-of-the-box access to some
platform-specific services and APIs from the operating system.
however, we want to avoid the “lowest common denominator” problem
with most cross-platform APIs, so we don’t intend to build
cross-platform APIs for all native services and APIs.
a number of platform services and APIs have
ready-made packages available on pub.dev.
using an existing package is easy.
finally, we encourage developers to use flutter’s
asynchronous message passing system to create your
own integrations with platform and third-party APIs.
developers can expose as much or as little of the
platform APIs as they need, and build layers of
abstractions that are a best fit for their project.
<topic_end>
<topic_start>
can i extend and customize the bundled widgets?
absolutely. flutter’s widget system was designed
to be easily customizable.
rather than having each widget provide a large number of parameters,
flutter embraces composition. widgets are built out of smaller
widgets that you can reuse and combine in novel ways to make
custom widgets. for example, rather than subclassing a generic
button widget, ElevatedButton combines a material widget with a
GestureDetector widget. the material widget provides the visual
design and the GestureDetector widget provides the
interaction design.
to create a button with a custom visual design, you can combine
widgets that implement your visual design with a GestureDetector,
which provides the interaction design. for example,
CupertinoButton follows this approach and combines a
GestureDetector with several other widgets that implement its
visual design.
composition gives you maximum control over the visual and
interaction design of your widgets while also allowing a
large amount of code reuse. in the framework, we’ve decomposed
complex widgets to pieces that separately implement
the visual, interaction, and motion design. you can remix
these widgets however you like to make your own custom
widgets that have full range of expression.
<topic_end>
<topic_start>
why would i want to share layout code across iOS and android?
you can choose to implement different app layouts for
iOS and android. developers are free to check the mobile OS
at runtime and render different layouts,
though we find this practice to be rare.
more and more, we see mobile app layouts and designs evolving
to be more brand-driven and unified across platforms.
this implies a strong motivation to share layout and UI
code across iOS and android.
the brand identity and customization of the app’s
aesthetic design is now becoming more important than
strictly adhering to traditional platform aesthetics.
for example, app designs often require custom fonts, colors,
shapes, motion, and more in order to clearly convey their
brand identity.
we also see common layout patterns deployed across
iOS and android. for example, the “bottom nav bar”
pattern can now be naturally found across iOS and android.
there seems to be a convergence of design ideas
across mobile platforms.
<topic_end>
<topic_start>
can i interop with my mobile platform’s default programming language?
yes, flutter supports calling into the platform,
including integrating with java or kotlin code on android,
and ObjectiveC or swift code on iOS.
this is enabled by a flexible message passing style
where a flutter app might send and receive messages
to the mobile platform using a BasicMessageChannel.
learn more about accessing platform and third-party services
in flutter with platform channels.
here is an example project that shows how to use a
platform channel to access battery state information on
iOS and android.
<topic_end>
<topic_start>
does flutter come with a reflection / mirrors system?
no. dart includes dart:mirrors,
which provides type reflection. but since
flutter apps are pre-compiled for production,
and binary size is always a concern with mobile apps,
this library is unavailable for flutter apps.
using static analysis we can strip out anything that isn’t
used (“tree shaking”). if you import a huge dart library
but only use a self-contained two-line method,
then you only pay the cost of the two-line method,
even if that dart library itself imports dozens and
dozens of other libraries. this guarantee is only secure
if dart can identify the code path at compile time.
to date, we’ve found other approaches for specific needs
that offer a better trade-off, such as code generation.
<topic_end>
<topic_start>
how do i do international­ization (i18n), localization (l10n), and accessibility (a11y) in flutter?
learn more about i18n and l10n in the
internationalization tutorial.
learn more about a11y in the
accessibility documentation.
<topic_end>
<topic_start>
how do i write parallel and/or concurrent apps for flutter?
flutter supports isolates. isolates are separate heaps in
flutter’s VM, and they are able to run in parallel
(usually implemented as separate threads). isolates
communicate by sending and receiving asynchronous messages.
check out an example of using isolates with flutter.
<topic_end>
<topic_start>
can i run dart code in the background of a flutter app?
yes, you can run dart code in a background process on both
iOS and android. for more information, see the free medium article
executing dart in the background with flutter plugins and geofencing.
<topic_end>
<topic_start>
can i use JSON/XML/protobuffers (and so on) with flutter?
absolutely. there are libraries on
pub.dev for JSON, XML, protobufs,
and many other utilities and formats.
for a detailed writeup on using JSON with flutter,
check out the JSON tutorial.
<topic_end>
<topic_start>
can i build 3d (opengl) apps with flutter?
today we don’t support 3d using OpenGL ES or similar.
we have long-term plans to expose an optimized 3d API,
but right now we’re focused on 2d.
<topic_end>
<topic_start>
why is my APK or IPA so big?
usually, assets including images, sound files, fonts, and so on,
are the bulk of an APK or IPA. various tools in the
android and iOS ecosystems can help you understand
what’s inside of your APK or IPA.
also, be sure to create a release build
of your APK or IPA with the flutter tools.
a release build is usually much smaller
than a debug build.
learn more about creating a
release build of your android app,
and creating a release build of your iOS app.
also, check out measuring your app’s size.
<topic_end>
<topic_start>
do flutter apps run on chromebooks?
we have seen flutter apps run on some chromebooks.
we are tracking issues related to running flutter on
chromebooks.
<topic_end>
<topic_start>
is flutter ABI compatible?
flutter and dart don’t offer application binary interface (abi)
compatibility. offering ABI compatibility is not a current
goal for flutter or dart.
<topic_end>
<topic_start>
framework
<topic_end>
<topic_start>
why is the build() method on state, rather than StatefulWidget?
putting a widget build(BuildContext context) method on state
rather putting a widget build(BuildContext context, state state)
method on StatefulWidget gives developers more flexibility when
subclassing StatefulWidget. you can read a more
detailed discussion on the API docs for state.build.
<topic_end>
<topic_start>
where is flutter’s markup language? why doesn’t flutter have a markup syntax?
flutter UIs are built with an imperative, object-oriented
language (dart, the same language used to build flutter’s
framework). flutter doesn’t ship with a declarative markup.
we found that UIs dynamically built with code allow for
more flexibility. for example, we have found it difficult
for a rigid markup system to express and produce
customized widgets with bespoke behaviors.
we have also found that our “code-first” approach better allows
for features like hot reload and dynamic environment adaptations.
it’s possible to create a custom language that is then
converted to widgets on the fly. because build methods
are “just code”, they can do anything,
including interpreting markup and turning it into widgets.
<topic_end>
<topic_start>
my app has a debug banner/ribbon in the upper right. why am i seeing that?
by default, the flutter run command uses the
debug build configuration.
the debug configuration runs your dart code in a VM (virtual machine)
enabling a fast development cycle with hot reload
(release builds are compiled using the standard android
and iOS toolchains).
the debug configuration also checks all asserts, which helps
you catch errors early during development, but imposes a
runtime cost. the “debug” banner indicates that these checks
are enabled. you can run your app without these checks by
using either the --profile or --release flag to flutter run.
if your IDE uses the flutter plugin,
you can launch the app in profile or release mode.
for VS code, use the run > start debugging
or run > run without debugging menu entries.
for IntelliJ, use the menu entries
run > flutter run in profile mode or release mode.
<topic_end>
<topic_start>
what programming paradigm does flutter’s framework use?
flutter is a multi-paradigm programming environment.
many programming techniques developed over the past few decades
are used in flutter. we use each one where we believe
the strengths of the technique make it particularly well-suited.
in no particular order:
<topic_end>
<topic_start>
project
<topic_end>
<topic_start>
where can i get support?
if you think you’ve encountered a bug, file it in our
issue tracker. you might also use
stack overflow for “howto” type questions.
for discussions, join our mailing list at
flutter-dev@googlegroups.com or seek us out on discord.
for more information, see our community page.
<topic_end>
<topic_start>
how do i get involved?
flutter is open source, and we encourage you to contribute.
you can start by simply filing issues for feature requests
and bugs in our issue tracker.
we recommend that you join our mailing list at
flutter-dev@googlegroups.com and let us know how you’re
using flutter and what you’d like to do with it.
if you’re interested in contributing code, you can start
by reading our contributing guide, and check out our
list of easy starter issues.
finally, you can connect with helpful flutter communities.
for more information, see the community page.
<topic_end>
<topic_start>
is flutter open source?
yes, flutter is open source technology.
you can find the project on GitHub.
<topic_end>
<topic_start>
which software license(s) apply to flutter and its dependencies?
flutter includes two components: an engine that ships as a
dynamically linked binary, and the dart framework as a separate
binary that the engine loads. the engine uses multiple software
components with many dependencies; view the complete list
in its license file.
the framework is entirely self-contained and requires
only one license.
in addition, any dart packages you use might have their
own license requirements.
<topic_end>
<topic_start>
how can i determine the licenses my flutter application needs to show?
there’s an API to find the list of licenses you need to show:
if your application has a drawer, add an
AboutListTile.
if your application doesn’t have a drawer but does use the
material components library, call either showAboutDialog
or showLicensePage.
for a more custom approach, you can get the raw licenses from the
LicenseRegistry.
<topic_end>
<topic_start>
who works on flutter?
we all do! flutter is an open source project.
currently, the bulk of the development is done
by engineers at google. if you’re excited about flutter,
we encourage you to join the community and
contribute to flutter!
<topic_end>
<topic_start>
what are flutter’s guiding principles?
we believe the following:
we are focused on three things:
<topic_end>
<topic_start>
will apple reject my flutter app?
we can’t speak for apple, but their app store contains
many apps built with framework technologies such as flutter.
indeed, flutter uses the same fundamental architectural
model as unity, the engine that powers many of the
most popular games on the apple store.
apple has frequently featured well-designed apps
that are built with flutter,
including hamilton and reflectly.
as with any app submitted to the apple store,
apps built with flutter should follow apple’s
guidelines for app store submission.
<topic_end>
<topic_start>
books about flutter
here’s a collection of books about flutter,
in alphabetical order.
if you find another one that we should add,
file an issue and (feel free to)
submit a PR (sample) to add it yourself.
also, check the flutter version that the book
was written under. anything published before
flutter 3.10/dart 3 (may 2023),
won’t reflect the latest version of dart and
might not include null safety;
anything published before flutter 3.16 (november 2023)
won’t reflect that material 3 is now
flutter’s default theme.
see the what’s new
page to view flutter’s latest release.
  the following sections have more information about each book.
<topic_end>
<topic_start>
beginning app development with flutter
by rap payne
easy to understand starter book. currently the best-selling and highest rated flutter book on amazon.
<topic_end>
<topic_start>
beginning flutter: a hands on guide to app development
by marco l. napoli
build your first app in flutter - no experience necessary.
<topic_end>
<topic_start>
flutter apps development: build Cross-Platform flutter apps with trust
by mouaz m. Al-Shahmeh
this book teaches what you need to know to build your first flutter app. you will learn about the basics of flutter (widgets, state management, and navigation), as well as how to build a variety of different app types (games, social media apps, and e-commerce apps). by the end of this book, you will be able to build beautiful, high-performance mobile apps using flutter.
<topic_end>
<topic_start>
flutter apprentice
by michael katz, kevin david moore, vincent ngo, and vincenzo guzzi
build for both iOS and android with flutter! with flutter and flutter apprentice, you can achieve the dream of building fast applications, faster.
<topic_end>
<topic_start>
flutter complete reference 2.0
by alberto miola
the book’s first eight chapters are dedicated to dart 3.0 and all its features. over 500 pages are about the flutter framework: widgets basics, state management, animations, navigation, and more.
<topic_end>
<topic_start>
flutter: développez vos applications mobiles multiplateformes avec dart
by julien trillard
ce livre sur flutter s’adresse aux développeurs, initiés comme plus aguerris, qui souhaitent disposer des connaissances nécessaires pour créer de a à z des applications mobiles multiplateformes avec le framework de google
<topic_end>
<topic_start>
flutter for beginners
by thomas bailey and alessandro biessek
an introductory guide to building cross-platform mobile applications with flutter 2.5 and dart.
<topic_end>
<topic_start>
flutter in action
by eric windmill
flutter in action teaches you to build professional-quality mobile applications using the flutter SDK and the dart programming language.
<topic_end>
<topic_start>
flutter libraries we love
by codemagic
“flutter libraries we love” focuses on 11 different categories of flutter libraries. each category lists available libraries as well as a highlighted library that is covered in more detail – including pros and cons, developer’s perspective, and real-life code examples. the code snippets of all 11 highlighted libraries support flutter 2 with sound null safety.
<topic_end>
<topic_start>
flutter succinctly
by ed freitas
app UI in flutter-from zero to hero.
<topic_end>
<topic_start>
google flutter mobile development quick start guide
by prajyot mainkar and salvatore girodano
a fast-paced guide to get you started with cross-platform mobile application development with google flutter
<topic_end>
<topic_start>
learn google flutter fast
by mark clow
learn google flutter by example. over 65 example mini-apps.
<topic_end>
<topic_start>
managing state in flutter pragmatically
by waleed arshad
explore popular state management techniques in flutter.
<topic_end>
<topic_start>
practical flutter
by frank zammetti
improve your mobile development with google’s latest open source SDK.
<topic_end>
<topic_start>
pragmatic flutter
by priyanka tyagi
building Cross-Platform mobile apps for android, iOS, web & desktop
<topic_end>
<topic_start>
programming flutter
by carmine zaccagnino
native, Cross-Platform apps the easy way. doesn’t require previous dart knowledge.
<topic_end>
<topic_start>
flutter architectures
by atul vashisht
write code with a good architecture
<topic_end>
<topic_start>
videos
these flutter videos, produced both internally
at google and by the flutter community,
might help if you are a visual learner.
note that many people make flutter videos.
this page shows some that we like,
but there are many others, including
some in different languages.
<topic_end>
<topic_start>
series
<topic_end>
<topic_start>
flutter forward
even if you couldn’t make it to nairobi for the in-person
event, you can enjoy the content created for flutter forward!
flutter forward livestream
flutter forward playlist
<topic_end>
<topic_start>
get ready for flutter forward
flutter forward is happening on jan 25th, in nairobi, kenya.
before the event, the flutter team provided 17 days of flutter
featuring new content and activities leading up to the event.
this playlist contains these and other pre-event videos relating to
flutter forward.
17 days of flutter!
get ready for flutter forward playlist
<topic_end>
<topic_start>
learning to fly
info note
  season 2 of learning to fly has been released as part
  of the 17 days of flutter, leading up to the 3.7
  release! season 2 centers around creating a platform
  game, DoodleDash, using the flame engine.
follow along with khanh’s journey as she learns flutter.
from ideation down to the moments of confusion,
learn alongside her as she asks important questions like:
“what is the best way to build out a theme? how to approach using fonts?”
and more!
building my first flutter app | learning to fly
learning to fly playlist
here are some of the series offered on the
flutterdev YouTube channel.
for more information, check out all
of the flutter channel’s playlists.
<topic_end>
<topic_start>
decoding flutter
this series focuses on tips, tricks, best practices,
and general advice on getting the most out of flutter.
in the comments section for this series,
you can submit suggestions future episodes.
introducing decoding flutter
decoding flutter playlist
<topic_end>
<topic_start>
flutter widget of the week
do you have 60 seconds?
each one-minute video highlights a flutter widget.
introducing widget of the week
flutter widget of the week playlist
<topic_end>
<topic_start>
flutter package of the week
if you have another minute (or two),
each of these videos highlights a flutter package.
flutter_slidable package
flutter package of the week playlist
<topic_end>
<topic_start>
the boring flutter show
this series features flutter programmers coding,
unscripted and in real time. mistakes, solutions
(some of them correct), and snazzy intro music included.
introducing the boring flutter show
the boring flutter show playlist
<topic_end>
<topic_start>
flutter at google I/O 2022
google I/O 2022 is over, but you can still catch
the great flutter content!
flutter at google I/O playlist
<topic_end>
<topic_start>
flutter engage 2021
flutter engage 2021 was a day-long event that
officially launched flutter 2.
check out the flutter engage 2021 highlights reel.
watch recordings of the sessions on the flutter YouTube channel.
keynote
flutter engage 2021 playlist
watch recordings of the sessions offered by the flutter community.
flutter engage community talks playlist
<topic_end>
<topic_start>
flutter in focus
five-to-ten minute tutorials (more or less) on using flutter.
introducing flutter in focus
flutter in focus playlist
<topic_end>
<topic_start>
conference talks
here are a some flutter talks given at various conferences.
conference talks playlist
<topic_end>
<topic_start>
flutter developer stories
videos showing how various customers, such as abbey road studio, hamilton,
and alibaba, have used flutter to create beautiful compelling apps with
millions of downloads.
flutter developer stories playlist
<topic_end>
<topic_start>
online courses
learn how to build flutter apps with these video courses.
before signing up for a course, verify that it includes
up-to-date information, such as null-safe dart code.
these courses are listed alphabetically.
to include your course, submit a PR:
<topic_end>
<topic_start>
bootstrap into dart
new to the dart language?
we compiled our favorite resources to
help you quickly learn dart.
many people have reported that
dart is easy and fun to learn.
we hope these resources make dart easy for
you to learn, too.
want to learn more and perhaps contribute?
check out the dart community.
<topic_end>
<topic_start>
create useful bug reports
the instructions in this document detail the current steps
required to provide the most actionable bug reports for
crashes and other bad behavior. each step is optional but
will greatly improve how quickly issues are diagnosed and addressed.
we appreciate your effort in sending us as much feedback as possible.
<topic_end>
<topic_start>
create an issue on GitHub
<topic_end>
<topic_start>
provide a minimal reproducible code sample
create a minimal flutter app that shows the problem you are facing,
and paste it into the GitHub issue.
to create it you can use flutter create bug command and update
the main.dart file.
alternatively, you can use DartPad, which is capable
of creating and running small flutter apps.
if your problem goes out of what can be placed in a single file, for example
you have a problem with native channels, you can upload the full code of
the reproduction into a separate repository and link it.
<topic_end>
<topic_start>
provide some flutter diagnostics
<topic_end>
<topic_start>
run the command in verbose mode
follow these steps only if your issue is related to the
flutter tool.
<topic_end>
<topic_start>
provide the most recent logs
<topic_end>
<topic_start>
provide the crash report
<topic_end>
<topic_start>
issues: flutter/flutter
have a question about this project? sign up for a free GitHub account to open an issue and contact its maintainers and the community.
by clicking “sign up for GitHub”, you agree to our terms of service and
  privacy statement. we’ll occasionally send you account related emails.
    already on GitHub?
    sign in
    to your account
<topic_end>
<topic_start>
issues list
<topic_end>
<topic_start>
who is dash?
this is dash:
dash is the mascot for the dart language and the flutter framework.
info note
  you can now make your own digital dash using
  dashatar, a flutter app for web and mobile!
<topic_end>
<topic_start>
how did it all start?
as soon as shams zakhour started working as a
dart writer at google in december 2013,
she started advocating for a dart mascot.
after documenting java for 14 years, she
had observed how beloved the java mascot,
duke, had become,
and she wanted something similar for dart.
but the idea didn’t gain momentum until 2017,
when one of the flutter engineers, nina chen,
suggested it on an internal mailing list.
the flutter VP at the time, joshy joseph,
approved the idea and asked the
organizer for the 2018 dart conference,
linda rasmussen, to make it happen.
once shams heard about these plans,
she rushed to linda and asked to own and drive
the project to produce the plushies for the conference.
linda had already elicited some design sketches,
which she handed off.
starting with the sketches, shams located a vendor
who could work within an aggressive deadline
(competing with lunar new year),
and started the process of creating
the specs for the plushy.
that’s right, dash was originally a
dart mascot, not a flutter mascot.
here are some early mockups and one of the first prototypes:
the first prototype had uneven eyes
<topic_end>
<topic_start>
why a hummingbird?
early on, a hummingbird image was created for the dart team
to use for presentations and the web.
the hummingbird represents that dart is a speedy language.
however, hummingbirds are pointed and angular
and we wanted a cuddly plushy, so we chose a round
hummingbird.
shams specified which color would go where,
the tail shape, the tuft of hair, the eyes…all the
little details. the vendor sent the specs to two
manufacturers who returned the prototypes some weeks later.
introducing dash at the january 2018 dart conference.
while the manufacturing process was proceeding,
shams chose a name for the plushy: dash,
because it was an early code name for the
dart project, it was gender neutral,
and it seemed appropriate for a hummingbird.
many boxes of dash plushies arrived in
southern california just in time for the conference.
they were eagerly adopted by dart and flutter enthusiasts.
the people have spoken, so dash is now the mascot for flutter and dart.
dash 1.0
conference swag
since the creation of dash 1.0, we’ve made two more versions.
marketing slightly changed the dart and flutter color scheme after
dash 1.0 was created, so dash 2.0 reflects the updated scheme
(which removed the green color).
dash 2.1 is a smaller size and has a few more color
tweaks. the smaller size is easier to ship,
and fits better in a claw machine!
dash 2.0 and 2.1
<topic_end>
<topic_start>
dash facts
we also have Mega-Dash, a life-sized mascot
who is currently resting in a google office.
Mega-Dash made her
first appearance at the flutter interact event
in brooklyn, new york, on december 11, 2019.
we also have a dash puppet that shams made from
one of the first plushies.
a number of our YouTube videos feature the dash puppet,
voiced by emily fortuna, one of the early (and much loved)
flutter developer advocates.
<topic_end>
<topic_start>
this is an alphabetical list of nearly every widget that is bundled with flutter.
AbsorbPointer
a widget that absorbs pointers during hit testing. when absorbing is true, this widget prevents its subtree from receiving pointer events by terminating hit testing...
AlertDialog
hovering containers that prompt app users to provide more data or make a decision.
align
a widget that aligns its child within itself and optionally sizes itself based on the child's size.
AnimatedAlign
animated transition that moves the child's position over a given duration whenever the given alignment changes.
AnimatedBuilder
a general-purpose widget for building animations. AnimatedBuilder is useful for more complex widgets that wish to include animation as part of a larger build function....
AnimatedContainer
a container that gradually changes its values over a period of time.
AnimatedCrossFade
a widget that cross-fades between two given children and animates itself between their sizes.
AnimatedDefaultTextStyle
animated version of DefaultTextStyle which automatically transitions the default text style (the text style to apply to descendant text widgets without explicit style) over a...
AnimatedList
a scrolling container that animates items when they are inserted or removed.
AnimatedListState
the state for a scrolling container that animates items when they are inserted or removed.
AnimatedModalBarrier
a widget that prevents the user from interacting with widgets behind itself.
AnimatedOpacity
animated version of opacity which automatically transitions the child's opacity over a given duration whenever the given opacity changes.
AnimatedPhysicalModel
animated version of PhysicalModel.
AnimatedPositioned
animated version of positioned which automatically transitions the child's position over a given duration whenever the given position changes.
AnimatedSize
animated widget that automatically transitions its size over a given duration whenever the given child's size changes.
AnimatedWidget
a widget that rebuilds when the given listenable changes value.
AppBar
container that displays content and actions at the top of a screen.
AspectRatio
a widget that attempts to size the child to a specific aspect ratio.
AssetBundle
asset bundles contain resources, such as images and strings, that can be used by an application. access to these resources is asynchronous so that they...
autocomplete
a widget for helping the user make a selection by entering some text and choosing from among a list of options.
BackdropFilter
a widget that applies a filter to the existing painted content and then paints a child. this effect is relatively expensive, especially if the filter...
badge
icon-like block that conveys dynamic content such as counts or status. it can include labels or numbers.
baseline
container that positions its child according to the child's baseline.
bottom app bar
container that displays navigation and key actions at the bottom of a screen.
bottom sheet
containers that anchor supplementary content to the bottom of the screen.
BottomNavigationBar
container that includes tools to explore and switch between top-level views in a single tap.
BottomSheet
bottom sheets slide up from the bottom of the screen to reveal more content. you can call showBottomSheet() to implement a persistent bottom sheet or...
card
container for short, related pieces of content displayed in a box with rounded corners and a drop shadow.
center
alignment block that centers its child within itself.
checkbox
form control that app users can set or clear to select one or more options from a set.
chip
small blocks that simplify entering information, making selections, filtering content, or triggering actions.
CircularProgressIndicator
circular progress indicator that spins to indicate a busy application.
ClipOval
a widget that clips its child using an oval.
ClipPath
a widget that clips its child using a path.
ClipRect
a widget that clips its child using a rectangle.
column
layout a list of child widgets in the vertical direction.
common buttons
clickable blocks that start an action, such as sending an email, sharing a document, or liking a comment.
ConstrainedBox
a widget that imposes additional constraints on its child.
container
a convenience widget that combines common painting, positioning, and sizing widgets.
CupertinoActionSheet
an iOS-style modal bottom action sheet to choose an option among many.
CupertinoActivityIndicator
an iOS-style activity indicator. displays a circular 'spinner'.
CupertinoAlertDialog
an iOS-style alert dialog.
CupertinoButton
an iOS-style button.
CupertinoContextMenu
an iOS-style full-screen modal route that opens when the child is long-pressed. used to display relevant actions for your content.
CupertinoDatePicker
an iOS-style date or date and time picker.
CupertinoDialogAction
a button typically used in a CupertinoAlertDialog.
CupertinoFullscreenDialogTransition
an iOS-style transition used for summoning fullscreen dialogs.
CupertinoListSection
container that uses the iOS style to display a scrollable view.
CupertinoListTile
a block that uses the iOS style to create a row in a list.
CupertinoNavigationBar
container at the top of a screen that uses the iOS style. many developers use this with `cupertinopagescaffold`.
CupertinoPageScaffold
basic iOS style page layout structure. positions a navigation bar and content on a background.
CupertinoPageTransition
provides an iOS-style page transition animation.
CupertinoPicker
an iOS-style picker control. used to select an item in a short list.
CupertinoPopupSurface
rounded rectangle surface that looks like an iOS popup surface, such as an alert dialog or action sheet.
CupertinoScrollbar
an iOS-style scrollbar that indicates which portion of a scrollable widget is currently visible.
CupertinoSearchTextField
an iOS-style search field.
CupertinoSegmentedControl
an iOS-style segmented control. used to select mutually exclusive options in a horizontal list.
CupertinoSlider
used to select from a range of values.
CupertinoSlidingSegmentedControl
an iOS-13-style segmented control. used to select mutually exclusive options in a horizontal list.
CupertinoSliverNavigationBar
an iOS-styled navigation bar with iOS-11-style large titles using slivers.
CupertinoSwitch
an iOS-style switch. used to toggle the on/off state of a single setting.
CupertinoTabBar
an iOS-style bottom tab bar. typically used with CupertinoTabScaffold.
CupertinoTabScaffold
tabbed iOS app structure. positions a tab bar on top of tabs of content.
CupertinoTabView
root content of a tab that supports parallel navigation between tabs. typically used with CupertinoTabScaffold.
CupertinoTextField
an iOS-style text field.
CupertinoTimerPicker
an iOS-style countdown timer picker.
CustomMultiChildLayout
a widget that uses a delegate to size and position multiple children.
CustomPaint
a widget that provides a canvas on which to draw during the paint phase.
CustomScrollView
a ScrollView that creates custom scroll effects using slivers.
CustomSingleChildLayout
a widget that defers the layout of its single child to a delegate.
DataTable
data tables display sets of raw data. they usually appear in desktop enterprise products. the DataTable widget implements this component.
DatePicker
calendar interface used to select a date or a range of dates.
DecoratedBox
a widget that paints a decoration either before or after its child paints.
DecoratedBoxTransition
animated version of a DecoratedBox that animates the different properties of its decoration.
DefaultTextStyle
the text style to apply to descendant text widgets without explicit style.
dismissible
a widget that can be dismissed by dragging in the indicated direction. dragging or flinging this widget in the DismissDirection causes the child to slide...
divider
thin line that groups content in lists and containers.
DragTarget
a widget that receives data when a draggable widget is dropped. when a draggable is dragged on top of a drag target, the drag target...
draggable
a widget that can be dragged from to a DragTarget. when a draggable widget recognizes the start of a drag gesture, it displays a feedback...
DraggableScrollableSheet
a container for a scrollable that responds to drag gestures by resizing the scrollable until a limit is reached, and then scrolling.
drawer
a material design panel that slides in horizontally from the edge of a scaffold to show navigation links in an application.
DropdownButton
shows the currently selected item and an arrow that opens a menu for selecting another item.
ElevatedButton
a material design elevated button. a filled button whose material elevates when pressed.
ExcludeSemantics
a widget that drops all the semantics of its descendants. this can be used to hide subwidgets that would otherwise be reported but that would...
expanded
a widget that expands a child of a row, column, or flex.
ExpansionPanel
expansion panels contain creation flows and allow lightweight editing of an element. the ExpansionPanel widget implements this component.
extended FloatingActionButton
clickable block that triggers an action. these wider blocks can fit a text label and provide a larger target area.
FadeTransition
animates the opacity of a widget.
FittedBox
scales and positions its child within itself according to fit.
FloatingActionButton
clickable block containing an icon that keeps a key action always in reach.
flow
a widget that implements the flow layout algorithm.
FlutterLogo
the flutter logo, in widget form. this widget respects the IconTheme.
form
an optional container for grouping together multiple form field widgets (e.g. TextField widgets).
FormField
a single form field. this widget maintains the current state of the form field, so that updates and validation errors are visually reflected in the...
FractionalTranslation
a widget that applies a translation expressed as a fraction of the box's size before painting its child.
FractionallySizedBox
a widget that sizes its child to a fraction of the total available space. for more details about the layout algorithm, see RenderFractionallySizedOverflowBox.
FutureBuilder
widget that builds itself based on the latest snapshot of interaction with a future.
GestureDetector
a widget that detects gestures. attempts to recognize gestures that correspond to its non-null callbacks. if this widget has a child, it defers to that...
GridView
a grid list consists of a repeated pattern of cells arrayed in a vertical and horizontal layout. the GridView widget implements this component.
hero
a widget that marks its child as being a candidate for hero animations.
icon
a material design icon.
IconButton
clickable icons to prompt app users to take supplementary actions.
IgnorePointer
a widget that is invisible during hit testing. when ignoring is true, this widget (and its subtree) is invisible to hit testing. it still consumes...
image
a widget that displays an image.
ImplicitlyAnimatedWidget
an abstract class for building widgets that animate changes to their properties.
IndexedStack
a stack that shows a single child from a list of children.
InteractiveViewer
a widget that enables pan and zoom interactions with its child.
IntrinsicHeight
a widget that sizes its child to the child's intrinsic height.
IntrinsicWidth
a widget that sizes its child to the child's intrinsic width.
KeyboardListener
a widget that calls a callback whenever the user presses or releases a key on a keyboard.
LayoutBuilder
builds a widget tree that can depend on the parent widget's size.
LimitedBox
a box that limits its size only when it's unconstrained.
LinearProgressIndicator
vertical line that changes color as an ongoing process, such as loading an app or submitting a form, completes.
ListBody
a widget that arranges its children sequentially along a given axis, forcing them to the dimension of the parent in the other axis.
ListTile
a single fixed-height row that typically contains some text as well as a leading or trailing icon.
ListView
a scrollable, linear list of widgets. ListView is the most commonly used scrolling widget. it displays its children one after another in the scroll direction....
LongPressDraggable
makes its child draggable starting from long press.
MaterialApp
a convenience widget that wraps a number of widgets that are commonly required for applications implementing material design.
MediaQuery
establishes a subtree in which media queries resolve to the given data.
menu
container that displays a list of choices on a temporary surface.
MergeSemantics
a widget that merges the semantics of its descendants.
navigation rail
persistent container on the leading edge of tablet and desktop screens to navigate to parts of an app.
NavigationBar
persistent container that enables switching between primary destinations in an app.
NavigationDrawer
container that slides from the leading edge of the app to navigate to other sections in an app.
navigator
a widget that manages a set of child widgets with a stack discipline. many apps have a navigator near the top of their widget hierarchy...
NestedScrollView
a scrolling view inside of which can be nested other scrolling views, with their scroll positions being intrinsically linked.
NotificationListener
a widget that listens for notifications bubbling up the tree.
offstage
a widget that lays the child out as if it was in the tree, but without painting anything, without making the child available for hit...
opacity
a widget that makes its child partially transparent.
OutlinedButton
a material design outlined button, essentially a TextButton with an outlined border.
OverflowBox
a widget that imposes different constraints on its child than it gets from its parent, possibly allowing the child to overflow the parent.
padding
a widget that insets its child by the given padding.
PageView
a scrollable list that works page by page.
placeholder
a widget that draws a box that represents where other widgets will one day be added.
PopupMenuButton
displays a menu when pressed and calls onSelected when the menu is dismissed because an item was selected.
PositionedTransition
animated version of positioned which takes a specific animation to transition the child's position from a start position to and end position over the lifetime...
radio
form control that app users can set or clear to select only one option from a set.
RawImage
a widget that displays a dart:ui.Image directly.
RefreshIndicator
a material design pull-to-refresh wrapper for scrollables.
ReorderableListView
a list whose items the user can interactively reorder by dragging.
RichText
the RichText widget displays text that uses multiple different styles. the text to display is described using a tree of TextSpan objects, each of which...
RotatedBox
a widget that rotates its child by a integral number of quarter turns.
RotationTransition
animates the rotation of a widget.
row
layout a list of child widgets in the horizontal direction.
scaffold
implements the basic material design visual layout structure. this class provides APIs for showing drawers, snack bars, and bottom sheets.
ScaleTransition
animates the scale of transformed widget.
ScrollConfiguration
controls how scrollable widgets behave in a subtree.
scrollable
scrollable implements the interaction model for a scrollable widget, including gesture recognition, but does not have an opinion about how the viewport, which actually displays...
scrollbar
a material design scrollbar. a scrollbar indicates which portion of a scrollable widget is actually visible.
SegmentedButton
single or multiple selected clickable blocks to help people select options, switch views, or sort elements.
semantics
a widget that annotates the widget tree with a description of the meaning of the widgets. used by accessibility tools, search engines, and other semantic...
SimpleDialog
simple dialogs can provide additional details or actions about a list item. for example they can display avatars icons clarifying subtext or orthogonal actions (such...
SingleChildScrollView
a box in which a single widget can be scrolled. this widget is useful when you have a single box that will normally be entirely...
SizeTransition
animates its own size and clips and aligns the child.
SizedBox
a box with a specified size. if given a child, this widget forces its child to have a specific width and/or height (assuming values are...
SizedOverflowBox
a widget that is a specific size but passes its original constraints through to its child, which will probably overflow.
SlideTransition
animates the position of a widget relative to its normal position.
slider
form control that enables selecting a range of values.
SliverAppBar
a material design app bar that integrates with a CustomScrollView.
SliverChildBuilderDelegate
a delegate that supplies children for slivers using a builder callback.
SliverChildListDelegate
a delegate that supplies children for slivers using an explicit list.
SliverFixedExtentList
a sliver that places multiple box children with the same main axis extent in a linear array.
SliverGrid
a sliver that places multiple box children in a two dimensional arrangement.
SliverList
a sliver that places multiple box children in a linear array along the main axis.
SliverPadding
a sliver that applies padding on each side of another sliver.
SliverPersistentHeader
a sliver whose size varies when the sliver is scrolled to the edge of the viewport opposite the sliver's GrowthDirection.
SliverToBoxAdapter
a sliver that contains a single box widget.
SnackBar
brief messages about app processes that display at the bottom of the screen.
stack
this class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with...
stepper
a material design stepper widget that displays progress through a sequence of steps.
StreamBuilder
widget that builds itself based on the latest snapshot of interaction with a stream.
switch
toggle control that changes the state of a single item to on or off.
TabBar
layered containers that organize content across different screens, data sets, and other interactions.
TabBarView
a page view that displays the widget which corresponds to the currently selected tab. typically used in conjunction with a TabBar.
TabController
coordinates tab selection between a TabBar and a TabBarView.
TabPageSelector
displays a row of small circular indicators, one per tab. the selected tab's indicator is highlighted. often used in conjunction with a TabBarView.
table
displays child widgets in rows and columns.
text
a run of text with a single style.
TextButton
a material design text button. a simple flat button without a border outline.
TextField
box into which app users can enter text. they appear in forms and dialogs.
theme
applies a theme to descendant widgets. a theme describes the colors and typographic choices of an application.
TimePicker
clock interface used to select and set a specific time.
tooltip
tooltips provide text labels that help explain the function of a button or other user interface action. wrap the button in a tooltip widget to...
transform
a widget that applies a transformation before painting its child.
WidgetsApp
a convenience class that wraps a number of widgets that are commonly required for an application.
wrap
a widget that displays its children in multiple horizontal or vertical runs.
<topic_end>