text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
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;
}
| website/examples/get-started/flutter-for/android_devs/lib/canvas.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/canvas.dart",
"repo_id": "website",
"token_count": 606
} | 1,271 |
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);
},
),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/listview_builder.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/listview_builder.dart",
"repo_id": "website",
"token_count": 577
} | 1,272 |
import 'package:flutter/cupertino.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 CupertinoApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
// #docregion textbutton
CupertinoButton(
onPressed: () {
// This closure is called when your button is tapped.
},
child: const Text('Do something'),
)
// #enddocregion textbutton
),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/text_button.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/text_button.dart",
"repo_id": "website",
"token_count": 324
} | 1,273 |
import 'package:flutter/material.dart';
// #docregion Navigator
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(),
},
//...
);
}
}
// #enddocregion Navigator
class UsualNavScreen extends StatelessWidget {
const UsualNavScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Hello World!');
}
}
class DrawerNavScreen extends StatelessWidget {
const DrawerNavScreen({super.key});
void navigateRoute(BuildContext context) {
// #docregion PushNamed
Navigator.of(context).pushNamed('/a');
// #enddocregion PushNamed
}
void pushNavigator(BuildContext context) {
// #docregion NavigatorPush
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const UsualNavScreen(),
),
);
// #enddocregion NavigatorPush
}
@override
Widget build(BuildContext context) {
return const Text('Hello World!');
}
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
// #docregion TabNav
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)),
],
);
}
}
// #enddocregion TabNav
class NavigationHomePage extends StatefulWidget {
const NavigationHomePage({super.key});
@override
State<NavigationHomePage> createState() => _NavigationHomePageState();
}
// #docregion NavigationHomePageState
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()],
));
}
}
// #enddocregion NavigationHomePageState
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Home Screen');
}
}
class TabScreen extends StatelessWidget {
const TabScreen({super.key});
@override
Widget build(BuildContext context) {
return const Text('Tab Screen');
}
}
class DrawerExample extends StatelessWidget {
const DrawerExample({super.key});
// #docregion Drawer
@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');
},
),
);
}
// #enddocregion Drawer
}
| website/examples/get-started/flutter-for/react_native_devs/lib/navigation.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/navigation.dart",
"repo_id": "website",
"token_count": 1360
} | 1,274 |
{
"helloWorld": "Hello World!",
"@helloWorld": {
"description": "The conventional newborn programmer greeting"
},
"hello": "Hello {userName}",
"@hello": {
"description": "A message with a single parameter",
"placeholders": {
"userName": {
"type": "String",
"example": "Bob"
}
}
},
"nWombats": "{count, plural, =0{no wombats} =1{1 wombat} other{{count} wombats}}",
"@nWombats": {
"description": "A plural message",
"placeholders": {
"count": {
"type": "num",
"format": "compact"
}
}
},
"pronoun": "{gender, select, male{he} female{she} other{they}}",
"@pronoun": {
"description": "A gendered message",
"placeholders": {
"gender": {
"type": "String"
}
}
},
"numberOfDataPoints": "Number of data points: {value}",
"@numberOfDataPoints": {
"description": "A message with a formatted int parameter",
"placeholders": {
"value": {
"type": "int",
"format": "compactCurrency",
"optionalParameters": {
"decimalDigits": 2
}
}
}
}
}
| website/examples/internationalization/gen_l10n_example/lib/l10n/app_en.arb/0 | {
"file_path": "website/examples/internationalization/gen_l10n_example/lib/l10n/app_en.arb",
"repo_id": "website",
"token_count": 492
} | 1,275 |
// Copyright 2019 The Flutter team. 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';
class GridListDemo extends StatelessWidget {
const GridListDemo({super.key, required this.type});
final GridListDemoType type;
static const List<_Photo> _photos = [
_Photo(
assetName: 'places/india_chennai_flower_market.png',
title: 'Chennai',
subtitle: 'Flower Market',
),
_Photo(
assetName: 'places/india_tanjore_bronze_works.png',
title: 'Tanjore',
subtitle: 'Bronze Works',
),
_Photo(
assetName: 'places/india_tanjore_market_merchant.png',
title: 'Tanjore',
subtitle: 'Market',
),
_Photo(
assetName: 'places/india_tanjore_thanjavur_temple.png',
title: 'Tanjore',
subtitle: 'Thanjavur Temple',
),
_Photo(
assetName: 'places/india_tanjore_thanjavur_temple_carvings.png',
title: 'Tanjore',
subtitle: 'Thanjavur Temple',
),
_Photo(
assetName: 'places/india_pondicherry_salt_farm.png',
title: 'Pondicherry',
subtitle: 'Salt Farm',
),
_Photo(
assetName: 'places/india_chennai_highway.png',
title: 'Chennai',
subtitle: 'Scooters',
),
_Photo(
assetName: 'places/india_chettinad_silk_maker.png',
title: 'Chettinad',
subtitle: 'Silk Maker',
),
_Photo(
assetName: 'places/india_chettinad_produce.png',
title: 'Chettinad',
subtitle: 'Lunch Prep',
),
_Photo(
assetName: 'places/india_tanjore_market_technology.png',
title: 'Tanjore',
subtitle: 'Market',
),
_Photo(
assetName: 'places/india_pondicherry_beach.png',
title: 'Pondicherry',
subtitle: 'Beach',
),
_Photo(
assetName: 'places/india_pondicherry_fisherman.png',
title: 'Pondicherry',
subtitle: 'Fisherman',
),
];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Grid view'),
),
body: GridView.count(
restorationId: 'grid_view_demo_grid_offset',
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
padding: const EdgeInsets.all(8),
childAspectRatio: 1,
children: _photos.map<Widget>((photo) {
return _GridDemoPhotoItem(
photo: photo,
tileStyle: type,
);
}).toList(),
),
),
);
}
}
class _Photo {
const _Photo({
required this.assetName,
required this.title,
required this.subtitle,
});
final String assetName;
final String title;
final String subtitle;
}
/// Allow the text size to shrink to fit in the space.
class _GridTitleText extends StatelessWidget {
const _GridTitleText(this.text);
final String text;
@override
Widget build(BuildContext context) {
return FittedBox(
fit: BoxFit.scaleDown,
alignment: AlignmentDirectional.centerStart,
child: Text(text),
);
}
}
class _GridDemoPhotoItem extends StatelessWidget {
const _GridDemoPhotoItem({
required this.photo,
required this.tileStyle,
});
final _Photo photo;
final GridListDemoType tileStyle;
@override
Widget build(BuildContext context) {
final Widget image = Semantics(
label: '${photo.title} ${photo.subtitle}',
child: Material(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
clipBehavior: Clip.antiAlias,
child: Image.asset(
photo.assetName,
fit: BoxFit.cover,
),
),
);
return switch (tileStyle) {
GridListDemoType.imageOnly => image,
GridListDemoType.header => GridTile(
header: Material(
color: Colors.transparent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(4)),
),
clipBehavior: Clip.antiAlias,
child: GridTileBar(
title: _GridTitleText(photo.title),
backgroundColor: Colors.black45,
),
),
child: image,
),
GridListDemoType.footer => GridTile(
footer: Material(
color: Colors.transparent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(bottom: Radius.circular(4)),
),
clipBehavior: Clip.antiAlias,
child: GridTileBar(
backgroundColor: Colors.black45,
title: _GridTitleText(photo.title),
subtitle: _GridTitleText(photo.subtitle),
),
),
child: image,
)
};
}
}
enum GridListDemoType {
imageOnly,
header,
footer,
}
void main() {
runApp(const GridListDemo(type: GridListDemoType.footer));
}
| website/examples/layout/gallery/lib/grid_list_demo.dart/0 | {
"file_path": "website/examples/layout/gallery/lib/grid_list_demo.dart",
"repo_id": "website",
"token_count": 2297
} | 1,276 |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'src/passing_callbacks.dart' as callbacks;
import 'src/performance.dart' as performance;
import 'src/provider.dart';
import 'src/set_state.dart' as set_state;
// #docregion main
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CartModel(),
child: const MyApp(),
),
);
}
// #enddocregion main
Map<String, WidgetBuilder> _routes = {
'/setstate': (context) => const set_state.HelperScaffoldWrapper(),
'/provider': (context) => const MyHomepage(),
'/callbacks': (context) => const callbacks.MyHomepage(),
'/perf': (context) => const performance.MyHomepage(),
};
// #docregion multi-provider-main
void multiProviderMain() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => CartModel()),
Provider(create: (context) => SomeOtherClass()),
],
child: const MyApp(),
),
);
}
// #enddocregion multi-provider-main
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter State Management Code Excerpts',
routes: _routes,
home: const Material(
child: _Menu(),
),
);
}
}
class SomeOtherClass {}
class _Menu extends StatelessWidget {
const _Menu();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Simple state management'),
),
body: Wrap(
children: [
for (final name in _routes.keys)
TextButton(
onPressed: () => Navigator.pushNamed(context, name),
child: Text(name),
)
],
),
);
}
}
| website/examples/state_mgmt/simple/lib/main.dart/0 | {
"file_path": "website/examples/state_mgmt/simple/lib/main.dart",
"repo_id": "website",
"token_count": 719
} | 1,277 |
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'),
),
),
);
}
}
| website/examples/testing/code_debugging/lib/dump_app.dart/0 | {
"file_path": "website/examples/testing/code_debugging/lib/dump_app.dart",
"repo_id": "website",
"token_count": 210
} | 1,278 |
// ignore_for_file: equal_elements_in_set
import 'package:flutter/material.dart';
void main() {
// #docregion Syntax
print(<Widget>{
// this is the syntax for a Set<Widget> literal
const SizedBox(),
const SizedBox(),
}.length);
// #enddocregion Syntax
// #docregion SyntaxExplain
print(<Widget>{
const SizedBox(/* location: Location(file: 'foo.dart', line: 12) */),
const SizedBox(/* location: Location(file: 'foo.dart', line: 13) */),
}.length);
// #enddocregion SyntaxExplain
}
| website/examples/testing/debugging/lib/main.dart/0 | {
"file_path": "website/examples/testing/debugging/lib/main.dart",
"repo_id": "website",
"token_count": 194
} | 1,279 |
# adaptive_app_demos
This project contains demo code for adaptive app development techniques from
https://github.com/gskinnerTeam/flutter-adaptive-demo.
Additional example code in this project was moved from
code snippets originally seen in
[Building adaptive apps](https://docs.flutter.dev/ui/layout/responsive/building-adaptive-apps)
to ensure analysis in the flutter.dev CI pipeline.
These snippets were intended to illustrate concepts and may
therefore not be fully integrated/a functional part of the original demo code.
| website/examples/ui/layout/adaptive_app_demos/README.md/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/README.md",
"repo_id": "website",
"token_count": 128
} | 1,280 |
import 'package:flutter/material.dart';
import '../global/device_type.dart';
class OkCancelDialog extends StatelessWidget {
const OkCancelDialog({super.key, required this.message});
final String message;
@override
Widget build(BuildContext context) {
return Dialog(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Padding(
padding: const EdgeInsets.all(Insets.large),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message),
const SizedBox(height: Insets.large),
_OkCancelButtons(),
],
),
),
),
);
}
}
class _OkCancelButtons extends StatelessWidget {
@override
Widget build(BuildContext context) {
// #docregion RowTextDirection
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),
),
],
),
],
);
// #enddocregion RowTextDirection
}
}
class DialogButton extends StatelessWidget {
const DialogButton({
super.key,
required this.onPressed,
required this.label,
});
final VoidCallback onPressed;
final String label;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: onPressed,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(label),
),
);
}
}
| website/examples/ui/layout/adaptive_app_demos/lib/widgets/ok_cancel_dialog.dart/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/lib/widgets/ok_cancel_dialog.dart",
"repo_id": "website",
"token_count": 854
} | 1,281 |
import 'package:flutter/material.dart';
// #docregion Toggle
void showOversizedImages() {
debugInvertOversizedImages = true;
}
// #enddocregion Toggle
// #docregion ResizedImage
class ResizedImage extends StatelessWidget {
const ResizedImage({super.key});
@override
Widget build(BuildContext context) {
return Image.asset(
'dash.png',
cacheHeight: 213,
cacheWidth: 392,
);
}
}
// #enddocregion ResizedImage
| website/examples/visual_debugging/lib/oversized_images.dart/0 | {
"file_path": "website/examples/visual_debugging/lib/oversized_images.dart",
"repo_id": "website",
"token_count": 158
} | 1,282 |
- platform: 'Android SDK'
chipsets: 'x64, Arm32, Arm64'
supported: '21 to 34'
besteffort: '19 to 20'
unsupported: '18 and earlier'
- platform: 'iOS'
chipsets: 'Arm64'
supported: '17'
besteffort: '12 to 16'
unsupported: '11 and earlier'
- platform: 'macOS'
chipsets: 'x64, Arm64'
supported: '<abbr title="Ventura">13</abbr>'
besteffort: '<abbr title="Mojave">10.14</abbr> to <abbr title="Monterrey">12</abbr>, <abbr title="Sonoma">14</abbr>'
unsupported: '<abbr title="High Sierra">10.13</abbr> and earlier'
- platform: 'Windows'
chipsets: 'x64, Arm64'
supported: '10'
besteffort: '7, 8, 11'
unsupported: 'Vista and earlier'
- platform: 'Debian (Linux)'
chipsets: 'x64, Arm64'
supported: '11, 12'
besteffort: '9, 10'
unsupported: '8 and earlier'
- platform: 'Ubuntu (Linux)'
chipsets: 'x64, Arm64'
supported: '20.04 LTS'
besteffort: '22.04 to 23.10'
unsupported: '22.04 and earlier normal'
- platform: 'Chrome (Web)'
chipsets: 'N/A'
supported: '[Latest 2](https://chromereleases.googleblog.com/search/label/Stable%20updates)'
besteffort: '96 to latest 2'
unsupported: '95 and earlier'
- platform: 'Firefox (Web)'
chipsets: 'N/A'
supported: '[Latest 2](https://www.mozilla.org/en-US/firefox/releases/)'
besteffort: '99 to latest 2'
unsupported: '98 and earlier'
- platform: 'Safari (Web)'
chipsets: 'N/A'
supported: '[Latest 2](https://developer.apple.com/documentation/safari-release-notes/)'
besteffort: '15.6 to latest 2'
unsupported: '15.5 and earlier'
- platform: 'Edge (Web)'
chipsets: 'N/A'
supported: '[Latest 2](https://learn.microsoft.com/en-us/deployedge/microsoft-edge-relnote-stable-channel)'
besteffort: '96 to latest 2'
unsupported: '95 and earlier'
| website/src/_data/platforms.yml/0 | {
"file_path": "website/src/_data/platforms.yml",
"repo_id": "website",
"token_count": 659
} | 1,283 |
{{site.alert.note}}
The Flutter SDK contains the `dart` command alongside the `flutter` command
so that you can more easily run Dart command-line programs.
Downloading the Flutter SDK also downloads the compatible version of Dart,
but if you've downloaded the Dart SDK separately,
make sure that the Flutter version of `dart` is
first in your path, as the two versions might not be compatible.
The following command tells you whether the `flutter` and `dart`
commands originate from the same `bin` directory and are
therefore compatible.
```terminal
C:\>where flutter dart
C:\path-to-flutter-sdk\bin\flutter
C:\path-to-flutter-sdk\bin\flutter.bat
C:\path-to-dart-sdk\bin\dart.exe :: this should go after `C:\path-to-flutter-sdk\bin\` commands
C:\path-to-flutter-sdk\bin\dart
C:\path-to-flutter-sdk\bin\dart.bat
```
As shown above, the command `dart` from the Flutter SDK doesn't come first.
Update your path to use commands from `C:\path-to-flutter-sdk\bin\` before
commands from `C:\path-to-dart-sdk\bin\` (in this case).
After restarting your shell for the change to take effect,
running the `where` command again
should show that the `flutter` and `dart` commands
from the same directory now come first.
```terminal
C:\>where flutter dart
C:\dev\src\flutter\bin\flutter
C:\dev\src\flutter\bin\flutter.bat
C:\dev\src\flutter\bin\dart
C:\dev\src\flutter\bin\dart.bat
C:\dev\src\dart-sdk\bin\dart.exe
```
However, if you are using `PowerShell`, in it `where` is
an alias of `Where-Object` command, so you need to use `where.exe` instead.
```terminal
PS C:\> where.exe flutter dart
```
To learn more about the `dart` command, run `dart -h`
from the command line, or see the [dart tool][] page.
{{site.alert.end}}
[dart tool]: {{site.dart-site}}/tools/dart-tool
| website/src/_includes/docs/dart-tool-win.md/0 | {
"file_path": "website/src/_includes/docs/dart-tool-win.md",
"repo_id": "website",
"token_count": 642
} | 1,284 |
{{site.alert.important}}
Perform this guide in sequence. Skipping steps can cause errors.
{{site.alert.end}}
| website/src/_includes/docs/install/admonitions/install-in-order.md/0 | {
"file_path": "website/src/_includes/docs/install/admonitions/install-in-order.md",
"repo_id": "website",
"token_count": 31
} | 1,285 |
{% assign os = include.os %}
{% assign target = include.target %}
{% include docs/install/admonitions/install-in-order.md %}
## Verify system requirements
To install and run Flutter,
your {{os}} environment must meet the following hardware
and software requirements.
### Hardware requirements
Your {{os}} Flutter development environment must meet the following
minimal hardware requirements.
<div class="table-wrapper" markdown="1">
| Requirement | Minimum | Recommended |
|:-----------------------------|:------------------------------------------------------------------------:|:-------------------:|
| CPU Cores | 4 | 8 |
| Memory in GB | 8 | 16 |
| Display resolution in pixels | WXGA (1366 x 768) | FHD (1920 x 1080) |
| Free disk space in GB | {% include docs/install/reqs/linux/storage.md target=target %}
</div>
{% if os == 'ChromeOS' and target == 'Android' %}
To discover which hardware devices ChromeOS recommends for Android development,
consult the [ChromeOS docs][chromeos-docs].
{% endif %}
[chromeos-docs]: https://chromeos.dev/en/android-environment
### Software requirements
To write and compile Flutter code for {{target}},
you must have the following version of {{os}} and the listed
software packages.
#### Operating system
{:.no_toc}
{% if os == 'Linux' %}
{%- capture supported-os %}
Debian Linux {{site.devmin.linux.debian}} or later
and Ubuntu Linux {{site.devmin.linux.ubuntu}} or later
{% endcapture -%}
{% else %}
{% assign supported-os = 'ChromeOS' %}
{% endif %}
Flutter supports {{supported-os}}.
#### Development tools
{:.no_toc}
{% include docs/install/reqs/linux/software.md target=target os=os %}
{% include docs/install/reqs/flutter-sdk/flutter-doctor-precedence.md %}
The developers of the preceding software provide support for those products.
To troubleshoot installation issues, consult that product's documentation.
## Configure a text editor or IDE
You can build apps with Flutter using any text editor or
integrated development environment (IDE) combined with
Flutter's command-line tools.
Using an IDE with a Flutter extension or plugin provides code completion,
syntax highlighting, widget editing assists, debugging, and other features.
Popular options include:
* [Visual Studio Code][vscode] {{site.appmin.vscode}} or later
with the [Flutter extension for VS Code][].
* [Android Studio][] {{site.appmin.android_studio}} or later
with the [Flutter plugin for IntelliJ][].
* [IntelliJ IDEA][] {{site.appmin.intellij_idea}} or later
with the [Flutter plugin for IntelliJ][].
{{site.alert.recommend}}
The Flutter team recommends installing [Visual Studio Code][vscode]
{{site.appmin.vscode}} or later and the [Flutter extension for VS Code][].
This combination simplifies installing the Flutter SDK.
{{site.alert.end}}
[Android Studio]: https://developer.android.com/studio/install#linux
[IntelliJ IDEA]: https://www.jetbrains.com/help/idea/installation-guide.html
[vscode]: https://code.visualstudio.com/docs/setup/linux
[Flutter extension for VS Code]: https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[Flutter plugin for IntelliJ]: https://plugins.jetbrains.com/plugin/9212-flutter
| website/src/_includes/docs/install/reqs/linux/base.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/linux/base.md",
"repo_id": "website",
"token_count": 1296
} | 1,286 |
{% if include.target == 'desktop' -%}
* [Visual Studio 2022][] to debug and compile native C++ Windows code.
Make sure to install the **Desktop development with C++** workload.
This enables building Windows app including all of its default components.
**Visual Studio** is an IDE separate from **[Visual Studio _Code_][]**.
{% elsif include.target == 'mobile' -%}
* [Android Studio][] {{site.appmin.android_studio}} to debug and compile
Java or Kotlin code for Android.
Flutter requires the full version of Android Studio.
{% elsif include.target == 'web' -%}
* [Google Chrome][] to debug JavaScript code for web apps.
{% else -%}
* [Visual Studio 2022][] with the the **Desktop development with C++** workload
or [Build Tools for Visual Studio 2022][].
This enables building Windows app including all of its default components.
**Visual Studio** is an IDE separate from **[Visual Studio _Code_][]**.
* [Android Studio][] {{site.appmin.android_studio}} to debug and compile
Java or Kotlin code for Android.
Flutter requires the full version of Android Studio.
* The latest version of [Google Chrome][] to debug JavaScript code for web apps.
{% endif -%}
[Android Studio]: https://developer.android.com/studio/install#windows
[Visual Studio 2022]: https://learn.microsoft.com/visualstudio/install/install-visual-studio?view=vs-2022
[Build Tools for Visual Studio 2022]: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022
[Google Chrome]: https://www.google.com/chrome/dr/download/
[Visual Studio _Code_]: https://code.visualstudio.com/
| website/src/_includes/docs/install/reqs/windows/software.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/windows/software.md",
"repo_id": "website",
"token_count": 453
} | 1,287 |
{% if page.diff2html -%}
{% comment %}Get from CDN for now{% endcomment -%}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/github.min.css" integrity="sha512-7QTQ5Qsc/IL1k8UU2bkNFjpKTfwnvGuPYE6fzm6yeneWTEGiA3zspgjcTsSgln9m0cn3MgyE7EnDNkF1bB/uCw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/diff2html/2.12.2/diff2html.css" integrity="sha512-5wTRTFfZjM308tVHwxoRX4dRjECvSJQeCsOt2yuZoKe5UACngZ0ihkhGsjfiNef26AjTFl6bNyw+2Gf5JGlTLw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff2html/2.12.2/diff2html.min.js" integrity="sha512-8cdb9zL6w8Wyo/efaAxbcA7Gh+lJglOQvChN0clQ7bZQ4BaV5RgBGavSa1pUhVkcWlalyttHMhxPPf9koYmJNw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/diff2html/2.12.2/diff2html-ui.js" integrity="sha512-O6oUIH4/NypmxRX1uQYSXZDE1cTTMXcnZKGeizozCa2bN2YWiH/gkw21FDUZ9SWDCl+Yw5L4OASvZz/Bp5KkEg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js" integrity="sha512-zol3kFQ5tnYhL7PzGt0LnllHHVWRGt2bTCIywDiScVvLIlaDOVJ6sPdJTVi0m3rA660RT+yZxkkRzMbb1L8Zkw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/dart.min.js" integrity="sha512-7XEwLyeyXQMzcKJzj/etI+Nd8+kiUyQdpKos15OOpdwrHIOwRAiLrOBHjm6IKJ/JVqm8jcPwv3J8gTLyELwSHg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/yaml.min.js" integrity="sha512-+SOjIeQujn8n6mzB4huTBHQGnbF8OaiOOfBMalxIV0YSOSNFdatL+DVCZJj5JLN8XOnpR6v8kkWBpwDCiuWnKw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
function setupDiff() {
const diff2htmlUi = new Diff2HtmlUI();
diff2htmlUi.highlightCode(".d2h-wrapper");
}
if (document.readyState !== "loading") {
setupDiff();
} else {
document.addEventListener("DOMContentLoaded", setupDiff);
}
</script>
{% endif -%}
| website/src/_includes/head-diff2html.html/0 | {
"file_path": "website/src/_includes/head-diff2html.html",
"repo_id": "website",
"token_count": 1065
} | 1,288 |
---
layout: default
toc: false
sitemap: false
---
{% assign url = page.url | regex_replace: '/index$|/index.html$|/$' -%}
{% assign path_parts = url | split: '/' -%}
{% assign topics = site.data.sidenav -%}
{% comment %}
- path_parts[0] == '' because page.url always starts with '/'
{% endcomment -%}
{% for path_part in path_parts -%}
{% if forloop.first == true -%}
{% assign path = '' -%}
{% else -%}
{% assign path = path | append: '/' | append: path_part -%}
{% endif -%}
{% if forloop.index0 > 0 and path != '/ui' -%}
{% assign topics = topics | where: "permalink", path -%}
{% assign topics = topics[0].children | where_exp:"item", "item != 'divider'" -%}
{% endif -%}
{% endfor -%}
{% assign entries = topics -%}
{% capture md %}{% include mini-toc.md %}{% endcapture %}
{{ md | markdownify }}
{{content}}
| website/src/_layouts/toc.html/0 | {
"file_path": "website/src/_layouts/toc.html",
"repo_id": "website",
"token_count": 333
} | 1,289 |
module RegexReplaceFilter
# From https://github.com/Shopify/liquid/issues/202#issuecomment-19112872
def regex_replace(input, regex, replacement = '')
input.to_s.gsub(Regexp.new(regex), replacement.to_s)
end
end
Liquid::Template.register_filter(RegexReplaceFilter)
| website/src/_plugins/regex_replace_filter.rb/0 | {
"file_path": "website/src/_plugins/regex_replace_filter.rb",
"repo_id": "website",
"token_count": 96
} | 1,290 |
@use '../vendor/bootstrap';
.site-nextprev-nav, // Nav with both links
.site-nextprev-nav__single // Nav with single link
{
clear: both;
ul {
$spacer-base: bootstrap.bs-spacer(3);
list-style-type: none;
margin: 0;
padding: 0;
li {
display: flex;
margin-bottom: $spacer-base;
white-space: nowrap;
a {
text-overflow: ellipsis;
overflow: hidden;
}
&.prev:before {
color: bootstrap.$primary;
content: "\2329"; // ⟨
padding-right: $spacer-base * 0.5;
}
&.next {
justify-content: flex-end;
text-align: right;
}
&.next:after {
color: bootstrap.$primary;
content: "\232A"; // ⟩
padding-left: $spacer-base * 0.5;
}
}
}
}
.site-nextprev-nav > ul > li {
width: 49%;
&.prev { float: left; }
}
.site-nextprev-nav__single > ul > li {
&.prev { width: 100%; }
&.next {
float: right;
width: 100%;
}
}
| website/src/_sass/components/_next-prev-nav.scss/0 | {
"file_path": "website/src/_sass/components/_next-prev-nav.scss",
"repo_id": "website",
"token_count": 482
} | 1,291 |
---
title: Debug your add-to-app module
short-title: Debugging
description: How to run, debug, and hot reload your add-to-app Flutter 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`.
### 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.
#### Terminal
Run `flutter attach` or `flutter attach -d deviceId` to attach from the terminal.
{% include docs/app-figure.md image="development/add-to-app/debugging/cli-attach.png" caption="flutter attach via terminal" %}
#### VS Code
{% include docs/debug/debug-flow-ios.md %}
{% include docs/debug/vscode-flutter-attach-json.md %}
#### IntelliJ / Android Studio
Select the device on which the Flutter module runs so `flutter attach` filters for the right start signals.
{% include docs/app-figure.md image="development/add-to-app/debugging/intellij-attach.png" caption="flutter attach via IntelliJ" %}
[debugging functionalities]: /testing/debugging
### Wireless debugging
You can debug your app wirelessly on an iOS or Android device
using `flutter attach`.
#### iOS
On iOS, you must follow the steps below:
<ol markdown="1">
<li markdown="1">
Ensure that your device is wirelessly connected to Xcode
as described in the [iOS setup guide][].
</li>
<li markdown="1">
Open **Xcode > Product > Scheme > Edit Scheme**
</li>
<li markdown="1">
Select the **Arguments** tab
</li>
<li markdown="1">
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.
<img src="/assets/images/docs/development/add-to-app/debugging/wireless-port.png" alt="Check the box that says 'connect via network' from the devices and simulators page">
</li>
</ol>
#### Android
Ensure that your device is wirelessly connected to Android Studio
as described in the [Android setup guide][].
[iOS setup guide]: /get-started/install/macos/mobile-ios
[Android setup guide]: /get-started/install/macos/mobile-android?tab=physical#configure-your-target-android-device
| website/src/add-to-app/debugging.md/0 | {
"file_path": "website/src/add-to-app/debugging.md",
"repo_id": "website",
"token_count": 938
} | 1,292 |
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="567.27px" height="159px" viewBox="0 0 567.27 159" enable-background="new 0 0 567.27 159" xml:space="preserve">
<g>
<g enable-background="new ">
<path fill="#FFFFFF" d="M199.42,35.51H252V45.8h-41.91v31.12h37.85v10.16h-37.85v39.37h-10.67V35.51z"/>
<path fill="#FFFFFF" d="M264.7,35.51h10.79v90.93H264.7V35.51z"/>
<path fill="#FFFFFF" d="M297.15,121.61c-4.11-4.57-6.16-10.96-6.16-19.18V61.67h10.79v39.12c0,6.18,1.4,10.71,4.19,13.59
s6.56,4.32,11.3,4.32c3.64,0,6.88-0.97,9.71-2.92c2.84-1.95,5.04-4.49,6.6-7.62c1.57-3.13,2.35-6.43,2.35-9.91V61.67h10.8v64.77
h-10.29v-9.4h-0.51c-1.78,3.22-4.62,5.93-8.51,8.13c-3.9,2.2-8.04,3.3-12.45,3.3C307.2,128.47,301.25,126.18,297.15,121.61z"/>
<path fill="#FFFFFF" d="M380.97,127.18c-2.25-0.86-4.13-2.03-5.65-3.49c-1.7-1.64-2.96-3.53-3.81-5.69s-1.27-4.78-1.27-7.89V71.45
h-11.3v-9.78h11.3V43.38h10.79v18.29h15.75v9.78h-15.75v36.09c0,3.64,0.68,6.32,2.03,8.05c1.61,1.91,3.94,2.86,6.99,2.86
c2.46,0,4.83-0.72,7.11-2.16v10.54c-1.27,0.59-2.56,1.02-3.87,1.27s-2.98,0.38-5.02,0.38
C385.64,128.47,383.21,128.04,380.97,127.18z"/>
<path fill="#FFFFFF" d="M426.81,127.18c-2.25-0.86-4.13-2.03-5.65-3.49c-1.7-1.64-2.96-3.53-3.81-5.69s-1.27-4.78-1.27-7.89V71.45
h-11.3v-9.78h11.3V43.38h10.79v18.29h15.75v9.78h-15.75v36.09c0,3.64,0.68,6.32,2.03,8.05c1.61,1.91,3.94,2.86,6.99,2.86
c2.46,0,4.83-0.72,7.11-2.16v10.54c-1.27,0.59-2.56,1.02-3.87,1.27s-2.98,0.38-5.02,0.38
C431.49,128.47,429.06,128.04,426.81,127.18z"/>
<path fill="#FFFFFF" d="M465.11,124.02c-4.91-2.96-8.74-7.05-11.49-12.25c-2.75-5.21-4.13-11.07-4.13-17.59
c0-6.26,1.29-12.02,3.87-17.27s6.24-9.44,10.99-12.57c4.74-3.13,10.24-4.7,16.51-4.7c6.35,0,11.85,1.42,16.51,4.25
c4.66,2.84,8.23,6.75,10.73,11.75s3.75,10.71,3.75,17.15c0,1.27-0.13,2.37-0.38,3.3h-51.18c0.25,4.91,1.44,9.06,3.56,12.45
s4.8,5.93,8.06,7.62c3.26,1.7,6.67,2.54,10.22,2.54c8.3,0,14.69-3.89,19.18-11.68l9.14,4.45c-2.79,5.25-6.58,9.4-11.37,12.45
c-4.78,3.05-10.56,4.57-17.33,4.57C475.56,128.47,470.02,126.99,465.11,124.02z M500.41,87.19c-0.17-2.71-0.93-5.42-2.29-8.13
c-1.36-2.71-3.49-4.99-6.41-6.86c-2.92-1.86-6.58-2.79-10.99-2.79c-5.08,0-9.38,1.63-12.89,4.89s-5.82,7.56-6.92,12.89H500.41z"/>
<path fill="#FFFFFF" d="M524.41,61.67h10.29v10.41h0.51c1.27-3.56,3.72-6.52,7.37-8.89c3.64-2.37,7.45-3.56,11.43-3.56
c2.96,0,5.5,0.47,7.62,1.4v11.56c-2.71-1.35-5.76-2.03-9.14-2.03c-3.13,0-6.01,0.89-8.64,2.67c-2.62,1.78-4.72,4.18-6.29,7.19
s-2.35,6.26-2.35,9.74v36.28h-10.79V61.67H524.41z"/>
</g>
<g>
<g>
<g>
<g>
<defs>
<path id="SVGID_1_" d="M131.51,73.51l-41.95,41.95l41.95,41.96l0,0H83.57l-17.98-17.98l0,0l-23.98-23.98l41.96-41.95
L131.51,73.51L131.51,73.51L131.51,73.51z M83.57,1.58L5.65,79.5l23.98,23.98L131.51,1.58H83.57z"/>
</defs>
<clipPath id="SVGID_2_">
<use xlink:href="#SVGID_1_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_2_)">
<g>
<polygon fill="#39CEFD" points="131.51,73.51 131.51,73.51 131.51,73.51 83.57,73.51 41.61,115.47 65.58,139.43 "/>
</g>
</g>
</g>
</g>
<g>
<g>
<defs>
<path id="SVGID_3_" d="M131.51,73.51l-41.95,41.95l41.95,41.96l0,0H83.57l-17.98-17.98l0,0l-23.98-23.98l41.96-41.95
L131.51,73.51L131.51,73.51L131.51,73.51z M83.57,1.58L5.65,79.5l23.98,23.98L131.51,1.58H83.57z"/>
</defs>
<clipPath id="SVGID_4_">
<use xlink:href="#SVGID_3_" overflow="visible"/>
</clipPath>
<polygon clip-path="url(#SVGID_4_)" fill="#39CEFD" points="29.63,103.48 5.65,79.5 83.57,1.58 131.51,1.58 "/>
</g>
</g>
<g>
<g>
<defs>
<path id="SVGID_5_" d="M131.51,73.51l-41.95,41.95l41.95,41.96l0,0H83.57l-17.98-17.98l0,0l-23.98-23.98l41.96-41.95
L131.51,73.51L131.51,73.51L131.51,73.51z M83.57,1.58L5.65,79.5l23.98,23.98L131.51,1.58H83.57z"/>
</defs>
<clipPath id="SVGID_6_">
<use xlink:href="#SVGID_5_" overflow="visible"/>
</clipPath>
<polygon clip-path="url(#SVGID_6_)" fill="#03569B" points="65.58,139.43 83.57,157.42 131.51,157.42 131.51,157.42
89.56,115.47 "/>
</g>
</g>
<g>
<g>
<defs>
<path id="SVGID_7_" d="M131.51,73.51l-41.95,41.95l41.95,41.96l0,0H83.57l-17.98-17.98l0,0l-23.98-23.98l41.96-41.95
L131.51,73.51L131.51,73.51L131.51,73.51z M83.57,1.58L5.65,79.5l23.98,23.98L131.51,1.58H83.57z"/>
</defs>
<clipPath id="SVGID_8_">
<use xlink:href="#SVGID_7_" overflow="visible"/>
</clipPath>
<linearGradient id="SVGID_9_" gradientUnits="userSpaceOnUse" x1="13607.9531" y1="7933.7598" x2="13679.3789" y2="7862.334" gradientTransform="matrix(0.25 0 0 0.25 -3329.4131 -1839.375)">
<stop offset="0" style="stop-color:#1A237E;stop-opacity:0.4"/>
<stop offset="1" style="stop-color:#1A237E;stop-opacity:0"/>
</linearGradient>
<polygon clip-path="url(#SVGID_8_)" fill="url(#SVGID_9_)" points="65.58,139.43 101.14,127.13 89.56,115.47 "/>
</g>
</g>
<g>
<g>
<defs>
<path id="SVGID_10_" d="M131.51,73.51l-41.95,41.95l41.95,41.96l0,0H83.57l-17.98-17.98l0,0l-23.98-23.98l41.96-41.95
L131.51,73.51L131.51,73.51L131.51,73.51z M83.57,1.58L5.65,79.5l23.98,23.98L131.51,1.58H83.57z"/>
</defs>
<clipPath id="SVGID_11_">
<use xlink:href="#SVGID_10_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_11_)">
<rect x="48.63" y="98.51" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -62.4365 80.1901)" fill="#16B9FD" width="33.9" height="33.9"/>
</g>
</g>
</g>
</g>
<radialGradient id="SVGID_12_" cx="13354.416" cy="7406.333" r="762.6133" gradientTransform="matrix(0.25 0 0 0.25 -3329.4131 -1839.375)" gradientUnits="userSpaceOnUse">
<stop offset="0" style="stop-color:#FFFFFF;stop-opacity:0.1"/>
<stop offset="1" style="stop-color:#FFFFFF;stop-opacity:0"/>
</radialGradient>
<path fill="url(#SVGID_12_)" d="M131.51,73.51l-41.95,41.95l41.95,41.96l0,0H83.57l-17.98-17.98l0,0l-23.98-23.98l41.96-41.95
L131.51,73.51L131.51,73.51L131.51,73.51z M83.57,1.58L5.65,79.5l23.98,23.98L131.51,1.58H83.57z"/>
</g>
</g>
</svg>
| website/src/assets/images/branding/flutter/logo+text/horizontal/white.svg/0 | {
"file_path": "website/src/assets/images/branding/flutter/logo+text/horizontal/white.svg",
"repo_id": "website",
"token_count": 4122
} | 1,293 |
{% assign id = include.ref-os | downcase -%}
{% assign jsonurl = 'https://storage.googleapis.com/flutter_infra_release/releases/releases_{{id}}.json' %}
{% assign os = include.ref-os -%}
{% assign sdk = include.sdk -%}
{% if id == 'windows' -%}
{% assign shell = 'Powershell' -%}
{% assign prompt = 'C:\>' -%}
{% assign comtoset = '$env:' -%}
{% assign installdirsuggestion = '`%USERPROFILE%\dev`' %}
{% capture envvarset -%}{{prompt}} {{comtoset}}{% endcapture -%}
{% capture setpath -%}{{envvarset}}PATH = $pwd.PATH + "/flutter/bin",$env:PATH -join ";"{% endcapture -%}
{% capture newdir -%}{{prompt}} New-Item -Path '{{installdirsuggestion}}' -ItemType Directory{% endcapture -%}
{% capture unzip -%} {{prompt}} Extract-Archive:{% endcapture -%}
{% capture permaddexample -%}
$newPath = $pwd.PATH + "/flutter/bin",$env:PATH -join ";"
[System.Environment]::SetEnvironmentVariable('Path',$newPath,User)
[System.Environment]::SetEnvironmentVariable('PUB_HOSTED_URL','https://pub.flutter-io.cn',User)
[System.Environment]::SetEnvironmentVariable('FLUTTER_STORAGE_BASE_URL','https://storage.flutter-io.cn',User)
{% endcapture -%}
{% else -%}
{% assign shell = 'your terminal' -%}
{% assign prompt = '$' -%}
{% assign comtoset = 'export ' -%}
{% assign installdirsuggestion = '`~/dev`' %}
{% capture envvarset -%}{{prompt}} {{comtoset}}{% endcapture -%}
{% capture setpath -%}{{envvarset}}PATH="$PWD/flutter/bin:$PATH"{% endcapture -%}
{% capture newdir -%}{{prompt}} mkdir ~/dev{% endcapture -%}
{% if id == 'macos' %}
{% capture unzip -%} {{prompt}} unzip{% endcapture -%}
{% else %}
{% capture unzip -%} {{prompt}} tar -xf{% endcapture -%}
{% endif %}
{% capture permaddexample -%}
cat <<EOT >> ~/.zprofile
{{envvarset}}PUB_HOSTED_URL="https://pub.flutter-io.cn"
{{envvarset}}FLUTTER_STORAGE_BASE_URL="https://storage.flutter-io.cn"
{{setpath}}
EOT
{% endcapture -%}
{% endif -%}
{%- case id %}
{% when 'windows','macos' %}
{%- assign file-format = 'zip' %}
{%- assign download-os = id %}
{% when 'linux','chromeos' %}
{%- assign download-os = 'linux' %}
{%- assign file-format = 'tar.xz' %}
{% endcase %}
<div id="{{id}}" class="tab-pane
{%- if id == 'windows' %} active {% endif %}"
role="tabpanel" aria-labelledby="{{id}}-tab" markdown="1">
This procedure requires using {{shell}}.
1. Open a new window in {{shell}} to prepare running scripts.
1. Set `PUB_HOSTED_URL` to your mirror site.
```terminal
{{envvarset}}PUB_HOSTED_URL="https://pub.flutter-io.cn"
```
1. Set `FLUTTER_STORAGE_BASE_URL` to your mirror site.
```terminal
{{envvarset}}FLUTTER_STORAGE_BASE_URL="https://storage.flutter-io.cn"
```
1. Download the Flutter archive from your mirror site.
In your preferred browser, go to
[Flutter SDK archive](https://flutter.cn/docs/release/archive?tab={{id}}).
1. Create a folder where you can install Flutter. then change into it.
Consider a path like {{installdirsuggestion}}.
```terminal
{{newdir}}; cd {{installdirsuggestion}}
```
1. Extract the SDK from the {{file-format}} archive file.
This example assumes you downloaded the {{os}} version of the Flutter SDK.
```terminal
{{unzip}} {{sdk | replace: "opsys", download-os}}{{file-format}}
```
1. Add Flutter to your `PATH` environment variable.
```terminal
{{setpath}}
```
1. Run Flutter Doctor to verify your installation.
```terminal
{{prompt}} flutter doctor
```
1. Return to the [setting up Flutter](/get-started/editor)
guide and continue from that procedure.
From this example, `flutter pub get` fetches packages from `flutter-io.cn`,
in any terminal where you set `PUB_HOSTED_URL` and `FLUTTER_STORAGE_BASE_URL`.
Any environment variables set using `{{comtoset}}` in this procedure
only apply to the current window.
To set these values on a permanent basis,
{% if id == 'windows' -%}
set the environment variables as in the following example:
{% else -%}
append those three `export` commands to the `*rc` or `*profile`
file that your preferred shell uses. This would resemble the following:
{% endif -%}
```terminal
{{permaddexample}}
```
</div>
| website/src/community/china/_os-settings.md/0 | {
"file_path": "website/src/community/china/_os-settings.md",
"repo_id": "website",
"token_count": 1626
} | 1,294 |
---
title: Create a download button
description: How to implement a download button.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/effects/download_button"?>
Apps are filled with buttons that execute long-running behaviors.
For example, a button might trigger a download,
which starts a download process, receives data over time,
and then provides access to the downloaded asset.
It's helpful to show the user the progress of a
long-running process, and the button itself is a good place
to provide this feedback. In this recipe,
you'll build a download button that transitions through
multiple visual states, based on the status of an app download.
The following animation shows the app's behavior:
{:.site-mobile-screenshot}
## Define a new stateless widget
Your button widget needs to change its appearance over time.
Therefore, you need to implement your button with a custom
stateless widget.
Define a new stateless widget called `DownloadButton`.
<?code-excerpt "lib/stateful_widget.dart (DownloadButton)"?>
```dart
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
});
@override
Widget build(BuildContext context) {
// TODO:
return const SizedBox();
}
}
```
## Define the button's possible visual states
The download button's visual presentation is based on a
given download status. Define the possible states of
the download, and then update `DownloadButton` to accept
a `DownloadStatus` and a `Duration` for how long the button
should take to animate from one status to another.
<?code-excerpt "lib/visual_states.dart (VisualStates)"?>
```dart
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.transitionDuration = const Duration(
milliseconds: 500,
),
});
final DownloadStatus status;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
// TODO: We'll add more to this later.
return const SizedBox();
}
}
```
{{site.alert.note}}
Each time you define a custom widget,
you must decide whether all relevant
information is provided to that widget
from its parent or if that widget orchestrates
the application behavior within itself.
For example, `DownloadButton` could receive the
current `DownloadStatus` from its parent,
or the `DownloadButton` could orchestrate the
download process itself within its `State` object.
For most widgets, the best answer is to pass the relevant
information into the widget from its parent,
rather than manage behavior within the widget.
By passing in all the relevant information,
you ensure greater reusability for the widget,
easier testing, and easier changes to application
behavior in the future.
{{site.alert.end}}
## Display the button shape
The download button changes its shape based on the download
status. The button displays a grey, rounded rectangle during
the `notDownloaded` and `downloaded` states.
The button displays a transparent circle during the
`fetchingDownload` and `downloading` states.
Based on the current `DownloadStatus`,
build an `AnimatedContainer` with a
`ShapeDecoration` that displays a rounded
rectangle or a circle.
Consider defining the shape's widget tree in a separated
`Stateless` widget so that the main `build()`
method remains simple, allowing for the additions
that follow. Instead of creating a function to return a widget,
like `Widget _buildSomething() {}`, always prefer creating a
`StatelessWidget` or a `StatefulWidget` which is more performant. More
considerations on this can be found in the [documentation]({{site.api}}/flutter/widgets/StatelessWidget-class.html)
or in a dedicated video in the Flutter [YouTube channel]({{site.yt.watch}}?v=IOyq-eTRhvo).
For now, the `AnimatedContainer` child is just a `SizedBox` because we will come back at it in another step.
<?code-excerpt "lib/display.dart (Display)"?>
```dart
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.transitionDuration = const Duration(
milliseconds: 500,
),
});
final DownloadStatus status;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
@override
Widget build(BuildContext context) {
return ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
);
}
}
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: const SizedBox(),
);
}
}
```
You might wonder why you need a `ShapeDecoration`
widget for a transparent circle, given that it's invisible.
The purpose of the invisible circle is to orchestrate
the desired animation. The `AnimatedContainer` begins with a rounded
rectangle. When the `DownloadStatus` changes to `fetchingDownload`,
the `AnimatedContainer` needs to animate from a rounded rectangle
to a circle, and then fade out as the animation takes place.
The only way to implement this animation is to define both
the beginning shape of a rounded rectangle and the
ending shape of a circle. But, you don't want the final
circle to be visible, so you make it transparent,
which causes an animated fade-out.
## Display the button text
The `DownloadButton` displays `GET` during the
`notDownloaded` phase, `OPEN` during the `downloaded`
phase, and no text in between.
Add widgets to display text during each download phase,
and animate the text's opacity in between. Add the text
widget tree as a child of the `AnimatedContainer` in the
button wrapper widget.
<?code-excerpt "lib/display_text.dart (DisplayText)"?>
```dart
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ? 'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activeBlue,
),
),
),
),
);
}
}
```
## Display a spinner while fetching download
During the `fetchingDownload` phase, the `DownloadButton`
displays a radial spinner. This spinner fades in from
the `notDownloaded` phase and fades out to
the `fetchingDownload` phase.
Implement a radial spinner that sits on top of the button
shape and fades in and out at the appropriate times.
We have removed the `ButtonShapeWidget`'s constructor to keep the
focus on its build method and the `Stack` widget we've added.
<?code-excerpt "lib/spinner.dart (Spinner)"?>
```dart
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
),
),
],
),
);
}
```
## Display the progress and a stop button while downloading
After the `fetchingDownload` phase is the `downloading` phase.
During the `downloading` phase, the `DownloadButton`
replaces the radial progress spinner with a growing
radial progress bar. The `DownloadButton` also displays a stop
button icon so that the user can cancel an in-progress download.
Add a progress property to the `DownloadButton` widget,
and then update the progress display to switch to a radial
progress bar during the `downloading` phase.
Next, add a stop button icon at the center of the
radial progress bar.
<?code-excerpt "lib/stop.dart (StopIcon)"?>
```dart
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: Stack(
alignment: Alignment.center,
children: [
ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
if (_isDownloading)
const Icon(
Icons.stop,
size: 14.0,
color: CupertinoColors.activeBlue,
),
],
),
),
),
],
),
);
}
```
## Add button tap callbacks
The last detail that your `DownloadButton` needs is the
button behavior. The button must do things when the user taps it.
Add widget properties for callbacks to start a download,
cancel a download, and open a download.
Finally, wrap `DownloadButton`'s existing widget tree
with a `GestureDetector` widget, and forward the
tap event to the corresponding callback property.
<?code-excerpt "lib/button_taps.dart (TapCallbacks)"?>
```dart
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.downloadProgress = 0,
required this.onDownload,
required this.onCancel,
required this.onOpen,
this.transitionDuration = const Duration(milliseconds: 500),
});
final DownloadStatus status;
final double downloadProgress;
final VoidCallback onDownload;
final VoidCallback onCancel;
final VoidCallback onOpen;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
void _onPressed() {
switch (status) {
case DownloadStatus.notDownloaded:
onDownload();
case DownloadStatus.fetchingDownload:
// do nothing.
break;
case DownloadStatus.downloading:
onCancel();
case DownloadStatus.downloaded:
onOpen();
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: const Stack(
children: [
/* ButtonShapeWidget and progress indicator */
],
),
);
}
}
```
Congratulations! You have a button that changes its display
depending on which phase the button is in: not downloaded,
fetching download, downloading, and downloaded.
Now, the user can tap to start a download, tap to cancel an
in-progress download, and tap to open a completed download.
## Interactive example
Run the app:
* Click the **GET** button to kick off a
simulated download.
* The button changes to a progress indicator
to simulate an in-progress download.
* When the simulated download is complete, the
button transitions to **OPEN**, to indicate
that the app is ready for the user
to open the downloaded asset.
<!-- start dartpad -->
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleCupertinoDownloadButton(),
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class ExampleCupertinoDownloadButton extends StatefulWidget {
const ExampleCupertinoDownloadButton({super.key});
@override
State<ExampleCupertinoDownloadButton> createState() =>
_ExampleCupertinoDownloadButtonState();
}
class _ExampleCupertinoDownloadButtonState
extends State<ExampleCupertinoDownloadButton> {
late final List<DownloadController> _downloadControllers;
@override
void initState() {
super.initState();
_downloadControllers = List<DownloadController>.generate(
20,
(index) => SimulatedDownloadController(onOpenDownload: () {
_openDownload(index);
}),
);
}
void _openDownload(int index) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Open App ${index + 1}'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Apps')),
body: ListView.separated(
itemCount: _downloadControllers.length,
separatorBuilder: (_, __) => const Divider(),
itemBuilder: _buildListItem,
),
);
}
Widget _buildListItem(BuildContext context, int index) {
final theme = Theme.of(context);
final downloadController = _downloadControllers[index];
return ListTile(
leading: const DemoAppIcon(),
title: Text(
'App ${index + 1}',
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleLarge,
),
subtitle: Text(
'Lorem ipsum dolor #${index + 1}',
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall,
),
trailing: SizedBox(
width: 96,
child: AnimatedBuilder(
animation: downloadController,
builder: (context, child) {
return DownloadButton(
status: downloadController.downloadStatus,
downloadProgress: downloadController.progress,
onDownload: downloadController.startDownload,
onCancel: downloadController.stopDownload,
onOpen: downloadController.openDownload,
);
},
),
),
);
}
}
@immutable
class DemoAppIcon extends StatelessWidget {
const DemoAppIcon({super.key});
@override
Widget build(BuildContext context) {
return const AspectRatio(
aspectRatio: 1,
child: FittedBox(
child: SizedBox(
width: 80,
height: 80,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.red, Colors.blue],
),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: Center(
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 40,
),
),
),
),
),
);
}
}
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
abstract class DownloadController implements ChangeNotifier {
DownloadStatus get downloadStatus;
double get progress;
void startDownload();
void stopDownload();
void openDownload();
}
class SimulatedDownloadController extends DownloadController
with ChangeNotifier {
SimulatedDownloadController({
DownloadStatus downloadStatus = DownloadStatus.notDownloaded,
double progress = 0.0,
required VoidCallback onOpenDownload,
}) : _downloadStatus = downloadStatus,
_progress = progress,
_onOpenDownload = onOpenDownload;
DownloadStatus _downloadStatus;
@override
DownloadStatus get downloadStatus => _downloadStatus;
double _progress;
@override
double get progress => _progress;
final VoidCallback _onOpenDownload;
bool _isDownloading = false;
@override
void startDownload() {
if (downloadStatus == DownloadStatus.notDownloaded) {
_doSimulatedDownload();
}
}
@override
void stopDownload() {
if (_isDownloading) {
_isDownloading = false;
_downloadStatus = DownloadStatus.notDownloaded;
_progress = 0.0;
notifyListeners();
}
}
@override
void openDownload() {
if (downloadStatus == DownloadStatus.downloaded) {
_onOpenDownload();
}
}
Future<void> _doSimulatedDownload() async {
_isDownloading = true;
_downloadStatus = DownloadStatus.fetchingDownload;
notifyListeners();
// Wait a second to simulate fetch time.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Shift to the downloading phase.
_downloadStatus = DownloadStatus.downloading;
notifyListeners();
const downloadProgressStops = [0.0, 0.15, 0.45, 0.8, 1.0];
for (final stop in downloadProgressStops) {
// Wait a second to simulate varying download speeds.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Update the download progress.
_progress = stop;
notifyListeners();
}
// Wait a second to simulate a final delay.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Shift to the downloaded state, completing the simulation.
_downloadStatus = DownloadStatus.downloaded;
_isDownloading = false;
notifyListeners();
}
}
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.downloadProgress = 0.0,
required this.onDownload,
required this.onCancel,
required this.onOpen,
this.transitionDuration = const Duration(milliseconds: 500),
});
final DownloadStatus status;
final double downloadProgress;
final VoidCallback onDownload;
final VoidCallback onCancel;
final VoidCallback onOpen;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
void _onPressed() {
switch (status) {
case DownloadStatus.notDownloaded:
onDownload();
case DownloadStatus.fetchingDownload:
// do nothing.
break;
case DownloadStatus.downloading:
onCancel();
case DownloadStatus.downloaded:
onOpen();
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: Stack(
alignment: Alignment.center,
children: [
ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
if (_isDownloading)
const Icon(
Icons.stop,
size: 14,
color: CupertinoColors.activeBlue,
),
],
),
),
),
],
),
);
}
}
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ? 'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activeBlue,
),
),
),
),
);
}
}
@immutable
class ProgressIndicatorWidget extends StatelessWidget {
const ProgressIndicatorWidget({
super.key,
required this.downloadProgress,
required this.isDownloading,
required this.isFetching,
});
final double downloadProgress;
final bool isDownloading;
final bool isFetching;
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 1,
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: downloadProgress),
duration: const Duration(milliseconds: 200),
builder: (context, progress, child) {
return CircularProgressIndicator(
backgroundColor: isDownloading
? CupertinoColors.lightBackgroundGray
: Colors.white.withOpacity(0),
valueColor: AlwaysStoppedAnimation(isFetching
? CupertinoColors.lightBackgroundGray
: CupertinoColors.activeBlue),
strokeWidth: 2,
value: isFetching ? null : progress,
);
},
),
);
}
}
```
| website/src/cookbook/effects/download-button.md/0 | {
"file_path": "website/src/cookbook/effects/download-button.md",
"repo_id": "website",
"token_count": 9113
} | 1,295 |
---
title: Build a form with validation
description: How to build a form that validates input.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/forms/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:
1. Create a `Form` with a `GlobalKey`.
2. Add a `TextFormField` with validation logic.
3. Create a button to validate and submit the form.
## 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-excerpt "lib/form.dart"?>
```dart
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.
],
),
);
}
}
```
{{site.alert.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.
{{site.alert.end}}
## 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-excerpt "lib/main.dart (TextFormField)"?>
```dart
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;
},
),
```
## 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-excerpt "lib/main.dart (ElevatedButton)" replace="/^child\: //g"?>
```dart
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'),
),
```
### 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`.
## Interactive example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
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'),
),
),
],
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/form-validation.gif" alt="Form Validation Demo" class="site-mobile-screenshot" />
</noscript>
To learn how to retrieve these values, check out the
[Retrieve the value of a text field][] recipe.
[Retrieve the value of a text field]: /cookbook/forms/retrieve-input
[`Form`]: {{site.api}}/flutter/widgets/Form-class.html
[`Form.of()`]: {{site.api}}/flutter/widgets/Form/of.html
[`FormState`]: {{site.api}}/flutter/widgets/FormState-class.html
[`GlobalKey`]: {{site.api}}/flutter/widgets/GlobalKey-class.html
[`TextFormField`]: {{site.api}}/flutter/material/TextFormField-class.html
| website/src/cookbook/forms/validation.md/0 | {
"file_path": "website/src/cookbook/forms/validation.md",
"repo_id": "website",
"token_count": 2851
} | 1,296 |
---
title: Set up universal links for iOS
description: How set up universal links for an iOS application built with Flutter
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="codelabs/deeplink_cookbook"?>
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.
## 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.
1. To create a new application, type `flutter create <app-name>`.
```shell
$ flutter create deeplink_cookbook
```
2. To include the `go_router` package as a dependency,
run `flutter pub add`:
```terminal
$ flutter pub add go_router
```
3. To handle the routing, create a `GoRouter` object in the `main.dart` file:
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
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')),
),
),
],
),
],
);
```
## 2. Adjust iOS build settings
1. Launch Xcode.
1. Open the `ios/Runner.xcworkspace` file inside the project's `ios` folder.
1. Navigate to the `Info` Plist file in the `ios/Runner` folder.
<img src="/assets/images/docs/cookbook/set-up-universal-links-info-plist.png" alt="Xcode info.Plist screenshot" width="100%" />
1. In the `Info` property list, control-click at the list to add a row.
1. Control-click the newly added row and turn on the **Raw Keys and Values** mode
1. Update the key to `FlutterDeepLinkingEnabled` with a `Boolean` value set to `YES`.
<img src="/assets/images/docs/cookbook/set-up-universal-links-flutterdeeplinkingenabled.png" alt="flutter deeplinking enabled screenshot" width="100%" />
{{site.alert.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.
{{site.alert.end}}
1. Click the top-level **Runner**.
1. Click **Signing & Capabilities**.
1. Click **+ Capability** to add a new domain.
1. Click **Associated Domains**.
<img src="/assets/images/docs/cookbook/set-up-universal-links-associated-domains.png" alt="Xcode associated domains screenshot" width="100%" />
1. In the **Associated Domains** section, click **+**.
1. Enter `applinks:<web domain>`. Replace `<web domain>` with your own domain name.
<img src="/assets/images/docs/cookbook/set-up-universal-links-add-associated-domains.png" alt="Xcode add associated domains screenshot" width="100%" />
You have finished configuring the application for deep linking.
## 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.
### App ID
Apple formats the app ID as `<team id>.<bundle id>`.
* Locate the bundle ID in the Xcode project.
* Locate the team ID in the [developer account][].
**For example:** Given a team ID of `S8QB4VV633`
and a bundle ID of `com.example.deeplinkCookbook`, The app ID is
`S8QB4VV633.com.example.deeplinkCookbook`.
### apple-app-site-association
The hosted file should have the following content:
```json
{
"applinks": {
"apps": [],
"details": [
{
"appID": "S8QB4VV633.com.example.deeplinkCookbook",
"paths": ["*"]
}
]
}
}
```
1. Set the `appID` value to `<team id>.<bundle id>`.
1. 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.
1. Host the file at a URL that resembles the following:
`<webdomain>/.well-known/apple-app-site-association`
1. Verify that your browser can access this file.
## Testing
{{site.alert.note}}
It might take up to 24 hours before Apple's
[Content Delivery Network](https://en.wikipedia.org/wiki/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][].
{{site.alert.end}}
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.
<img src="/assets/images/docs/cookbook/set-up-universal-links-simulator.png" alt="Simulator screenshot" width="50%" />
If using the Simulator, test using the Xcode CLI:
```terminal
$ xcrun simctl openurl booted https://<web domain>/details
```
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:
<img src="/assets/images/docs/cookbook/set-up-universal-links-simulator-deeplinked.png" alt="Deeplinked Simulator screenshot" width="50%" />
## Appendix
Source code: [deeplink_cookbook][]
[alternate mode section]: {{site.apple-dev}}/documentation/bundleresources/entitlements/com_apple_developer_associated-domains?language=objc
[deeplink_cookbook]: {{site.repo.organization}}/codelabs/tree/main/deeplink_cookbook
[developer account]: {{site.apple-dev}}/account
[Firebase Hosting]: {{site.firebase}}/docs/hosting
[go_router]: {{site.pub-pkg}}/go_router
[GitHub Pages]: https://pages.github.com
[uni_links]: {{site.pub-pkg}}/uni_links
| website/src/cookbook/navigation/set-up-universal-links.md/0 | {
"file_path": "website/src/cookbook/navigation/set-up-universal-links.md",
"repo_id": "website",
"token_count": 2341
} | 1,297 |
---
title: Play and pause a video
description: How to use the video_player plugin.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/plugins/play_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.
{{site.alert.warning}}
At this time,
the `video_player` plugin doesn't work with any desktop platform.
To learn more, check out the [`video_player`][] package.
{{site.alert.end}}
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:
1. Add the `video_player` dependency.
2. Add permissions to your app.
3. Create and initialize a `VideoPlayerController`.
4. Display the video player.
5. Play and pause the video.
## 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`:
```terminal
$ flutter pub add video_player
```
## 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.
### 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`.
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application ...>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
```
### iOS
For iOS, add the following to the `Info.plist` file found at
`<project root>/ios/Runner/Info.plist`.
```xml
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
```
{{site.alert.warning}}
The `video_player` plugin can only play asset videos in iOS simulators.
You must test network-hosted videos on physical iOS devices.
{{site.alert.end}}
## 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:
1. Create a `StatefulWidget` with a companion `State` class
2. Add a variable to the `State` class to store the `VideoPlayerController`
3. Add a variable to the `State` class to store the `Future` returned from
`VideoPlayerController.initialize`
4. Create and initialize the controller in the `initState` method
5. Dispose of the controller in the `dispose` method
<?code-excerpt "lib/main_step3.dart (VideoPlayerScreen)"?>
```dart
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();
}
}
```
## 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-excerpt "lib/main.dart (FutureBuilder)" replace="/body: //g;/,$//g"?>
```dart
// 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(),
);
}
},
)
```
## 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-excerpt "lib/main.dart (FAB)" replace="/^floatingActionButton: //g;/,$//g"?>
```dart
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,
),
)
```
## Complete example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
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,
),
),
);
}
}
```
[`AspectRatio`]: {{site.api}}/flutter/widgets/AspectRatio-class.html
[`AVPlayer`]: {{site.apple-dev}}/documentation/avfoundation/avplayer
[`ExoPlayer`]: https://google.github.io/ExoPlayer/
[`pause()`]: {{site.pub-api}}/video_player/latest/video_player/VideoPlayerController/pause.html
[`play()`]: {{site.pub-api}}/video_player/latest/video_player/VideoPlayerController/play.html
[`video_player`]: {{site.pub-pkg}}/video_player
[`VideoPlayer`]: {{site.pub-api}}/video_player/latest/video_player/VideoPlayer-class.html
| website/src/cookbook/plugins/play-video.md/0 | {
"file_path": "website/src/cookbook/plugins/play-video.md",
"repo_id": "website",
"token_count": 3700
} | 1,298 |
---
layout: toc
title: Data & backend
description: Content covering data and backend development in Flutter apps.
---
| website/src/data-and-backend/index.md/0 | {
"file_path": "website/src/data-and-backend/index.md",
"repo_id": "website",
"token_count": 29
} | 1,299 |
---
title: Build and release a Linux app to the Snap Store
description: How to prepare for and release a Linux app to the Snap store.
short-title: Linux
---
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][snap],
this page can help.
## Prerequisites
To build and publish to the Snap Store, you need the
following components:
* [Ubuntu][] OS, 18.04 LTS (or higher)
* [Snapcraft][] command line tool
* [LXD container manager][]
## Set up the build environment
Use the following instructions to set up your build environment.
### Install snapcraft
At the command line, run the following:
```terminal
$ sudo snap install snapcraft --classic
```
### Install LXD
To install LXD, use the following command:
```terminal
$ sudo snap install lxd
```
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.
```terminal
$ sudo lxd init
Would you like to use LXD clustering? (yes/no) [default=no]:
Do you want to configure a new storage pool? (yes/no) [default=yes]:
Name of the new storage pool [default=default]:
Name of the storage backend to use (btrfs, dir, lvm, zfs, ceph) [default=zfs]:
Create a new ZFS pool? (yes/no) [default=yes]:
Would you like to use an existing empty disk or partition? (yes/no) [default=no]:
Size in GB of the new loop device (1GB minimum) [default=5GB]:
Would you like to connect to a MAAS server? (yes/no) [default=no]:
Would you like to create a new local network bridge? (yes/no) [default=yes]:
What should the new bridge be called? [default=lxdbr0]:
What IPv4 address should be used? (CIDR subnet notation, "auto" or "none") [default=auto]:
What IPv6 address should be used? (CIDR subnet notation, "auto" or "none") [default=auto]:
Would you like LXD to be available over the network? (yes/no) [default=no]:
Would you like stale cached images to be updated automatically? (yes/no) [default=yes]
Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]:
```
On the first run, LXD might not be able to connect to its socket:
```terminal
An error occurred when trying to communicate with the 'LXD'
provider: cannot connect to the LXD socket
('/var/snap/lxd/common/lxd/unix.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:
```terminal
$ sudo usermod -a -G lxd <your username>
```
## 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.
## 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:
```yaml
name: super-cool-app
version: 0.1.0
summary: Super Cool App
description: Super Cool App that does everything!
confinement: strict
base: core22
grade: stable
slots:
dbus-super-cool-app: # adjust accordingly to your app name
interface: dbus
bus: session
name: org.bar.super_cool_app # adjust accordingly to your app name and
apps:
super-cool-app:
command: super_cool_app
extensions: [gnome] # gnome includes the libraries required by flutter
plugs:
- network
slots:
- dbus-super-cool-app
parts:
super-cool-app:
source: .
plugin: flutter
flutter-target: lib/main.dart # The main entry-point file of the application
```
The following sections explain the various pieces of the YAML file.
### Metadata
This section of the `snapcraft.yaml` file defines and
describes the application. The snap version is
derived (adopted) from the build section.
```yaml
name: super-cool-app
version: 0.1.0
summary: Super Cool App
description: Super Cool App that does everything!
```
### Grade, confinement, and base
This section defines how the snap is built.
```yaml
confinement: strict
base: core18
grade: stable
```
**Grade**
: Specifies the quality of the snap; this is relevant for
the publication step later.
**Confinement**
: Specifies what level of system resource access the snap
will have once installed on the end-user system.
Strict confinement limits the application access to
specific resources (defined by plugs in the `app` section).
**Base**
: Snaps are designed to be self-contained applications,
and therefore, they require their own private core root
filesystem known as `base`. The `base` keyword specifies
the version used to provide the minimal set of common libraries,
and mounted as the root filesystem for the application at runtime.
### 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.
```yaml
apps:
super-cool-app:
command: super_cool_app
extensions: [gnome]
```
**Command**
: Points to the binary, relative to the snap's root,
and runs when the snap is invoked.
**Extensions**
: A list of one or more extensions. Snapcraft extensions
are reusable components that can expose sets of libraries
and tools to a snap at build and runtime,
without the developer needing to have specific knowledge
of included frameworks. The `gnome` extension exposes
the GTK 3 libraries to the Flutter snap. This ensures a
smaller footprint and better integration with the system.
**Plugs**
: A list of one or more plugs for system interfaces.
These are required to provide necessary functionality
when snaps are strictly confined. This Flutter snap needs
access to the network.
**DBus interface**
: The [DBus interface][] provides a way for snaps to
communicate over DBus. The snap providing the DBus
service declares a slot with the well-known DBus name
and which bus it uses. Snaps wanting to communicate
with the providing snap's service declare a plug for
the providing snap. Note that a snap declaration is
needed for your snap to be delivered via the snap store
and claim this well-known DBus name (simply upload the
snap to the store and request a manual review and
a reviewer will take a look).
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.
```
dbus-super-cool-app: # adjust accordingly to your app name
interface: dbus
bus: session
name: dev.site.super_cool_app
```
### 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.
**nil** plugin
: Performs no action and the actual build process is
handled using a manual override.
**flutter** plugin
: Provides the necessary Flutter SDK tools so you can
use it without having to manually download and set up
the build tools.
```yaml
parts:
super-cool-app:
source: .
plugin: flutter
flutter-target: lib/main.dart # The main entry-point file of the application
```
## 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.
### 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:
```desktop
[Desktop Entry]
Name=Super Cool App
Comment=Super Cool App that does everything
Exec=super-cool-app
Icon=${SNAP}/meta/gui/super-cool-app.png # replace name to your app name
Terminal=false
Type=Application
Categories=Education; #adjust accordingly your snap category
```
Place your icon with .png extension in your Flutter
project under `<project root>/snap/gui/super-cool-app.png`.
## 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:
```terminal
$ snapcraft
```
To use the LXD container backend:
```terminal
$ snapcraft --use-lxd
```
## 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
## Publish
You can now publish the snap.
The process consists of the following:
1. Create a developer account at [snapcraft.io][], if you
haven't already done so.
1. Register the app's name. Registration can be done
either using the Snap Store Web UI portal, or from the
command line, as follows:
```terminal
$ snapcraft login
$ snapcraft register
```
1. Release the app. After reading the next section
to learn about selecting a Snap Store channel,
push the snap to the store:
```terminal
$ snapcraft upload --release=<channel> <file>.snap
```
### 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:
**Track**
: All snaps must have a default track called latest.
This is the implied track unless specified otherwise.
**Risk**
: Defines the readiness of the application.
The risk levels used in the snap store are:
`stable`, `candidate`, `beta`, and `edge`.
**Branch**
: Allows creation of short-lived snap
sequences to test bug-fixes.
### 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.
## Additional resources
You can learn more from the following links on the
[snapcraft.io][] site:
* [Channels][]
* [Environment variables][]
* [Interface management][]
* [Parts environment variables][]
* [Releasing to the Snap Store][]
* [Snapcraft extensions][]
* [Supported plugins][]
[Desktop shells]: {{site.repo.flutter}}/wiki/Desktop-shells
[Environment variables]: https://snapcraft.io/docs/environment-variables
[Flutter wiki]: {{site.repo.flutter}}/wiki/
[Interface management]: https://snapcraft.io/docs/interface-management
[DBus interface]: https://snapcraft.io/docs/dbus-interface
[Introduction to snapcraft]: https://snapcraft.io/blog/introduction-to-snapcraft
[LXD container manager]: https://linuxcontainers.org/lxd/downloads/
[Multipass virtualization manager]: https://multipass.run/
[Parts environment variables]: https://snapcraft.io/docs/parts-environment-variables
[Releasing to the Snap Store]: https://snapcraft.io/docs/releasing-to-the-snap-store
[Channels]: https://docs.snapcraft.io/channels
[snap]: https://snapcraft.io/store
[Snap documentation]: https://snapcraft.io/docs
[Snapcraft]: https://snapcraft.io/snapcraft
[snapcraft.io]: https://snapcraft.io/
[Snapcraft extensions]: https://snapcraft.io/docs/snapcraft-extensions
[Supported plugins]: https://snapcraft.io/docs/supported-plugins
[Ubuntu]: https://ubuntu.com/download/desktop
| website/src/deployment/linux.md/0 | {
"file_path": "website/src/deployment/linux.md",
"repo_id": "website",
"token_count": 3515
} | 1,300 |
---
title: Flutter for UIKit developers
description: Learn how to apply iOS and UIKit developer knowledge when building Flutter apps.
---
<?code-excerpt path-base="get-started/flutter-for/ios_devs"?>
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.
{{site.alert.note}}
If you have experience building apps with SwiftUI,
check out [Flutter for SwiftUI developers][] instead.
{{site.alert.end}}
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.
{% comment %}
TODO: Add talk about plugin system for interacting with OS and hardware
when [iOS and Apple hardware interactions with Flutter][] is released.
{% endcomment -%}
Flutter also makes a number of adaptations
to app behavior when running on iOS.
To learn how, see [Platform adaptations][].
{{site.alert.info}}
To integrate Flutter code into an **existing** iOS app,
check out [Add Flutter to existing app][].
{{site.alert.end}}
Use this guide as a cookbook.
Jump around and find questions that address your most relevant needs.
## Overview
As an introduction, watch the following video.
It outlines how Flutter works on iOS and how to use Flutter to build iOS apps.
<iframe class="full-width" src="{{site.yt.embed}}/ceMsPBbcEGg" title="Learn how to develop with Flutter as an iOS developer" {{site.yt.set}}></iframe>
### Views vs. Widgets
{{site.alert.secondary}}
How is react-style, or _declarative_,
programming different from the
traditional imperative style?
For a comparison, see [Introduction to declarative UI][].
{{site.alert.end}}
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][].
### 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 `StatefulWidget`s 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 common`StatelessWidget` is the `Text` widget.
If you look at the implementation of the `Text` widget,
you'll find it subclasses `StatelessWidget`.
<?code-excerpt "lib/text_widget.dart (TextWidget)" replace="/return const //g"?>
```dart
Text(
'I like Flutter!',
style: TextStyle(fontWeight: FontWeight.bold),
);
```
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-excerpt "lib/text_widget.dart (StatefulWidget)"?>
```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: '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),
),
);
}
}
```
### 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-excerpt "lib/layout.dart (SimpleWidget)"?>
```dart
@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'),
),
),
);
}
```
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][].
### 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-excerpt "lib/layout.dart (ToggleWidget)"?>
```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: '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),
),
);
}
}
```
### 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
`Animation`s 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-excerpt "lib/animation.dart"?>
```dart
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),
),
);
}
}
```
For more information, see [Animation & Motion widgets][],
the [Animations tutorial][], and the [Animations overview][].
### 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][].
[StackOverflow]: {{site.so}}/questions/46241071/create-signature-area-for-mobile-app-in-dart-flutter
<?code-excerpt "lib/canvas.dart"?>
```dart
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;
}
```
### 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.
### 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-excerpt "lib/custom.dart (CustomButton)"?>
```dart
class CustomButton extends StatelessWidget {
const CustomButton(this.label, {super.key});
final String label;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {},
child: Text(label),
);
}
}
```
Then use `CustomButton`,
just as you'd use any other Flutter widget:
<?code-excerpt "lib/custom.dart (UseCustomButton)"?>
```dart
@override
Widget build(BuildContext context) {
return const Center(
child: CustomButton('Hello'),
);
}
```
## Navigation
This section of the document discusses navigation
between pages of an app, the push and pop mechanism, and more.
### 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:
* Specify a `Map` of route names.
* Directly navigate to a route.
The following example builds a `Map.`
<?code-excerpt "lib/intent.dart (Map)"?>
```dart
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'),
},
),
);
}
```
Navigate to a route by `push`ing its name to the `Navigator`.
<?code-excerpt "lib/intent.dart (Push)"?>
```dart
Navigator.of(context).pushNamed('/b');
```
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 `await`ing 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-excerpt "lib/intent.dart (PushAwait)"?>
```dart
Object? coordinates = await Navigator.of(context).pushNamed('/location');
```
And then, inside your `location` route, once the user has selected their
location, `pop()` the stack with the result:
<?code-excerpt "lib/intent.dart (Pop)"?>
```dart
Navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392});
```
### 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`][].
### Manually pop back
Calling `SystemNavigator.pop()` from your Dart code
invokes the following iOS code:
```objc
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
if ([viewController isKindOfClass:[UINavigationController class]]) {
[((UINavigationController*)viewController) popViewControllerAnimated:NO];
}
```
If that doesn't do what you want, you can create your own
[platform channel][] to invoke arbitrary iOS code.
### 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-excerpt "lib/string_examples.dart (Strings)"?>
```dart
class Strings {
static const String welcomeMessage = 'Welcome To Flutter';
}
```
You can access your strings as such:
<?code-excerpt "lib/string_examples.dart (AccessString)" replace="/const //g"?>
```dart
Text(Strings.welcomeMessage);
```
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.
```yaml
dependencies:
flutter_localizations:
sdk: flutter
intl: any # Use version of intl from flutter_localizations.
```
To use the `flutter_localizations` package,
specify the `localizationsDelegates` and
`supportedLocales` on the app widget:
<?code-excerpt "lib/localizations_example.dart"?>
```dart
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
],
);
}
}
```
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.
### 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][].
## ViewControllers
This section of the document discusses the equivalent
of ViewController in Flutter and how to listen to
lifecycle events.
### 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 `Route`s
that represent different screens or pages,
or maybe different states or renderings of the same data.
### 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:
**`inactive`**
: The application is in an inactive state and is not receiving
user input. This event only works on iOS,
as there is no equivalent event on Android.
**`paused`**
: The application is not currently visible to the user,
is not responding to user input, but is running in the background.
**`resumed`**
: The application is visible and responding to user input.
**`suspending`**
: The application is suspended momentarily.
The iOS platform has no equivalent event.
For more details on the meaning of these states, see
[`AppLifecycleState` documentation][].
## Layouts
This section discusses different layouts in Flutter
and how they compare with UIKit.
### 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-excerpt "lib/listview.dart"?>
```dart
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()),
);
}
}
```
### 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-excerpt "lib/list_item_tapped.dart"?>
```dart
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()),
);
}
}
```
### 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 `ListView`s 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-excerpt "lib/listview_dynamic.dart"?>
```dart
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),
);
}
}
```
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-excerpt "lib/listview_builder.dart"?>
```dart
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);
},
),
);
}
}
```
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 `.add`s to it.
### 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-excerpt "lib/layout.dart (ListView)"?>
```dart
@override
Widget build(BuildContext context) {
return ListView(
children: const <Widget>[
Text('Row One'),
Text('Row Two'),
Text('Row Three'),
Text('Row Four'),
],
);
}
```
For more detailed docs on how to lay out widgets in Flutter,
see the [layout tutorial][].
## 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.
### 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:
1. 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-excerpt "lib/events.dart (onPressed)"?>
```dart
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
developer.log('click');
},
child: const Text('Button'),
);
}
```
2. If the Widget doesn't support event detection,
wrap the widget in a GestureDetector and pass a function
to the `onTap` parameter.
<?code-excerpt "lib/events.dart (onTap)"?>
```dart
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,
),
),
),
);
}
}
```
### Handling other gestures
Using `GestureDetector` you can listen
to a wide range of gestures such as:
* **Tapping**
**`onTapDown`**
: A pointer that might cause a tap has contacted the
screen at a particular location.
**`onTapUp`**
: A pointer that triggers a tap has stopped contacting the
screen at a particular location.
**`onTap`**
: A tap has occurred.
**`onTapCancel`**
: The pointer that previously triggered the `onTapDown`
won't cause a tap.
* **Double tapping**
**`onDoubleTap`**
: The user tapped the screen at the same location twice in
quick succession.
* **Long pressing**
**`onLongPress`**
: A pointer has remained in contact with the screen
at the same location for a long period of time.
* **Vertical dragging**
**`onVerticalDragStart`**
: A pointer has contacted the screen and might begin to
move vertically.
**`onVerticalDragUpdate`**
: A pointer in contact with the screen
has moved further in the vertical direction.
**`onVerticalDragEnd`**
: A pointer that was previously in contact with the
screen and moving vertically is no longer in contact
with the screen and was moving at a specific velocity
when it stopped contacting the screen.
* **Horizontal dragging**
**`onHorizontalDragStart`**
: A pointer has contacted the screen and might begin
to move horizontally.
**`onHorizontalDragUpdate`**
: A pointer in contact with the screen
has moved further in the horizontal direction.
**`onHorizontalDragEnd`**
: A pointer that was previously in contact with the
screen and moving horizontally is no longer in
contact with the screen.
The following example shows a `GestureDetector`
that rotates the Flutter logo on a double tap:
<?code-excerpt "lib/events.dart (SampleApp)"?>
```dart
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,
),
),
),
),
);
}
}
```
## 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.
### 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-excerpt "lib/theme.dart (Theme)"?>
```dart
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(),
);
}
}
```
### 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.
```yaml
fonts:
- family: MyCustomFont
fonts:
- asset: fonts/MyCustomFont.ttf
- style: italic
```
Then assign the font to your `Text` widget:
<?code-excerpt "lib/text.dart (CustomFont)"?>
```dart
@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'),
),
),
);
}
```
### 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:
* `color`
* `decoration`
* `decorationColor`
* `decorationStyle`
* `fontFamily`
* `fontSize`
* `fontStyle`
* `fontWeight`
* `hashCode`
* `height`
* `inherit`
* `letterSpacing`
* `textBaseline`
* `wordSpacing`
### 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:
```
my-assets/data.json
```
Declare the asset in the `pubspec.yaml` file:
```yaml
assets:
- my-assets/data.json
```
And then access it from code using an [`AssetBundle`][]:
<?code-excerpt "lib/asset_bundle.dart"?>
```dart
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('my-assets/data.json');
}
```
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:
```
images/my_icon.png // Base: 1.0x image
images/2.0x/my_icon.png // 2.0x image
images/3.0x/my_icon.png // 3.0x image
```
Next, declare these images in the `pubspec.yaml` file:
```yaml
assets:
- images/my_icon.png
```
You can now access your images using `AssetImage`:
<?code-excerpt "lib/images.dart (AssetImage)"?>
```dart
AssetImage('images/a_dot_burr.jpeg')
```
or directly in an `Image` widget:
<?code-excerpt "lib/images.dart (Imageasset)"?>
```dart
@override
Widget build(BuildContext context) {
return Image.asset('images/my_image.png');
}
```
For more details, see
[Adding Assets and Images in Flutter][].
## Form input
This section discusses how to use forms in Flutter
and how they compare with UIKit.
### 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-excerpt "lib/form.dart (MyFormState)"?>
```dart
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),
),
);
}
}
```
You can find more information and the full code listing in
[Retrieve the value of a text field][],
from the [Flutter cookbook][].
### 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-excerpt "lib/form.dart (InputHint)" replace="/return const //g;/;//g"?>
```dart
Center(
child: TextField(
decoration: InputDecoration(hintText: 'This is a hint'),
),
)
```
### 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-excerpt "lib/validation_errors.dart"?>
```dart
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,
),
),
),
);
}
}
```
## Threading & asynchronicity
This section discusses concurrency in Flutter and
how it compares with UIKit.
### Writing asynchronous code
Dart has a single-threaded execution model,
with support for `Isolate`s
(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-excerpt "lib/async.dart (loadData)"?>
```dart
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);
});
}
```
Once the `await`ed 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-excerpt "lib/async.dart"?>
```dart
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);
},
),
);
}
}
```
Refer to the next section for more information on doing work
in the background, and how Flutter differs from iOS.
### 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-excerpt "lib/async.dart (loadData)"?>
```dart
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);
});
}
```
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 `Isolate`s 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-excerpt "lib/isolates.dart (loadData)"?>
```dart
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>>>;
}
```
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-excerpt "lib/isolates.dart"?>
```dart
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(),
);
}
}
```
### 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`:
```terminal
flutter pub add http
```
To make a network call,
call `await` on the `async` function `http.get()`:
<?code-excerpt "lib/progress.dart (loadData)"?>
```dart
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);
});
}
```
### 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-excerpt "lib/progress.dart"?>
```dart
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(),
);
}
}
```
[Flutter for SwiftUI developers]: /get-started/flutter-for/swiftui-devs
[Add Flutter to existing app]: /add-to-app
[Adding Assets and Images in Flutter]: /ui/assets/assets-and-images
[Animation & Motion widgets]: /ui/widgets/animation
[Animations overview]: /ui/animations
[Animations tutorial]: /ui/animations/tutorial
[Apple's iOS design language]: {{site.apple-dev}}/design/resources
[`AppLifecycleState` documentation]: {{site.api}}/flutter/dart-ui/AppLifecycleState.html
[arb]: {{site.github}}/googlei18n/app-resource-bundle
[`AssetBundle`]: {{site.api}}/flutter/services/AssetBundle-class.html
[composing]: /resources/architectural-overview#composition
[Cupertino library]: {{site.api}}/flutter/cupertino/cupertino-library.html
[Cupertino widgets]: /ui/widgets/cupertino
[`devicePixelRatio`]: {{site.api}}/flutter/dart-ui/FlutterView/devicePixelRatio.html
[existing plugin]: {{site.pub}}/flutter
[Flutter concurrency for Swift developers]: /get-started/flutter-for/dart-swift-concurrency
[Flutter cookbook]: /cookbook
[`http` package]: {{site.pub-pkg}}/http
[Human Interface Guidelines]: {{site.apple-dev}}/ios/human-interface-guidelines/overview/themes/
[internationalization guide]: /ui/accessibility-and-internationalization/internationalization
[`intl`]: {{site.pub-pkg}}/intl
[`intl_translation`]: {{site.pub-pkg}}/intl_translation
[Introduction to declarative UI]: /get-started/flutter-for/declarative
[layout tutorial]: /ui/widgets/layout
[`Localizations`]: {{site.api}}/flutter/widgets/Localizations-class.html
[Material Components]: {{site.material}}/develop/flutter/
[Material Design guidelines]: {{site.material}}/styles/
[optimized for all platforms]: {{site.material2}}/design/platform-guidance/cross-platform-adaptation.html#cross-platform-guidelines
[Platform adaptations]: /platform-integration/platform-adaptations
[platform channel]: /platform-integration/platform-channels
[pub.dev]: {{site.pub}}/flutter/packages
[Retrieve the value of a text field]: /cookbook/forms/retrieve-input
[`TextEditingController`]: {{site.api}}/flutter/widgets/TextEditingController-class.html
[`url_launcher`]: {{site.pub-pkg}}/url_launcher
[widget]: /resources/architectural-overview#widgets
[widget catalog]: /ui/widgets/layout
[`Window.locale`]: {{site.api}}/flutter/dart-ui/Window/locale.html
[Learning Dart as a Swift Developer]: {{site.dart-site}}/guides/language/coming-from/swift-to-dart
| website/src/get-started/flutter-for/uikit-devs.md/0 | {
"file_path": "website/src/get-started/flutter-for/uikit-devs.md",
"repo_id": "website",
"token_count": 20032
} | 1,301 |
## Get the Flutter SDK {#get-sdk}
{% include docs/china-notice.md %}
To install the Flutter SDK on your Linux system,
use one of the following methods.
### Method 1: Install Flutter using snapd
This offers the most direct method to install
the Flutter SDK on your Linux system.
To learn about using snapd, check [Installing snapd][].
After you install `snapd`, [install Flutter from the Snap Store][] or
run the following command:
```terminal
$ sudo snap install flutter --classic
```
{{site.alert.note}}
After you install Flutter with `snapd`,
display your Flutter SDK path with the following command:
```terminal
$ flutter sdk-path
```
{{site.alert.end}}
### Method 2: Manual installation
If you aren't using `snapd`, follow these steps to install Flutter.
1. Download the installation bundle for the latest
{{site.sdk.channel}} release of the Flutter SDK:
[(loading...)](#){:.download-latest-link-{{os}}.btn.btn-primary}
You can find older builds and other release channels in the [SDK archive][].
1. Extract the downloaded file to a location of your choice:
```terminal
$ cd ~/development
$ tar xf ~/Downloads/flutter_{{os}}_vX.X.X-{{site.sdk.channel}}.tar.xz
```
1. Add the `flutter` tool to your path:
```terminal
$ export PATH="$PATH:`pwd`/flutter/bin"
```
This command sets your `PATH` environment variable for the current
terminal window only.
To add Flutter as permanent part of your path,
check out [Update your path][].
1. (Optional) Pre-download development binaries:
```terminal
$ flutter precache
```
To find additional download options, run `flutter help precache`.
{{site.alert.note}}
To update an existing version of Flutter, see [Upgrading Flutter][].
{{site.alert.end}}
### Verify your install with `flutter doctor`
After installing Flutter, run `flutter doctor`.
```terminal
$ flutter doctor
```
This command checks your environment and displays a report in the
terminal window.
Flutter bundles the Dart SDK. You don't need to install Dart.
To get greater detail on what you need to fix, add the `-v` flag:
```terminal
$ flutter doctor -v
```
Review the output for further tasks to perform.
An example would be the text shown in **bold**.
The `flutter doctor -v` output might resemble the following:
{% comment %}
Need to use HTML for this code block to get the replacements
and boldface to work.
{% endcomment
-%}
<pre>
[-] Android toolchain - develop for Android devices
• Android SDK at /Users/dash/Library/Android/sdk
<strong>✗ Android SDK is missing command line tools; download from https://goo.gl/XxQghQ</strong>
• Try re-installing or updating your Android SDK,
visit /setup/#android-setup for detailed instructions.
</pre>
The following sections describe how to perform these tasks
and finish the setup process.
After completing the outlined tasks,
run the `flutter doctor` command again.
{% include_relative _analytics.md %}
[Flutter repo]: {{site.repo.flutter}}
[install Flutter from the Snap Store]: https://snapcraft.io/flutter
[Installing snapd]: https://snapcraft.io/docs/installing-snapd
[SDK archive]: /release/archive
[Update your path]: #update-your-path
[Upgrading Flutter]: /release/upgrade
| website/src/get-started/install/_deprecated/_get-sdk-linux.md/0 | {
"file_path": "website/src/get-started/install/_deprecated/_get-sdk-linux.md",
"repo_id": "website",
"token_count": 1010
} | 1,302 |
---
title: Flutter and Dart team job openings
description: Open job listings for the Flutter and Dart teams.
---
The Flutter and Dart teams aren't currently hiring.
Thanks for your interest!
{% comment %}
We are hiring on the Flutter and Dart teams!
The following jobs are open:
## Software Engineering
* [Android Engineer](/jobs/android)
* [Android Technical Lead](/jobs/android_tl)
* [iOS Engineer](/jobs/ios)
{% endcomment %}
| website/src/jobs/index.md/0 | {
"file_path": "website/src/jobs/index.md",
"repo_id": "website",
"token_count": 122
} | 1,303 |
---
title: Shader compilation jank
short-title: Shader jank
description: What is shader jank and how to minimize it.
---
{% include docs/performance.md %}
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.
[Impeller]: {{site.repo.flutter}}/wiki/Impeller
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.
## 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.
{:width="100%"}
## 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.
## 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:
<ol markdown="1">
<li markdown="1">Run the app with `--cache-sksl` turned on
to capture shaders in SkSL:
```terminal
flutter run --profile --cache-sksl
```
If the same app has been previously run
without `--cache-sksl`, then the
`--purge-persistent-cache` flag might be needed:
```terminal
flutter run --profile --cache-sksl --purge-persistent-cache
```
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.
</li>
<li markdown="1"> Play with the app to trigger as many animations
as needed; particularly those with compilation jank.
</li>
<li markdown="1"> 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.
</li>
<li markdown="1"> Build the app with SkSL warm-up using the following,
as appropriate:
```terminal
flutter build ios --bundle-sksl-path flutter_01.sksl.json
```
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`).
</li>
<li markdown="1"> Test the newly built app.
</li>
</ol>
Alternatively, you can write some integration tests to
automate the first three steps using a single command.
For example:
```terminal
flutter drive --profile --cache-sksl --write-sksl-on-exit flutter_01.sksl.json -t test_driver/app.dart
```
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.
[integration tests]: /cookbook/testing/integration/introduction
{{site.alert.note}}
The integration_test package is now the recommended way
to write integration tests. Refer to the
[Integration testing](/testing/integration-tests/)
page for details.
{{site.alert.end}}
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.
[Flutter Gallery]: {{site.repo.flutter}}/tree/main/dev/integration_tests/flutter_gallery
[`flutter_gallery_sksl_warmup__transition_perf`]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/flutter_gallery_sksl_warmup__transition_perf.dart
[`flutter_gallery_sksl_warmup__transition_perf_e2e_ios32`]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/flutter_gallery_sksl_warmup__transition_perf_e2e_ios32.dart
[`transitions_perf_test.dart`]: {{site.repo.flutter}}/blob/master/dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart
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.
| website/src/perf/shader.md/0 | {
"file_path": "website/src/perf/shader.md",
"repo_id": "website",
"token_count": 2041
} | 1,304 |
---
title: "Restore state on Android"
description: "How to restore the state of your Android app after it's been killed by the OS."
---
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.
{{site.alert.secondary}}
**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.
{{site.alert.end}}
[state]: /data-and-backend/state-mgmt/ephemeral-vs-app
## Overview
You can enable state restoration with just a few tasks:
1. 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.
2. 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.
3. 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.
[a bit of extra setup]: {{site.api}}/flutter/services/RestorationManager-class.html#state-restoration-on-ios
[`restorationId`]: {{site.api}}/flutter/widgets/RestorationScope/restorationId.html
[`restorationScopeId`]: {{site.api}}/flutter/widgets/RestorationScope/restorationScopeId.html
[`RestorationMixin`]: {{site.api}}/flutter/widgets/RestorationMixin-mixin.html
[`RestorationScope`]: {{site.api}}/flutter/widgets/RestorationScope-class.html
[`restoreState`]: {{site.api}}/flutter/widgets/RestorationMixin/restoreState.html
[VeggieSeasons]: {{site.repo.samples}}/tree/main/veggieseasons
## 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.
## 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.
{{site.alert.warning}}
Don't forget to reenable
storing state on your device once you are
finished with testing!
{{site.alert.end}}
[Testing state restoration]: {{site.api}}/flutter/services/RestorationManager-class.html#testing-state-restoration
[`RestorationBucket`]: {{site.api}}/flutter/services/RestorationBucket-class.html
[`RestorationManager`]: {{site.api}}/flutter/services/RestorationManager-class.html
[services]: {{site.api}}/flutter/services/services-library.html
## Other resources
For further information on state restoration,
check out the following resources:
* For an example that implements state restoration,
check out [VeggieSeasons][], a sample app written
for iOS that uses Cupertino widgets. An iOS app requires
[a bit of extra setup][] in Xcode, but the restoration
classes otherwise work the same on both iOS and Android.<br>
The following list links to relevant parts of the VeggieSeasons
example:
* [Defining a `RestorablePropery` as an instance property]({{site.repo.samples}}/blob/604c82cd7c9c7807ff6c5ca96fbb01d44a4f2c41/veggieseasons/lib/widgets/trivia.dart#L33-L37)
* [Registering the properties]({{site.repo.samples}}/blob/604c82cd7c9c7807ff6c5ca96fbb01d44a4f2c41/veggieseasons/lib/widgets/trivia.dart#L49-L54)
* [Updating the property values]({{site.repo.samples}}/blob/604c82cd7c9c7807ff6c5ca96fbb01d44a4f2c41/veggieseasons/lib/widgets/trivia.dart#L108-L109)
* [Using property values in build]({{site.repo.samples}}/blob/604c82cd7c9c7807ff6c5ca96fbb01d44a4f2c41/veggieseasons/lib/widgets/trivia.dart#L205-L210)<br>
* To learn more about short term and long term state,
check out [Differentiate between ephemeral state
and app state][state].
* You might want to check out packages on pub.dev that
perform state restoration, such as [`statePersistence`][].
* For more information on navigation and the
`go_router` package, check out [Navigation and routing][].
[`RestorableProperty`]: {{site.api}}/flutter/widgets/RestorableProperty-class.html
[`restorablePush`]: {{site.api}}/flutter/widgets/Navigator/restorablePush.html
[`ScrollView`]: {{site.api}}/flutter/widgets/ScrollView/restorationId.html
[`statePersistence`]: {{site.pub-pkg}}/state_persistence
[`TextField`]: {{site.api}}/flutter/material/TextField/restorationId.html
[`restorablePush`]: {{site.api}}/flutter/widgets/Navigator/restorablePush.html
[`go_router`]: {{site.pub}}/packages/go_router
[Navigation and routing]: /ui/navigation
| website/src/platform-integration/android/restore-state-android.md/0 | {
"file_path": "website/src/platform-integration/android/restore-state-android.md",
"repo_id": "website",
"token_count": 2222
} | 1,305 |
---
title: "Restore state on iOS"
description: "How to restore the state of your iOS app after it's been killed by the OS."
---
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.
[a bit of extra setup]: {{site.api}}/flutter/services/RestorationManager-class.html#state-restoration-on-ios
[`RestorationManager`]: {{site.api}}/flutter/services/RestorationManager-class.html
[State restoration on Android]: /platform-integration/android/restore-state-android
[VeggieSeasons]: {{site.repo.samples}}/tree/main/veggieseasons
| website/src/platform-integration/ios/restore-state-ios.md/0 | {
"file_path": "website/src/platform-integration/ios/restore-state-ios.md",
"repo_id": "website",
"token_count": 296
} | 1,306 |
---
title: Web FAQ
description: Some gotchas and differences when writing or running web apps in Flutter.
---
### 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:
* Progressive Web Apps
* Single Page Apps
* Existing Flutter mobile apps
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][].
### 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]({{site.main-url}}),
[dart.dev]({{site.dart-site}}), and [pub.dev]({{site.pub}}). 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.
### How do I create an app that also runs on the web?
See [building a web app with Flutter][].
### 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.
### 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.
### Which web browsers are supported by Flutter?
Flutter web apps can run on the following browsers:
* Chrome (mobile & desktop)
* Safari (mobile & desktop)
* Edge (mobile & desktop)
* Firefox (mobile & desktop)
During development, Chrome (on macOS, Windows, and Linux) and Edge (on Windows)
are supported as the default browsers for debugging your app.
### 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.
### How do I build a responsive app for the web?
See [Creating responsive apps][].
### 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.
### 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]({{site.dart-site}}).
### 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.
### 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:
```html
<iframe src="URL"></iframe>
```
If you encounter problems, please [file an issue][].
### How do I debug a web app?
Use [Flutter DevTools][] for the following tasks:
* [Debugging][]
* [Logging][]
* [Running Flutter inspector][]
Use [Chrome DevTools][] for the following tasks:
* [Generating event timeline][]
* [Analyzing performance][]—make sure to use a
profile build
### 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.
### How do I deploy a web app?
See [Preparing a web app for release][].
### Does `Platform.is` work on the web?
Not currently.
[Analyzing performance]: {{site.developers}}/web/tools/chrome-devtools/evaluate-performance
[building a web app with Flutter]: /platform-integration/web/building
[Chrome DevTools]: {{site.developers}}/web/tools/chrome-devtools
[Creating responsive apps]: /ui/layout/responsive/adaptive-responsive
[Debugging]: /tools/devtools/debugger
[file an issue]: {{site.repo.flutter}}/issues/new?title=[web]:+%3Cdescribe+issue+here%3E&labels=%E2%98%B8+platform-web&body=Describe+your+issue+and+include+the+command+you%27re+running,+flutter_web%20version,+browser+version
[Flutter DevTools]: /tools/devtools/overview
[Generating event timeline]: {{site.developers}}/web/tools/chrome-devtools/evaluate-performance/performance-reference
[`http`]: {{site.pub}}/packages/http
[`iframe`]: https://html.com/tags/iframe/
[isolates]: {{site.dart-site}}/guides/language/concurrency
[Issue 32248]: {{site.repo.flutter}}/issues/32248
[Logging]: /tools/devtools/logging
[Preparing a web app for release]: /deployment/web
[Running Flutter inspector]: /tools/devtools/inspector
[Upgrading from package:flutter_web to the Flutter SDK]: {{site.repo.flutter}}/wiki/Upgrading-from-package:flutter_web-to-the-Flutter-SDK
[widget tests]: /testing/overview#widget-tests
[Web support for Flutter]: /platform-integration/web
[web workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
[run your web apps in any supported browser]: /platform-integration/web/building#create-and-run
[Integration testing]: /testing/integration-tests#running-in-a-browser
[documentation for conditional imports]: {{site.dart-site}}/guides/libraries/create-library-packages#conditionally-importing-and-exporting-library-files
| website/src/platform-integration/web/faq.md/0 | {
"file_path": "website/src/platform-integration/web/faq.md",
"repo_id": "website",
"token_count": 1775
} | 1,307 |
---
title: External windows in Flutter Windows apps
description: Special considerations for adding external windows to Flutter apps
---
# Windows lifecycle
## Who is affected
Windows applications built against Flutter versions after 3.13 that open non-Flutter windows.
## Overview
When adding a non-Flutter window to a Flutter Windows app, it will not be part
of the logic for application lifecycle state updates by default. For example,
this means that when the external window is shown or hidden, the app lifecycle
state will not appropriately update to inactive or hidden. As a result, the app
may receive incorrect lifecycle state changes through
[WidgetsBindingObserver.didChangeAppLifecycle][].
# What do I need to do?
To add the external window to this application logic,
the window's `WndProc` procedure
must invoke `FlutterEngine::ProcessExternalWindowMessage`.
To achieve this, add the following code to a window message handler function:
```diff
LRESULT Window::Messagehandler(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
+ std::optional<LRESULT> result = flutter_controller_->engine()->ProcessExternalWindowMessage(hwnd, msg, wparam, lparam);
+ if (result.has_value()) {
+ return *result;
+ }
// Original contents of WndProc...
}
```
[documentation of this breaking change.]: /release/breaking-changes/win_lifecycle_process_function
[WidgetsBindingObserver.didChangeAppLifecycle]: {{site.api}}/flutter/widgets/WidgetsBindingObserver/didChangeAppLifecycleState.html
| website/src/platform-integration/windows/extern_win.md/0 | {
"file_path": "website/src/platform-integration/windows/extern_win.md",
"repo_id": "website",
"token_count": 427
} | 1,308 |
---
title: Deprecated API removed after v2.10
description: >
After reaching end of life, the following deprecated APIs
were removed from Flutter.
---
## Summary
In accordance with Flutter's [Deprecation Policy][],
deprecated APIs that reached end of life after the
2.10 stable release have been removed.
All affected APIs have been compiled into this
primary source to aid in migration. A
[quick reference sheet][] is available as well.
[Deprecation Policy]: {{site.repo.flutter}}/wiki/Tree-hygiene#deprecation
[quick reference sheet]: /go/deprecations-removed-after-2-10
## Changes
This section lists the deprecations by affected class.
---
### `maxLengthEnforced` of `TextField` & related classes
Supported by Flutter Fix: yes
`maxLengthEnforced` was deprecated in v1.25.
Use `maxLengthEnforcement` instead.
Where `maxLengthEnforced` was true, replace with `MaxLengthEnforcement.enforce`.
Where `maxLengthEnforced` was false, replace with `MaxLengthEnforcement.none`.
This change allows more behaviors to be specified beyond the original binary
choice, adding `MaxLengthEnforcement.truncateAfterCompositionEnds` as an
additional option.
The following classes all have the same change of API:
- `TextField`
- `TextFormField`
- `CupertinoTextField`
**Migration guide**
[In-depth migration guide available][]
Code before migration:
```dart
const TextField textField = TextField(maxLengthEnforced: true);
const TextField textField = TextField(maxLengthEnforced: false);
final lengthEnforced = textField.maxLengthEnforced;
const TextFormField textFormField = TextFormField(maxLengthEnforced: true);
const TextFormField textFormField = TextFormField(maxLengthEnforced: false);
final lengthEnforced = textFormField.maxLengthEnforced;
const CupertinoTextField cupertinoTextField = CupertinoTextField(maxLengthEnforced: true);
const CupertinoTextField cupertinoTextField = CupertinoTextField(maxLengthEnforced: false);
final lengthEnforced = cupertinoTextField.maxLengthEnforced;
```
Code after migration:
```dart
const TextField textField = TextField(maxLengthEnforcement: MaxLengthEnforcement.enforce);
const TextField textField = TextField(maxLengthEnforcement: MaxLengthEnforcement.none);
final lengthEnforced = textField.maxLengthEnforcement;
const TextFormField textFormField = TextFormField(maxLengthEnforcement: MaxLengthEnforcement.enforce);
const TextFormField textFormField = TextFormField(maxLengthEnforcement: MaxLengthEnforcement.none);
final lengthEnforced = textFormField.maxLengthEnforcement;
const CupertinoTextField cupertinoTextField = CupertinoTextField(maxLengthEnforcement: MaxLengthEnforcement.enforce);
const CupertinoTextField cupertinoTextField = CupertinoTextField(maxLengthEnforcement: MaxLengthEnforcement.none);
final lengthEnforced = cupertinoTextField.maxLengthEnforcement;
```
**References**
API documentation:
* [`TextField`][]
* [`TextFormField`][]
* [`CupertinoTextField`][]
Relevant issues:
* [Issue 67898]({{site.repo.flutter}}/issues/67898)
Relevant PRs:
* Deprecated in [#68086]({{site.repo.flutter}}/pull/68086)
* Removed in [#98539]({{site.repo.flutter}}/pull/98539)
[In-depth migration guide available]: /release/breaking-changes/use-maxLengthEnforcement-instead-of-maxLengthEnforced
[`TextField`]: {{site.api}}/flutter/material/TextField-class.html
[`TextFormField`]: {{site.api}}/flutter/material/TextFormField-class.html
[`CupertinoTextField`]: {{site.api}}/flutter/cupertino/CupertinoTextField-class.html
---
### `VelocityTracker` constructor
Supported by Flutter Fix: yes
The default constructor for `VelocityTracker`was deprecated in v1.22.
The `VelocityTracker.withKind()` should be used instead. This allows for a
`PointerDeviceKind` to be specified for the tracker. The previous default for
`VelocityTracker.kind` was `PointerDeviceKind.touch`.
**Migration guide**
Code before migration:
```dart
final VelocityTracker tracker = VelocityTracker();
```
Code after migration:
```dart
final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch);
```
**References**
API documentation:
* [`VelocityTracker`][]
* [`PointerDeviceKind`][]
Relevant PRs:
* Deprecated in [#66043]({{site.repo.flutter}}/pull/66043)
* Removed in [#98541]({{site.repo.flutter}}/pull/98541)
[`VelocityTracker`]: {{site.api}}/flutter/gestures/VelocityTracker-class.html
[`PointerDeviceKind`]: {{site.api}}/flutter/dart-ui/PointerDeviceKind.html
---
### `DayPicker` & `MonthPicker`
Supported by Flutter Fix: no
The `DayPicker` and `MonthPicker` widgets were first deprecated in v1.15, and
then extended in v1.26.
They have been replaced by one comprehensive widget, `CalendarDatePicker`.
These widgets were displayed using the `showDatePicker` method. This method was
migrated to present the new `CalendarDatePicker` before this release, and so
their final removal should not necessitate further action.
**References**
Design document:
* [Material Date Picker Redesign][]
API documentation:
* [`CalendarDatePicker`][]
* [`showDatePicker`][]
Relevant issues:
* [Issue 50133]({{site.repo.flutter}}/issues/50133)
Relevant PRs:
* Deprecated in [#50546]({{site.repo.flutter}}/issues/50546)
* Removed in [#98543]({{site.repo.flutter}}/issues/98543)
[Material Date Picker Redesign]: /go/material-date-picker-redesign
[`CalendarDatePicker`]: {{site.api}}/flutter/material/CalendarDatePicker-class.html
[`showDatePicker`]: {{site.api}}/flutter/material/showDatePicker.html
---
### `FlatButton`, `RaisedButton`, & `OutlineButton`
Supported by Flutter Fix: no
The `FlatButton`, `RaisedButton`, and `OutlineButton` widgets were first
deprecated in v1.20, and then extended in v1.26.
They are replaced by new buttons, `TextButton`, `ElevatedButton`, and
`OutlinedButton`. These new widgets also use new associated themes, rather than
the generic `ButtonTheme`.
<div class="table-wrapper" markdown="1">
| Old Widget | Old Theme | New Widget | New Theme |
|-----------------|---------------|------------------|-----------------------|
| `FlatButton` | `ButtonTheme` | `TextButton` | `TextButtonTheme` |
| `RaisedButton` | `ButtonTheme` | `ElevatedButton` | `ElevatedButtonTheme` |
| `OutlineButton` | `ButtonTheme` | `OutlinedButton` | `OutlinedButtonTheme` |
{:.table .table-striped .nowrap}
</div>
**Migration guide**
[In-depth migration guide available for detailed styling][]
Code before migration:
```dart
FlatButton(
onPressed: onPressed,
child: Text('Button'),
// ...
);
RaisedButton(
onPressed: onPressed,
child: Text('Button'),
// ...
);
OutlineButton(
onPressed: onPressed,
child: Text('Button'),
// ...
);
```
Code after migration:
```dart
TextButton(
onPressed: onPressed,
child: Text('Button'),
// ...
);
ElevatedButton(
onPressed: onPressed,
child: Text('Button'),
// ...
);
OutlinedButton(
onPressed: onPressed,
child: Text('Button'),
// ...
);
```
**References**
Design document:
* [New Material buttons and themes][]
API documentation:
* [`ButtonStyle`][]
* [`ButtonStyleButton`][]
* [`ElevatedButton`][]
* [`ElevatedButtonTheme`][]
* [`ElevatedButtonThemeData`][]
* [`OutlinedButton`][]
* [`OutlinedButtonTheme`][]
* [`OutlinedButtonThemeData`][]
* [`TextButton`][]
* [`TextButtonTheme`][]
* [`TextButtonThemeData`][]
Relevant PRs:
* New API added in [#59702]({{site.repo.flutter}}/issues/59702)
* Deprecated in [#73352]({{site.repo.flutter}}/issues/73352)
* Removed in [#98546]({{site.repo.flutter}}/issues/98546)
[In-depth migration guide available for detailed styling]: /release/breaking-changes/buttons
[New Material buttons and themes]: /go/material-button-migration-guide
[`ButtonStyle`]: {{site.api}}/flutter/material/ButtonStyle-class.html
[`ButtonStyleButton`]: {{site.api}}/flutter/material/ButtonStyleButton-class.html
[`ElevatedButton`]: {{site.api}}/flutter/material/ElevatedButton-class.html
[`ElevatedButtonTheme`]: {{site.api}}/flutter/material/ElevatedButtonTheme-class.html
[`ElevatedButtonThemeData`]: {{site.api}}/flutter/material/ElevatedButtonThemeData-class.html
[`OutlinedButton`]: {{site.api}}/flutter/material/OutlinedButton-class.html
[`OutlinedButtonTheme`]: {{site.api}}/flutter/material/OutlinedButtonTheme-class.html
[`OutlinedButtonThemeData`]: {{site.api}}/flutter/material/OutlinedButtonThemeData-class.html
[`TextButton`]: {{site.api}}/flutter/material/TextButton-class.html
[`TextButtonTheme`]: {{site.api}}/flutter/material/TextButtonTheme-class.html
[`TextButtonThemeData`]: {{site.api}}/flutter/material/TextButtonThemeData-class.html
---
### `Scaffold` `SnackBar` methods
Supported by Flutter Fix: no
The following `Scaffold` `SnackBar` methods were deprecated in v1.23.
- `showSnackBar`
- `removeCurrentSnackBar`
- `hideCurrentSnackBar`
The same named methods of the `ScaffoldMessenger` should be used instead. A
default `ScaffoldMessenger` is already created in every `MaterialApp`.
**Migration guide**
[In-depth migration guide available][]
Code before migration:
```dart
Scaffold.of(context).showSnackBar(mySnackBar);
Scaffold.of(context).removeCurrentSnackBar(mySnackBar);
Scaffold.of(context).hideCurrentSnackBar(mySnackBar);
```
Code after migration:
```dart
ScaffoldMessenger.of(context).showSnackBar(mySnackBar);
ScaffoldMessenger.of(context).removeCurrentSnackBar(mySnackBar);
ScaffoldMessenger.of(context).hideCurrentSnackBar(mySnackBar);
```
**References**
Design document:
* [ScaffoldMessenger Design][]
Video content:
* [SnackBar Delivery][]
* [Widget of the Week][]
API documentation:
* [`ScaffoldMessenger`][]
* [`SnackBar`][]
Relevant issues:
* [Issue 57218]({{site.repo.flutter}}/issues/57218)
* [Issue 62921]({{site.repo.flutter}}/issues/62921)
Relevant PRs:
* New API added in [#64101]({{site.repo.flutter}}/issues/64101)
* Deprecated in [#67947]({{site.repo.flutter}}/issues/67947)
* Removed in [#98549]({{site.repo.flutter}}/issues/98549)
[In-depth migration guide available]: /release/breaking-changes/scaffold-messenger
[ScaffoldMessenger Design]: /go/scaffold-messenger
[SnackBar Delivery]: https://youtu.be/sYG7HAGu_Eg?t=10271
[Widget of the Week]: https://youtu.be/lytQi-slT5Y
[`ScaffoldMessenger`]: {{site.api}}/flutter/material/ScaffoldMessenger-class.html
[`SnackBar`]: {{site.api}}/flutter/material/SnackBar-class.html
---
### `RectangularSliderTrackShape.disabledThumbGapWidth`
Supported by Flutter Fix: yes
The `RectangularSliderTrackShape.disabledThumbGapWidth` was first deprecated in
v1.5, and then extended in v1.26.
This was no longer used by the framework, as the animation of the slider thumb
no longer occurs when disabled.
**Migration guide**
Code before migration:
```dart
RectangularSliderTrackShape(disabledThumbGapWidth: 2.0);
```
Code after migration:
```dart
RectangularSliderTrackShape();
```
**References**
API documentation:
* [`RectangularSliderTrackShape`][]
Relevant PRs:
* Animation changed in [#30390]({{site.repo.flutter}}/issues/30390)
* Deprecated in [#65246]({{site.repo.flutter}}/issues/65246)
* Removed in [#98613]({{site.repo.flutter}}/issues/98613)
[`RectangularSliderTrackShape`]: {{site.api}}/flutter/material/RectangularSliderTrackShape-class.html
---
### Text selection of `ThemeData` to `TextSelectionThemeData`
Supported by Flutter Fix: yes
The following `ThemeData` members were first deprecated in v1.23, and extended
in v1.26.
- `useTextSelectionTheme`
- `textSelectionColor`
- `cursorColor`
- `textSelectionHandleColor`
These should be replaced by a more comprehensive `TextSelectionThemeData`,
which is now specified in `ThemeData` itself.
The `useTextSelectionTheme` flag served as a temporary migration flag to
distinguish the two APIs, it can be removed now.
**Migration guide**
[In-depth migration guide available][]
Code before migration:
```dart
ThemeData(
useTextSelectionTheme: false,
textSelectionColor: Colors.blue,
cursorColor: Colors.green,
textSelectionHandleColor: Colors.red,
);
```
Code after migration:
```dart
ThemeData(
textSelectionTheme: TextSelectionThemeData(
selectionColor: Colors.blue,
cursorColor: Colors.green,
selectionHandleColor: Colors.red,
),
);
```
**References**
Design document:
* [Text Selection Theme][]
API documentation:
* [`ThemeData`][]
* [`TextSelectionThemeData`][]
Relevant issues:
* [Issue 17635]({{site.repo.flutter}}/issues/17635)
* [Issue 56082]({{site.repo.flutter}}/issues/56082)
* [Issue 61227]({{site.repo.flutter}}/issues/61227)
Relevant PRs:
* New API added in [#62014]({{site.repo.flutter}}/issues/62014)
* Deprecated in [#66485]({{site.repo.flutter}}/issues/66482)
* Removed in [#98578]({{site.repo.flutter}}/issues/98578)
[In-depth migration guide available]: /release/breaking-changes/text-selection-theme
[Text Selection Theme]: /go/text-selection-theme
[`ThemeData`]: {{site.api}}/flutter/material/ThemeData-class.html
[`TextSelectionThemeData`]: {{site.api}}/flutter/material/TextSelectionThemeData-class.html
---
### `RenderEditable.onSelectionChanged` to `TextSelectionDelegate.textEditingValue`
Supported by Flutter Fix: no
`RenderEditable.onSelectionChanged` and `TextSelectionDelegate.textEditingValue`
were deprecated in v1.26.
Instead of calling one or both of these methods, call
`TextSelectionDelegate.userUpdateTextEditingValue`. This fixed a bug where the
`TextInputFormatter` would receive the wrong selection value.
**Migration guide**
Code before migration:
```dart
renderEditable.onSelectionChanged(selection, renderObject, cause);
textSelectionDelegate.textEditingValue = value;
```
Code after migration:
```dart
textSelectionDelegate.userUpdateTextEditingValue(value, cause);
```
**References**
API documentation:
* [`RenderEditable`][]
* [`TextSelectionDelegate`][]
Relevant issues:
* Resolved [#75505]({{site.repo.flutter}}/issues/75502)
Relevant PRs:
* Deprecated in [#75541]({{site.repo.flutter}}/issues/75541)
* Removed in [#98582]({{site.repo.flutter}}/issues/98582)
[`RenderEditable`]: {{site.api}}/flutter/rendering/RenderEditable-class.html
[`TextSelectionDelegate`]: {{site.api}}/flutter/services/TextSelectionDelegate-mixin.html
---
### `Stack.overflow`
Supported by Flutter Fix: yes
`Stack.overflow`, as well as the `Overflow` enum were deprecated in v1.22.
The replacement is `Stack.clipBehavior`, a change made as part of unifying clip
behaviors and semantics across the framework. Where `Overflow.visible` was used,
use `Clip.none`. Where `Overflow.clip` was used, use `Clip.hardEdge`.
**Migration guide**
[In-depth migration guide available][]
Code before migration:
```dart
const Stack stack = Stack(overflow: Overflow.visible);
const Stack stack = Stack(overflow: Overflow.clip);
```
Code after migration:
```dart
const Stack stack = Stack(clipBehavior: Clip.none);
const Stack stack = Stack(clipBehavior: Clip.hardEdge);
```
**References**
API documentation:
* [`Stack`][]
* [`Clip`][]
Relevant issues:
* Resolved [#66030]({{site.repo.flutter}}/issues/66030)
Relevant PRs:
* Deprecated in [#66305]({{site.repo.flutter}}/issues/66305)
* Removed in [#98583]({{site.repo.flutter}}/issues/98583)
[In-depth migration guide available]: /release/breaking-changes/clip-behavior
[`Stack`]: {{site.api}}/flutter/widgets/Stack-class.html
[`Clip`]: {{site.api}}/flutter/dart-ui/Clip.html
---
### `UpdateLiveRegionEvent`
Supported by Flutter Fix: no
The `SemanticsEvent` `UpdateLiveRegionEvent`, was first deprecated in v1.12, and
then extended in v1.26.
This was never implemented by the framework, and any references should be
removed.
**References**
API documentation:
* [`SemanticsEvent`][]
Relevant PRs:
* Deprecated in [#45940]({{site.repo.flutter}}/issues/45940)
* Removed in [#98615]({{site.repo.flutter}}/issues/98615)
[`SemanticsEvent`]: {{site.api}}/flutter/semantics/SemanticsEvent-class.html
---
### `RenderObjectElement` methods
Supported by Flutter Fix: yes
The following `RenderObjectElement` methods were deprecated in v1.21.
- `insertChildRenderObject`
- `moveChildRenderObject`
- `removeChildRenderObject`
These methods are replaced, respectively, by:
- `insertRenderObjectChild`
- `moveRenderObjectChild`
- `removeRenderObjectChild`
These changes were made as a soft breaking deprecation in order to change the
function signature.
**Migration guide**
Code before migration:
```dart
element.insertChildRenderObject(child, slot);
element.moveChildRenderObject(child, slot);
element.removeChildRenderObject(child);
```
Code after migration:
```dart
element.insertRenderObjectChild(child, slot);
element.moveRenderObjectChild(child, oldSlot, newSlot);
element.removeRenderObjectChild(child, slot);
```
**References**
API documentation:
* [`RenderObjectElement`][]
Relevant issues:
* [Issue 63269]({{site.repo.flutter}}/issues/63269)
Relevant PRs:
* Deprecated in [#64254]({{site.repo.flutter}}/issues/64254)
* Removed in [#98616]({{site.repo.flutter}}/issues/98616)
[`RenderObjectElement`]: {{site.api}}/flutter/widgets/RenderObjectElement-class.html
---
## Timeline
In stable release: 3.0.0
| website/src/release/breaking-changes/2-10-deprecations.md/0 | {
"file_path": "website/src/release/breaking-changes/2-10-deprecations.md",
"repo_id": "website",
"token_count": 5699
} | 1,309 |
---
title: FlutterMain.setIsRunningInRobolectricTest on Android removed
description: >
The test-only FlutterMain.setIsRunningInRobolectricTest API on the
Android engine is consolidated into the FlutterInjector.
---
## Summary
If you write Java JUnit tests (such as Robolectric tests)
against the Flutter engine's Java embedding and used the
`FlutterMain.setIsRunningInRobolectricTest(true)` API,
replace it with the following:
```java
FlutterJNI mockFlutterJNI = mock(FlutterJNI.class);
FlutterInjector.setInstance(
new FlutterInjector.Builder()
.setFlutterLoader(new FlutterLoader(mockFlutterJNI))
.build());
```
This should be very uncommon.
## Context
The `FlutterMain` class itself is being deprecated and replaced with the
`FlutterInjector` class. The `FlutterMain` class uses a number of
static variables and functions than make it difficult to test.
`FlutterMain.setIsRunningInRobolectricTest()` is one ad-hoc static
mechanism to allow tests to run on the host machine on JVM without
loading the `libflutter.so` native library
(which can't be done on the host machine).
Rather than one-off solutions, all dependency injections needed for tests
in Flutter's Android/Java engine embedding are now moved to the
[`FlutterInjector`] class.
[`FlutterInjector`]: https://cs.opensource.google/flutter/engine/+/master:shell/platform/android/io/flutter/FlutterInjector.java
Within the `FlutterInjector` class,
the `setFlutterLoader()` Builder
function allows for control of how the
[`FlutterLoader`][] class locates and loads
the `libflutter.so` library.
[`FlutterLoader`]: https://cs.opensource.google/flutter/engine/+/master:shell/platform/android/io/flutter/embedding/engine/loader/FlutterLoader.java
## Description of change
This [engine commit][] removed the
`FlutterMain.setIsRunningInRobolectricTest()` testing function;
and the following [commit][] added a
`FlutterInjector` class to assist testing.
[PR 20473][] further refactored `FlutterLoader`
and `FlutterJNI` to allow for additional mocking and testing.
[commit]: {{site.repo.engine}}/commit/15f5696c4139a21e1fc54014ce17d01f6ad1737c#diff-f928557f2d60773a8435366400fa42ed
[engine commit]: {{site.repo.engine}}/commit/15f5696c4139a21e1fc54014ce17d01f6ad1737c#diff-599e1d64442183ead768757cca6805c3L154
[PR 20473]: {{site.repo.engine}}/pull/20473
to allow for additional mocking/testing.
## Migration guide
Code before migration:
```java
FlutterMain.setIsRunningInRobolectricTest(true);
```
Code after migration:
```java
FlutterJNI mockFlutterJNI = mock(FlutterJNI.class);
FlutterInjector.setInstance(
new FlutterInjector.Builder()
.setFlutterLoader(new FlutterLoader(mockFlutterJNI))
.build());
```
## Timeline
Landed in version: 1.22.0-2.0.pre.133<br>
In stable release: 2.0.0
| website/src/release/breaking-changes/android-setIsRunningInRobolectricTest-removed.md/0 | {
"file_path": "website/src/release/breaking-changes/android-setIsRunningInRobolectricTest-removed.md",
"repo_id": "website",
"token_count": 971
} | 1,310 |
---
title: Added BuildContext parameter to TextEditingController.buildTextSpan
description: >
A BuildContext parameter is added to TextEditingController.buildTextSpan so
inheritors that override buildTextSpan can access inherited widgets.
---
## Summary
A `BuildContext` parameter was added to `TextEditingController.buildTextSpan`.
Classes that extend or implement `TextEditingController`
and override `buildTextSpan` need to add the `BuildContext`
parameter to the signature to make it a valid override.
Callers of `TextEditingController.buildTextSpan`
need to pass a `BuildContext` to the call.
## Context
`TextEditingController.buildTextSpan` is called by `EditableText`
on its controller to create the `TextSpan` that it renders.
`buildTextSpan` can be overridden in custom classes that extend
`TextEditingController`. This allows classes extending
`TextEditingController` override `buildTextSpan` to change
the style of parts of the text, for example, for rich text editing.
Any state that is required by `buildTextSpan`
(other than the `TextStyle` and `withComposing` arguments)
needed to be passed into the class that extends
`TextEditingController`.
## Description of change
With the `BuildContext` available, users can access
`InheritedWidgets` inside `buildTextSpan`
to retrieve state required to style the text,
or otherwise manipulate the created `TextSpan`.
Consider the example where we have a
`HighlightTextEditingController` that wants to
highlight text by setting its color to `Theme.accentColor`.
Before this change the controller implementation would look like this:
```dart
class HighlightTextEditingController extends TextEditingController {
HighlightTextEditingController(this.highlightColor);
final Color highlightColor;
@override
TextSpan buildTextSpan({TextStyle? style, required bool withComposing}) {
return super.buildTextSpan(style: TextStyle(color: highlightColor), withComposing: withComposing);
}
```
And users of the controller would need to pass the color
when creating the controller.
With the `BuildContext` parameter available,
the `HighlightTextEditingController` can directly access
`Theme.accentColor` using `Theme.of(BuildContext)`:
```dart
class HighlightTextEditingController extends TextEditingController {
@override
TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
final Color color = Theme.of(context).accentColor;
return super.buildTextSpan(context: context, style: TextStyle(color: color), withComposing: withComposing);
}
}
```
## Migration guide
### Overriding `TextEditingController.buildTextSpan`
Add a `required BuildContext context` parameter to the
signature of the `buildTextSpan` override.
Code before migration:
```dart
class MyTextEditingController {
@override
TextSpan buildTextSpan({TextStyle? style, required bool withComposing}) {
/* ... */
}
}
```
Example error message before migration:
```nocode
'MyTextEditingController.buildTextSpan' ('TextSpan Function({TextStyle? style, required bool withComposing})') isn't a valid override of 'TextEditingController.buildTextSpan' ('TextSpan Function({required BuildContext context, TextStyle? style, required bool withComposing})').
```
Code after migration:
```dart
class MyTextEditingController {
@override
TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
/* ... */
}
}
```
### Calling `TextEditingController.buildTextSpan`
Pass a named parameter 'context' of type
`BuildContext` to the call.
Code before migration:
```dart
TextEditingController controller = /* ... */;
TextSpan span = controller.buildTextSpan(withComposing: false);
```
Error message before migration:
```nocode
The named parameter 'context' is required, but there's no corresponding argument.
Try adding the required argument.
```
Code after migration:
```dart
BuildContext context = /* ... */;
TextEditingController controller = /* ... */;
TextSpan span = controller.buildTextSpan(context: context, withComposing: false);
```
## Timeline
Landed in version: 1.26.0<br>
In stable release: 2.0.0
## References
API documentation:
* [`TextEditingController.buildTextSpan`][]
Relevant issues:
* [Issue #72343][]
Relevant PRs:
* [Reland "Add BuildContext parameter to TextEditingController.buildTextSpan" #73510][]
* [Revert "Add BuildContext parameter to TextEditingController.buildTextSpan" #73503][]
* [Add BuildContext parameter to TextEditingController.buildTextSpan #72344][]
[Add BuildContext parameter to TextEditingController.buildTextSpan #72344]: {{site.repo.flutter}}/pull/72344
[Issue #72343]: {{site.repo.flutter}}/issues/72343
[Reland "Add BuildContext parameter to TextEditingController.buildTextSpan" #73510]: {{site.repo.flutter}}/pull/73510
[Revert "Add BuildContext parameter to TextEditingController.buildTextSpan" #73503]: {{site.repo.flutter}}/pull/73503
[`TextEditingController.buildTextSpan`]: {{site.api}}/flutter/widgets/TextEditingController/buildTextSpan.html
| website/src/release/breaking-changes/buildtextspan-buildcontext.md/0 | {
"file_path": "website/src/release/breaking-changes/buildtextspan-buildcontext.md",
"repo_id": "website",
"token_count": 1469
} | 1,311 |
---
title: Added missing `dispose()` for some disposable objects in Flutter
description: >
'dispose()' might fail because of double disposal.
---
## Summary
Missing calls to 'dispose()' are added for some disposable objects.
For example, ContextMenuController did not dispose OverlayEntry,
and EditableTextState did not dispose TextSelectionOverlay.
If some other code also invokes 'dispose()' for the object,
and the object is protected from double disposal,
the second 'dispose()' fails with the following error message:
`Once you have called dispose() on a <class name>, it can no longer be used.`
## Background
The convention is that the owner of an object should dispose of it.
This convention was broken in some places:
owners were not disposing the disposable objects.
The issue was fixed by adding a call to `dispose()`.
However, if the object is protected from double disposal,
this can cause failures when running in debug mode
and `dispose()` is called elsewhere on the object.
## Migration guide
If you encounter the following error, update your code to
call `dispose()` only in cases when your code created the object.
```
Once you have called dispose() on a <class name>, it can no longer be used.
```
Code before migration:
```dart
x.dispose();
```
Code after migration:
```dart
if (xIsCreatedByMe) {
x.dispose();
}
```
To locate the incorrect disposal, check the call stack of the error. If the call stack points to `dispose`
in your code, this disposal is incorrect and should be fixed.
If the error occurs in Flutter code, `dispose()` was
called incorrectly the first time.
You can locate the incorrect call by temporary calling `print(StackTrace.current)`
in the body of the failed method `dispose`.
## Timeline
See the progress and status [in the tracking issue]({{site.repo.flutter}}/issues/134787).
| website/src/release/breaking-changes/dispose.md/0 | {
"file_path": "website/src/release/breaking-changes/dispose.md",
"repo_id": "website",
"token_count": 496
} | 1,312 |
---
title: Adding ImageProvider.loadBuffer
description: >
ImageProviders must now be implemented using the
new loadBuffer API instead of the existing load API.
---
## Summary
* `ImageProvider` now has a method called `loadBuffer` that functions
similarly to `load`, except that it decodes from an `ui.ImmutableBuffer`.
* `ui.ImmutableBuffer` can now be created directly from an asset key.
* The `AssetBundle` classes can now load an `ui.ImmutableBuffer`.
* The `PaintingBinding` now has a method called
`instantiateImageCodecFromBuffer`, which functions similarly to
`instantiateImageCodec`.
* `ImageProvider.load` is now deprecated, it will be removed in a future
release.
* `PaintingBinding.instantiateImageCodec` is now deprecated, it will be removed
in a future release.
## Context
`ImageProvider.loadBuffer` is a new method that must be implemented in order to
load images. This API allows asset-based image loading to be performed faster
and with less memory impact on application.
## Description of change
When loading asset images, previously the image provider API required multiple
copies of the compressed data. First, when opening the asset the data was
copied into the external heap and exposed to Dart as a typed data array. Then
that typed data array was eventually converted into an `ui.ImmutableBuffer`,
which internally copies the data into a second structure for decoding.
With the addition of `ui.ImmutableBuffer.fromAsset`, compressed image bytes can
be loaded directly into the structure used for decoding. Using this approach
requires changes to the byte loading pipeline of `ImageProvider`. This process
is also faster, because it bypasses some additional scheduling overhead of the
previous method channel based loader.
`ImageProvider.loadBuffer` otherwise has the same contract as
`ImageProvider.load`, except it provides a new decoding callback that expects
an `ui.ImmutableBuffer` instead of a `Uint8List`. For `ImageProvider` classes
that acquire bytes from places other than assets, the convenience method
`ui.ImmutableBuffer.fromUint8List` can be used for compatibility.
## Migration guide
Classes that subclass `ImageProvider` must implement the `loadBuffer` method for
loading assets. Classes that delegate to or call the methods of an
`ImageProvider` directly must use `loadBuffer` instead of `load`.
Code before migration:
```dart
class MyImageProvider extends ImageProvider<MyImageProvider> {
@override
ImageStreamCompleter load(MyImageProvider key, DecoderCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadData(key, decode),
);
}
Future<ui.Codec> _loadData(MyImageProvider key, DecoderCallback decode) async {
final Uint8List bytes = await bytesFromSomeApi();
return decode(bytes);
}
}
class MyDelegatingProvider extends ImageProvider<MyDelegatingProvider> {
MyDelegatingProvider(this.provider);
final ImageProvder provider;
@override
ImageStreamCompleter load(MyDelegatingProvider key, DecoderCallback decode) {
return provider.load(key, decode);
}
}
```
Code after migration:
```dart
class MyImageProvider extends ImageProvider<MyImageProvider> {
@override
ImageStreamCompleter loadBuffer(MyImageProvider key, DecoderBufferCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadData(key, decode),
);
}
Future<ui.Codec> _loadData(MyImageProvider key, DecoderBufferCallback decode) async {
final Uint8List bytes = await bytesFromSomeApi();
final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
return decode(buffer);
}
}
class MyDelegatingProvider extends ImageProvider<MyDelegatingProvider> {
MyDelegatingProvider(this.provider);
final ImageProvder provider;
@override
ImageStreamCompleter loadBuffer(MyDelegatingProvider key, DecoderCallback decode) {
return provider.loadBuffer(key, decode);
}
}
```
In both cases you might choose to keep the
previous implementation of `ImageProvider.load`
to give users of your code time to migrate as well.
## Timeline
Landed in version: 3.1.0-0.0.pre.976<br>
In stable release: 3.3.0
## References
API documentation:
* [`ImmutableBuffer`]({{site.api}}/flutter/dart-ui/ImmutableBuffer-class.html)
* [`ImageProvider`]({{site.api}}/flutter/painting/ImageProvider-class.html)
Relevant PR:
* [Use immutable buffer for loading asset images]({{site.repo.flutter}}/pull/103496)
| website/src/release/breaking-changes/image-provider-load-buffer.md/0 | {
"file_path": "website/src/release/breaking-changes/image-provider-load-buffer.md",
"repo_id": "website",
"token_count": 1244
} | 1,313 |
---
title: MouseTracker no longer attaches annotations
description: >
MouseTracker no longer relies on annotation attachment to
perform the mounted-exit check; therefore,
all three related methods are removed.
---
## Summary
Removed `MouseTracker`'s methods `attachAnnotation`,
`detachAnnotation`, and `isAnnotationAttached`.
## Context
Mouse events, such as when a mouse pointer has entered a region,
exited, or is hovering over a region, are detected with the help of
`MouseTrackerAnnotation`s that are placed on interested regions
during the render phase. Upon each update (a new frame or a new event),
`MouseTracker` compares the annotations hovered by the mouse
pointer before and after the update, then dispatches
callbacks accordingly.
The `MouseTracker` class, which manages the state of mouse pointers,
used to require `MouseRegion` to attach annotations when mounted,
and detach annotations when unmounted.
This was used by `MouseTracker` to perform the
_mounted-exit check_ (for example, `MouseRegion.onExit`
must not be called if the exit was caused by the unmounting
of the widget), in order to prevent calling `setState`
of an unmounted widget and throwing exceptions (explained
in detail in [Issue #44631][]).
This mechanism has been replaced by making `MouseRegion`
a stateful widget, so that it can perform the mounted-exit
check by itself by blocking the callback when unmounted.
Therefore, these methods have been removed, and `MouseTracker`
no longer tracks all annotations on the screen.
## Description of change
The `MouseTracker` class has removed three methods related
to attaching annotations:
```diff
class MouseTracker extends ChangeNotifier {
// ...
- void attachAnnotation(MouseTrackerAnnotation annotation) {/* ... */}
- void detachAnnotation(MouseTrackerAnnotation annotation) {/* ... */}
- @visibleForTesting
- bool isAnnotationAttached(MouseTrackerAnnotation annotation) {/* ... */}
}
```
`RenderMouseRegion` and `MouseTrackerAnnotation` no longer perform the
mounted-exit check, while `MouseRegion` still does.
## Migration guide
Calls to `MouseTracker.attachAnnotation` and
`detachAnnotation` should be removed with little to no impact:
* Uses of `MouseRegion` should not be affected at all.
* If your code directly uses `RenderMouseRegion` or
`MouseTrackerAnnotation`, be aware that `onExit`
is now called when the exit is caused by events that used
to call `MouseTracker.detachAnnotation`.
This should not be a problem if no states are involved,
otherwise you might want to add the mounted-exit check,
especially if the callback is leaked so that outer
widgets might call `setState` in it. For example:
Code before migration:
```dart
class MyMouseRegion extends SingleChildRenderObjectWidget {
const MyMouseRegion({this.onHoverChange});
final ValueChanged<bool> onHoverChange;
@override
RenderMouseRegion createRenderObject(BuildContext context) {
return RenderMouseRegion(
onEnter: (_) { onHoverChange(true); },
onExit: (_) { onHoverChange(false); },
);
}
@override
void updateRenderObject(BuildContext context, RenderMouseRegion renderObject) {
renderObject
..onEnter = (_) { onHoverChange(true); }
..onExit = (_) { onHoverChange(false); };
}
}
```
Code after migration:
```dart
class MyMouseRegion extends SingleChildRenderObjectWidget {
const MyMouseRegion({this.onHoverChange});
final ValueChanged<bool> onHoverChange;
@override
RenderMouseRegion createRenderObject(BuildContext context) {
return RenderMouseRegion(
onEnter: (_) { onHoverChange(true); },
onExit: (_) { onHoverChange(false); },
);
}
@override
void updateRenderObject(BuildContext context, RenderMouseRegion renderObject) {
renderObject
..onEnter = (_) { onHoverChange(true); }
..onExit = (_) { onHoverChange(false); };
}
@override
void didUnmountRenderObject(RenderMouseRegion renderObject) {
renderObject
..onExit = onHoverChange == null ? null : (_) {};
}
}
```
Calls to `MouseTracker.isAnnotationAttached` must be removed.
This feature is no longer technically possible,
since annotations are no longer tracked.
If you somehow need this feature, please submit an issue.
## Timeline
Landed in version: 1.15.4<br>
In stable release: 1.17
## References
API documentation:
* [`MouseRegion`][]
* [`MouseTracker`][]
* [`MouseTrackerAnnotation`][]
* [`RenderMouseRegion`][]
Relevant PRs:
* [MouseTracker no longer requires annotations attached][],
which made the change
* [Improve MouseTracker lifecycle: Move checks to post-frame][],
which first introduced the mounted-exit change,
explained at _The change to onExit_.
[Improve MouseTracker lifecycle: Move checks to post-frame]: {{site.repo.flutter}}/issues/44631
[Issue #44631]: {{site.repo.flutter}}/pull/44631
[`MouseRegion`]: {{site.api}}/flutter/widgets/MouseRegion-class.html
[`MouseTracker`]: {{site.api}}/flutter/gestures/MouseTracker-class.html
[MouseTracker no longer requires annotations attached]: {{site.repo.flutter}}/issues/48453
[`MouseTrackerAnnotation`]: {{site.api}}/flutter/gestures/MouseTrackerAnnotation-class.html
[`RenderMouseRegion`]: {{site.api}}/flutter/rendering/RenderMouseRegion-class.html
| website/src/release/breaking-changes/mouse-tracker-no-longer-attaches-annotations.md/0 | {
"file_path": "website/src/release/breaking-changes/mouse-tracker-no-longer-attaches-annotations.md",
"repo_id": "website",
"token_count": 1510
} | 1,314 |
---
title: Notable Rendering and Layout Changes after v3.7
description: Non-API related breaking changes made after Flutter v3.7.
---
## Changes
This section lists the notable non-API breaking changes.
### (Only Affects Tests) `FlutterTest` is now the default test font
The `FlutterTest` font replaced `Ahem` as the default font in tests: when
`fontFamily` isn't specified, or the font families specified are not registered,
tests use the `FlutterTest` font to render text. The `Ahem` font is still
available in tests if specified as the `fontFamily` to use.
The `FlutterTest` font produces more precise font and glyph metrics than `Ahem`,
and the metrics are generally font-engine agnostic.
Check out the [Flutter Test Fonts][]
wiki page for more details about the test font.
**Differences**
The `FlutterTest` font looks almost identical to the old default `Ahem`: the
glyph for most characters is a box that fills the em square. The notable
differences between the `FlutterTest` font and `Ahem` font are:
**1. Different baseline location**
The `FlutterTest` font's ascent and descent are 0.75 em and 0.25 em, while
`Ahem`'s are 0.8 em and 0.2 em, respectively.
In the example golden image change below, the white blocks are text rendered
using `Ahem` and `FlutterTest`. The second character is taller in the new font
since it has a larger descent.
| Before (`Ahem`) | After | Animated Diff |
| :---: | :---: | :---: |
|  |  |  |
**2. Different decoration position**
The underline location is slightly higher in `FlutterTest` than `Ahem`.
In the example golden image change below, the 3 lines of white blocks are text
rendered using `Ahem` and `FlutterTest`. The blue dashed lines indicate the
[TextDecoration.overline]/[TextDecoration.lineThrough]/[TextDecoration.underline]
positions for each line.
| Before (`Ahem`) | After | Animated Diff |
| :---: | :---: | :---: |
|  |  |  |
**3. The glyph used for unmapped characters are slightly different**
Unmapped characters are rendered as hollow boxes in both fonts, with
a slight difference:
| Before (`Ahem`) | After | Diff |
| :---: | :---: | :---: |
|  |  |  |
## References
Relevant PRs:
* The `FlutterTest` font was added in: [Add new test font]({{site.repo.engine}}/pull/39809)
* The `FlutterTest` font was made the default in: [Make FlutterTest the default test font]({{site.repo.engine}}/pull/40188)
Wiki page:
* [Flutter Test Fonts][]
[Flutter Test Fonts]: {{site.repo.flutter}}/wiki/Flutter-Test-Fonts
[TextDecoration.underline]: {{site.api}}/flutter/dart-ui/TextDecoration/underline-constant.html
[TextDecoration.overline]: {{site.api}}/flutter/dart-ui/TextDecoration/overline-constant.html
[TextDecoration.lineThrough]: {{site.api}}/flutter/dart-ui/TextDecoration/lineThrough-constant.html
| website/src/release/breaking-changes/rendering-changes.md/0 | {
"file_path": "website/src/release/breaking-changes/rendering-changes.md",
"repo_id": "website",
"token_count": 1037
} | 1,315 |
---
title: TestWidgetsFlutterBinding.clock change
description: The Clock implementation now comes from package:clock.
---
## Summary
The `TestWidgetsFlutterBinding.clock` now comes from
`package:clock` and not `package:quiver`.
## Context
The `flutter_test` package is removing its dependency on
the heavier weight `quiver` package in favor of a dependency
on two more targeted and lighter weight packages,
`clock` and `fake_async`.
This can affect user code which grabs the clock from a
`TestWidgetsFlutterBinding` and passes that to an API
that expects a `Clock` from `package:quiver`,
for example some code like this:
```dart
testWidgets('some test', (WidgetTester tester) {
someApiThatWantsAQuiverClock(tester.binding.clock);
});
```
## Migration guide
The error you might see after this change looks something like this:
```nocode
Error: The argument type 'Clock/*1*/' can't be assigned to the parameter type 'Clock/*2*/'.
- 'Clock/*1*/' is from 'package:clock/src/clock.dart' ('<pub-cache>/clock/lib/src/clock.dart').
- 'Clock/*2*/' is from 'package:quiver/time.dart' ('<pub-cache>/quiver/lib/time.dart').
```
### Option #1: Create a package:quiver Clock from a package:clock Clock
The easiest migration is to create a `package:quiver` clock from the
`package:clock` clock, which can be done by passing the `.now` function
tearoff to the `Clock` constructor:
Code before migration:
```dart
testWidgets('some test', (WidgetTester tester) {
someApiThatWantsAQuiverClock(tester.binding.clock);
});
```
Code after migration:
```dart
testWidgets('some test', (WidgetTester tester) {
someApiThatWantsAQuiverClock(Clock(tester.binding.clock.now));
});
```
### Option #2: Change the api to accept a package:clock Clock
If you own the api you are calling,
you may want to change it to accept a `Clock`
from `package:clock`.
This is a judgement call based on how many places are
calling this API with something other than a clock
retrieved from a `TestWidgetsFlutterBinding`.
If you go this route, your call sites that are passing
`tester.binding.clock` won't need to be modified,
but other call sites will.
### Option #3: Change the API to accept a `DateTime function()`
If you only use the `Clock` for its `now` function,
and you control the API, then you can also change it
to accept that function directly instead of a `Clock`.
This makes it easily callable with either type of `Clock`,
by passing a tearoff of the `now` method from either type of clock:
Calling code before migration:
```dart
testWidgets('some test', (WidgetTester tester) {
someApiThatWantsAQuiverClock(tester.binding.clock);
});
```
Calling code after migration:
```dart
testWidgets('some test', (WidgetTester tester) {
modifiedApiThatTakesANowFunction(tester.binding.clock.now);
});
```
## Timeline
Landed in version: 1.18.0<br>
In stable release: 1.20
## References
API documentation:
* [`TestWidgetsFlutterBinding`][]
Relevant PRs:
* [PR 54125][]: remove flutter_test quiver dep,
use fake_async and clock instead
[`TestWidgetsFlutterBinding`]: {{site.api}}/flutter/flutter_test/TestWidgetsFlutterBinding-class.html
[PR 54125]: {{site.repo.flutter}}/pull/54125
| website/src/release/breaking-changes/test-widgets-flutter-binding-clock.md/0 | {
"file_path": "website/src/release/breaking-changes/test-widgets-flutter-binding-clock.md",
"repo_id": "website",
"token_count": 1009
} | 1,316 |
---
title: "\"Zone mismatch\" message"
description: >
When Flutter's bindings are initialized in a different zone
than the Zone used for `runApp`, a warning is printed to the console.
---
## Summary
Starting with Flutter 3.10, the framework detects mismatches
when using Zones and reports them to the console in debug builds.
## Background
Zones are a mechanism for managing callbacks in Dart.
While primarily useful for overriding `print` and `Timer` logic in tests,
and for catching errors in tests,
they are sometimes used for scoping global variables
to certain parts of an application.
Flutter requires (and has always required)
that all framework code be run in the same zone.
Notably, this means that calls to
`WidgetsFlutterBinding.ensureInitialized()` should be run in the same zone
as calls to `runApp()`.
Historically, Flutter has not detected such mismatches.
This sometimes leads to obscure and hard-to-debug issues.
For example,
a callback for keyboard input might be invoked
using a zone that does not have access to the `zoneValues` that it expects.
In our experience,
most if not all code that uses Zones
in a way that does not guarantee that all parts of
the Flutter framework are working in the same Zone
has some latent bug.
Often these bugs appear unrelated to the use of Zones.
To help developers who have accidentally violated this invariant,
starting with Flutter 3.10,
a non-fatal warning is printed in debug builds when a mismatch is detected.
The warning looks like the following:
```nocode
════════ Exception caught by Flutter framework ════════════════════════════════════
The following assertion was thrown during runApp:
Zone mismatch.
The Flutter bindings were initialized in a different zone than is now being used.
This will likely cause confusion and bugs as any zone-specific configuration will
inconsistently use the configuration of the original binding initialization zone or
this zone based on hard-to-predict factors such as which zone was active when a
particular callback was set.
It is important to use the same zone when calling `ensureInitialized` on the
binding as when calling `runApp` later.
To make this warning fatal, set BindingBase.debugZoneErrorsAreFatal to true before
the bindings are initialized (i.e. as the first statement in `void main() { }`).
[...]
═══════════════════════════════════════════════════════════════════════════════════
```
The warning can be made fatal by
setting [`BindingBase.debugZoneErrorsAreFatal`][] to `true`.
This flag might be changed to default to `true` in a future version of Flutter.
## Migration guide
The best way to silence this message is to
remove use of Zones from within the application.
Zones can be very hard to debug,
because they are essentially global variables,
and break encapsulation.
Best practice is to avoid global variables and zones.
If removing zones is not an option
(for example because the application depends on a third-party library
that relies on zones for its configuration),
then the various calls into the Flutter framework
should be moved to all be in the same zone.
Typically, this means moving the call to
`WidgetsFlutterBinding.ensureInitialized()` to the
same closure as the call to `runApp()`.
This can be awkward when the zone in which `runApp` is run
is being initialized with `zoneValues` obtained from a plugin
(which requires `WidgetsFlutterBinding.ensureInitialized()`
to have been called).
One option in this kind of scenario is to
place a mutable object in the `zoneValues`, and
update that object with the value once the value is available.
```dart
import 'dart:async';
import 'package:flutter/material.dart';
class Mutable<T> {
Mutable(this.value);
T value;
}
void main() {
var myValue = Mutable<double>(0.0);
Zone.current.fork(
zoneValues: {
'myKey': myValue,
}
).run(() {
WidgetsFlutterBinding.ensureInitialized();
var newValue = ...; // obtain value from plugin
myValue.value = newValue; // update value in Zone
runApp(...);
});
}
```
In code that needs to use `myKey`,
it can be obtained indirectly using `Zone.current['myKey'].value`.
When such a solution does not work
because a third-party dependency requires the use
of a specific type for a specific `zoneValues` key,
all calls into the dependency can be
wrapped in `Zone` calls that provide suitable values.
It is strongly recommended that packages that use zones in this way
migrate to more maintainable solutions.
## Timeline
Landed in version: 3.9.0-9.0.pre<br>
In stable release: 3.10.0
## References
API documentation:
* [`Zone`][]
* [`BindingBase.debugZoneErrorsAreFatal`][]
Relevant issues:
* [Issue 94123][]: Flutter framework does not warn when ensureInitialized
is called in a different zone than runApp
Relevant PRs:
* [PR 122836][]: Assert that runApp is called
in the same zone as binding.ensureInitialized
[`Zone`]: {{site.api}}/flutter/dart-async/Zone-class.html
[`BindingBase.debugZoneErrorsAreFatal`]: {{site.api}}/flutter/foundation/BindingBase/debugZoneErrorsAreFatal.html
[Issue 94123]: {{site.repo.flutter}}/issues/94123
[PR 122836]: {{site.repo.flutter}}/pull/122836
| website/src/release/breaking-changes/zone-errors.md/0 | {
"file_path": "website/src/release/breaking-changes/zone-errors.md",
"repo_id": "website",
"token_count": 1457
} | 1,317 |
---
title: Flutter 1.7.8 release notes
short-title: 1.7.8 release notes
description: Release notes for Flutter 1.7.8.
---
The 1.7.8 release is a follow-on to the 1.5.4 stable release in May,
providing 1289 merged PRs and closing 184 issues.
The major themes of this release are:
* Support for 32-bit and 64-bit bundles on Android
* Large number of iOS features and fixes,
including improved text editing and localization
* [AndroidX support](https://github.com/flutter/flutter/pull/31028)
for new projects via the --androidx flag of 'flutter create'
* A new widget: the
[RangeSlider](https://api.flutter.dev/flutter/material/RangeSlider-class.html)
As detailed in our
[roadmap](https://github.com/flutter/flutter/wiki/Roadmap),
we're also continuing the ongoing work in the Flutter engine
and framework to support turning on web and desktop targets;
however, this is not yet ready for general usage.
## Support for 32-bit and 64-bit Android Bundles
From August 1st, 2019, Android apps that use native code and target Android 9 Pie will[ be required to provide a 64-bit version](https://android-developers.googleblog.com/2019/01/get-your-apps-ready-for-64-bit.html) in addition to the 32-bit version when publishing to the Google Play Store. Since all Flutter apps include native code, this requirement will affect new Flutter apps submitted to the store, as well as updates to existing Flutter apps. This does not affect existing app versions published to the store.
This release includes support for building app bundles and APKs that support both 32-bit and 64-bit binaries, completing our work on [https://github.com/flutter/flutter/issues/31922](https://github.com/flutter/flutter/issues/31922). By using this release when building an Android application, your App Bundle or APK now supports both 32-bit and 64-bit CPU architectures by default.
## Breaking Changes
The following are the list of breaking changes in this release along with descriptions of each change and how to handle it in your Flutter code.
* [#29188](https://github.com/flutter/flutter/pull/29188) Fix 25807: implement move in sliver multibox widget
* [#29683](https://github.com/flutter/flutter/pull/29683) [Show/hide toolbar and handles based on device kind](https://groups.google.com/d/msgid/flutter-announce/CAAzQ467mb_7ZC4-djDeWLiYEmAH815-R5eums2cWmo2ND%3Dz%3DOw%40mail.gmail.com.)
* [#30040](https://github.com/flutter/flutter/pull/30040) Implement focus traversal for desktop platforms, shoehorn edition.
* [#30579](https://github.com/flutter/flutter/pull/30579) [PointerDownEvent and PointerMoveEvent default buttons to 1](https://groups.google.com/d/msgid/flutter-announce/9ed026a5-f6e3-438d-b4fd-303ae444323d%40googlegroups.com.)
* [#30874](https://github.com/flutter/flutter/pull/30874) Redo "Remove pressure customization from some pointer events"
* [#31227](https://github.com/flutter/flutter/pull/31227) [Adding CupertinoTabController](https://groups.google.com/d/msgid/flutter-announce/a1e7e4df-0310-4083-93b6-12ffd150dad0%40googlegroups.com.)
* [#31574](https://github.com/flutter/flutter/pull/31574) Improve RadioListTile Callback Behavior Consistency
* [#32059](https://github.com/flutter/flutter/pull/32059) fix issue 14014 read only text field
* [#32842](https://github.com/flutter/flutter/pull/32842) Allow "from" hero state to survive hero animation in a push transition
* [#33148](https://github.com/flutter/flutter/pull/33148) ExpandIcon Custom Colors
* [#33164](https://github.com/flutter/flutter/pull/33164) [remove Layer.replaceWith due to no usage and no tests](https://groups.google.com/d/msgid/flutter-announce/f9823aec-676a-41e9-a9ff-b6598c63b7fe%40googlegroups.com)
* [#33370](https://github.com/flutter/flutter/pull/33370) [Update FadeInImage to use new Image APIs]( https://groups.google.com/d/msgid/flutter-announce/CAA8mi4cGh6BVXS5u0g_7Kep6LOL6gO5htViMTgS%2BkMJ08oAjAQ%40mail.gmail.com.)
* [#34051](https://github.com/flutter/flutter/pull/34051) [Text inline widgets, TextSpan rework (#30069)" with improved backwards compatibility](https://groups.google.com/d/msgid/flutter-announce/CAN87bmyu29-ikjeSouVFNcpR7OEL95NPLnb7DN-F8bVLsnzkzQ%40mail.gmail.com.)
* [#34095](https://github.com/flutter/flutter/pull/34095) [Cupertino text edit to oltip, reworked](https://groups.google.com/d/msgid/flutter-announce/f7cc747a-c812-4bab-a97c-4adb4ce04084%40googlegroups.com.)
* [#34501](https://github.com/flutter/flutter/pull/34501) [Material] Fix TextDirection and selected thumb for RangeSliderThumbShape and RangeSliderValueIndicatorShape
* [#33946](https://github.com/flutter/flutter/pull/33946) Reland "Text inline widgets, TextSpan rework"
## Severe Crash Changes
We've also fixed several crashing issues in this release.
* [#31228](https://github.com/flutter/flutter/pull/31228) Fix ExpansionPanelList Duplicate Global Keys Exception
* [#31581](https://github.com/flutter/flutter/pull/31581) Fix Exception on Nested TabBarView disposal
* [#34460](https://github.com/flutter/flutter/pull/34460) Add back ability to override the local engine in Gradle
## iOS
We continue to focus heavily on the iOS support in Flutter, including enhanced text editing and localization in this release.
* [#29809](https://github.com/flutter/flutter/pull/29809) Fix text selection toolbar appearing under obstructions
* [#29824](https://github.com/flutter/flutter/pull/29824) Cupertino localization step 8: create a gen_cupertino_localizations and generate one for cupertino english and french
* [#29954](https://github.com/flutter/flutter/pull/29954) Cupertino localization step 9: add tests
* [#30129](https://github.com/flutter/flutter/pull/30129) Fix refresh control in the gallery demo, update comments
* [#30224](https://github.com/flutter/flutter/pull/30224) Cupertino localization step 10: update the flutter_localizations README
* [#31039](https://github.com/flutter/flutter/pull/31039) Fix bundle id on iOS launch using flutter run
* [#31308](https://github.com/flutter/flutter/pull/31308) Added font bold when isDefaultAction is true in CupertinoDialogAction
* [#31326](https://github.com/flutter/flutter/pull/31326) Add more shuffle cupertino icons
* [#31332](https://github.com/flutter/flutter/pull/31332) iOS selection handles are invisible
* [#31464](https://github.com/flutter/flutter/pull/31464) CupertinoPicker fidelity revision
* [#31623](https://github.com/flutter/flutter/pull/31623) fix edge swiping and dropping back at starting point
* [#31644](https://github.com/flutter/flutter/pull/31644) Cupertino localization step 12: push translation for all supported languages
* [#31687](https://github.com/flutter/flutter/pull/31687) Center iOS caret, remove constant offsets that do not scale
* [#31763](https://github.com/flutter/flutter/pull/31763) Fix ScrollbarPainter thumbExtent calculation and add padding
* [#31852](https://github.com/flutter/flutter/pull/31852) Text selection handles are sometimes not interactive
* [#32013](https://github.com/flutter/flutter/pull/32013) Cupertino Turkish Translation
* [#32086](https://github.com/flutter/flutter/pull/32086) Fix CupertinoSliverRefreshControl onRefresh callback
* [#32469](https://github.com/flutter/flutter/pull/32469) Let CupertinoNavigationBarBackButton take a custom onPressed
* [#32513](https://github.com/flutter/flutter/pull/32513) Cupertino localization step 12 try 2: push translation for all supported languages
* [#32620](https://github.com/flutter/flutter/pull/32620) Added ScrollController to TextField
* [#32823](https://github.com/flutter/flutter/pull/32823) Add enableInteractiveSelection to CupertinoTextField
* [#32974](https://github.com/flutter/flutter/pull/32974) Fix disabled CupertinoTextField style
* [#33450](https://github.com/flutter/flutter/pull/33450) Do not return null from IosProject.isSwift
* [#33624](https://github.com/flutter/flutter/pull/33624) CupertinoTabScaffold crash fix
* [#33634](https://github.com/flutter/flutter/pull/33634) Let there be scroll bars
* [#33653](https://github.com/flutter/flutter/pull/33653) Include advice about dispose in TextEditingController api
* [#33684](https://github.com/flutter/flutter/pull/33684) Disable CocoaPods input and output paths in Xcode build phase and adopt new Xcode build system
* [#33739](https://github.com/flutter/flutter/pull/33739) fixed cupertinoTextField placeholder textAlign
* [#33852](https://github.com/flutter/flutter/pull/33852) Disable CocoaPods input and output paths in Xcode build phase and adopt new Xcode build system
* [#34293](https://github.com/flutter/flutter/pull/34293) Change Xcode developmentRegion to 'en' and CFBundleDevelopmentRegion to DEVELOPMENT_LANGUAGE
* [#34964](https://github.com/flutter/flutter/pull/34964) CupertinoTextField.onTap
## Android
In this release, we've improved support for Android with new support for AndroidX from an external contributor (Thanks, [Josh](https://github.com/athornz)!) and supporting 64-bit and 32-bit APK bundles in compliance with [the Google Play Store's updated policy](https://developer.android.com/distribute/best-practices/develop/64-bit).
* [#31028](https://github.com/flutter/flutter/pull/31028) Adds support for generating projects that use AndroidX support libraries
* [#31359](https://github.com/flutter/flutter/pull/31359) Remove support for building dynamic patches on Android
* [#31491](https://github.com/flutter/flutter/pull/31491) Allow adb stdout to contain the port number without failing
* [#31835](https://github.com/flutter/flutter/pull/31835) Cherry-pick ADB CrOS fix to beta
* [#32787](https://github.com/flutter/flutter/pull/32787) Support 32 and 64 bit
* [#33191](https://github.com/flutter/flutter/pull/33191) Remove colon from Gradle task name since it's deprecated
* [#33611](https://github.com/flutter/flutter/pull/33611) Use Dart's new direct ELF generator to package AOT blobs as shared libraries in Android APKs
* [#33696](https://github.com/flutter/flutter/pull/33696) Generate ELF shared libraries and allow multi-abi libs in APKs and App bundles
* [#33901](https://github.com/flutter/flutter/pull/33901) Respond to AndroidView focus events.
* [#33923](https://github.com/flutter/flutter/pull/33923) [flutter_tool] Track APK sha calculation time
* [#33951](https://github.com/flutter/flutter/pull/33951) Whitelist adb.exe heap corruption exit code.
* [#34066](https://github.com/flutter/flutter/pull/34066) Adds the androidX flag to a modules pubspec.yaml template so it is se…
* [#34123](https://github.com/flutter/flutter/pull/34123) Generate ELF shared libraries and allow multi-abi libs in APKs and App bundles
## Material
This release includes a number of improvements to existing Material components, including the DatePicker, SnackBar and TimePicker, as well as a new component: the [RangeSlider](https://api.flutter.dev/flutter/material/RangeSlider-class.html).
* [#30572](https://github.com/flutter/flutter/pull/30572) [Material] Adaptive Slider constructor
* [#30884](https://github.com/flutter/flutter/pull/30884) [Material] Update TabController to support dynamic Tabs
* [#31018](https://github.com/flutter/flutter/pull/31018) [Material] selected/unselected label styles + icon themes on BottomNavigationBar
* [#31025](https://github.com/flutter/flutter/pull/31025) added scrimColor property in Scaffold widget
* [#31275](https://github.com/flutter/flutter/pull/31275) Update SnackBar to allow for support of the new style from Material spec
* [#31295](https://github.com/flutter/flutter/pull/31295) Improve ThemeData.accentColor connection to secondary color
* [#31318](https://github.com/flutter/flutter/pull/31318) Add BottomSheetTheme to enable theming color, elevation, shape of BottomSheet
* [#31438](https://github.com/flutter/flutter/pull/31438) Implements focus handling and hover for Material buttons.
* [#31514](https://github.com/flutter/flutter/pull/31514) Date picker layout exceptions
* [#31566](https://github.com/flutter/flutter/pull/31566) TimePicker moves to minute mode after hour selection
* [#31662](https://github.com/flutter/flutter/pull/31662) added shape property to SliverAppBar
* [#31681](https://github.com/flutter/flutter/pull/31681) [Material] Create a themable Range Slider (continuous and discrete)
* [#31693](https://github.com/flutter/flutter/pull/31693) Adds a note to Radio's/RadioListTile's onChange
* [#31902](https://github.com/flutter/flutter/pull/31902) Updated primaryColor docs to refer to colorScheme properties
* [#31938](https://github.com/flutter/flutter/pull/31938) Update scrimDrawerColor with proper const format
* [#32053](https://github.com/flutter/flutter/pull/32053) Increase TimePicker touch targets
* [#32070](https://github.com/flutter/flutter/pull/32070) rename foreground and background to light and dark [#32527](https://github.com/flutter/flutter/pull/32527) Added 'enabled' property to the PopupMenuButton
* [#32726](https://github.com/flutter/flutter/pull/32726) Material should not prevent ScrollNotifications from bubbling upwards
* [#32904](https://github.com/flutter/flutter/pull/32904) Use reverseDuration on Tooltip and InkWell
* [#32911](https://github.com/flutter/flutter/pull/32911) Material Long Press Text Handle Flash
* [#33073](https://github.com/flutter/flutter/pull/33073) SliverAppBar shape property
* [#34869](https://github.com/flutter/flutter/pull/34869) [Material] Properly call onChangeStart and onChangeEnd in Range Slider
* [#32950](https://github.com/flutter/flutter/pull/32950) Material allows "select all" when not collapsed
## Web
The work on web functionality continues with merging of the code from flutter_web repo into the main flutter repo, providing a simpler developer experience for this pre-release technology. We've already [compiled many of the existing Flutter samples for web](https://flutter.github.io/samples/). Enjoy!
* [#32360](https://github.com/flutter/flutter/pull/32360) Allow flutter web to be compiled with flutter
* [#33197](https://github.com/flutter/flutter/pull/33197) Wire up hot restart and incremental rebuilds for web
* [#33406](https://github.com/flutter/flutter/pull/33406) Add web safe indirection to Platform.isPlatform getters
* [#33525](https://github.com/flutter/flutter/pull/33525) Add capability to flutter test –platform=chrome
* [#33533](https://github.com/flutter/flutter/pull/33533) Reland - Wire up hot restart and incremental rebuilds for web
* [#33629](https://github.com/flutter/flutter/pull/33629) Add real-er restart for web using webkit inspection protocol
* [#33859](https://github.com/flutter/flutter/pull/33859) Reland support flutter test on platform chrome
* [#33892](https://github.com/flutter/flutter/pull/33892) add benchmarks to track web size
* [#33956](https://github.com/flutter/flutter/pull/33956) Codegen an entrypoint for flutter web applications
* [#34018](https://github.com/flutter/flutter/pull/34018) Add flutter create for the web
* [#34084](https://github.com/flutter/flutter/pull/34084) make running on web spooky
* [#34112](https://github.com/flutter/flutter/pull/34112) Separate web and io implementations of network image
* [#34159](https://github.com/flutter/flutter/pull/34159) Use product define for flutter web and remove extra asset server
* [#34589](https://github.com/flutter/flutter/pull/34589) Remove most of the target logic for build web, cleanup rules
* [#34856](https://github.com/flutter/flutter/pull/34856) set device name to Chrome
* [#34885](https://github.com/flutter/flutter/pull/34885) Reland: rename web device
## Desktop
The experimental support for desktop in Flutter continues as well, with many improvements to the basics needed on desktop like hover, focus traversal, shortcuts, actions and even game controllers! We've also continued to simplify the developer experience, which you can read about [here](http://github.com/google/flutter-desktop-embedding). This is very early, but if you are trying desktop support in Flutter, please [log issues](https://github.com/google/flutter-desktop-embedding/issues) when you find them!
* [#30076](https://github.com/flutter/flutter/pull/30076) Implements FocusTraversalPolicy and DefaultFocusTraversal features.
* [#30339](https://github.com/flutter/flutter/pull/30339) Add buttons to gestures
* [#31329](https://github.com/flutter/flutter/pull/31329) Add Xcode build script for macOS target
* [#31515](https://github.com/flutter/flutter/pull/31515) Support local engine and asset sync for macOS
* [#31567](https://github.com/flutter/flutter/pull/31567) Remove need for build/name scripts on Linux desktop
* [#31631](https://github.com/flutter/flutter/pull/31631) Teach Linux to use local engine
* [#31699](https://github.com/flutter/flutter/pull/31699) Re-land: Add support for Tooltip hover
* [#31802](https://github.com/flutter/flutter/pull/31802) Reland "Fix text field selection toolbar under Opacity (#31097)"
* [#31819](https://github.com/flutter/flutter/pull/31819) Redo: Add buttons to gestures
* [#31873](https://github.com/flutter/flutter/pull/31873) Add basic desktop linux checks
* [#31935](https://github.com/flutter/flutter/pull/31935) Redo#2: Add buttons to gestures
* [#32025](https://github.com/flutter/flutter/pull/32025) Make Hover Listener respect transforms
* [#32142](https://github.com/flutter/flutter/pull/32142) Fix RenderPointerListener so that callbacks aren't called at the wrong time.
* [#32335](https://github.com/flutter/flutter/pull/32335) Teach flutter msbuild for Windows
* [#32776](https://github.com/flutter/flutter/pull/32776) Text field focus and hover support.
* [#32838](https://github.com/flutter/flutter/pull/32838) Handles hidden by keyboard
* [#32914](https://github.com/flutter/flutter/pull/32914) Make hover and focus not respond when buttons and fields are disabled.
* [#33090](https://github.com/flutter/flutter/pull/33090) [Material] Add support for hovered, pressed, and focused text color on Buttons.
* [#33277](https://github.com/flutter/flutter/pull/33277) Implement macOS support in flutter doctor
* [#33279](https://github.com/flutter/flutter/pull/33279) Fix a problem in first focus determination.
* [#33298](https://github.com/flutter/flutter/pull/33298) Add actions and keyboard shortcut map support
* [#33443](https://github.com/flutter/flutter/pull/33443) Wrap Windows build invocation in a batch script
* [#33454](https://github.com/flutter/flutter/pull/33454) ensure unpack declares required artifacts
* [#33477](https://github.com/flutter/flutter/pull/33477) Fix onExit calling when the mouse is removed.
* [#33540](https://github.com/flutter/flutter/pull/33540) Pass local engine variables to Windows build
* [#33608](https://github.com/flutter/flutter/pull/33608) Restructure macOS project files
* [#33632](https://github.com/flutter/flutter/pull/33632) Update the keycodes from source
* [#33636](https://github.com/flutter/flutter/pull/33636) Implement plugin tooling support for macOS
* [#33695](https://github.com/flutter/flutter/pull/33695) Add pseudo-key synonyms for keys like shift, meta, alt, and control.
* [#33868](https://github.com/flutter/flutter/pull/33868) Game controller button support
* [#33872](https://github.com/flutter/flutter/pull/33872) Add 'doctor' support for Windows
* [#33874](https://github.com/flutter/flutter/pull/33874) Prevent windows web doctor from launching chrome
* [#34050](https://github.com/flutter/flutter/pull/34050) limit open files on macOS when copying assets
* [#34376](https://github.com/flutter/flutter/pull/34376) Add missing pieces for 'driver' support on macOS
* [#34755](https://github.com/flutter/flutter/pull/34755) Add linux doctor implementation
## Animation, Scrolling & Images
In this release, we continue to polish animations, scrolling and image support.
* [#21896](https://github.com/flutter/flutter/pull/21896) Bottom sheet scrolling
* [#28834](https://github.com/flutter/flutter/pull/28834) Sliver animated list [#29677](https://github.com/flutter/flutter/pull/29677) Fix calculation of hero rectTween when Navigator isn't fullscreen
* [#32730](https://github.com/flutter/flutter/pull/32730) Add reverseDuration to AnimationController
* [#32843](https://github.com/flutter/flutter/pull/32843) Added a missing dispose of an AnimationController that was leaking a ticker.
* [#31832](https://github.com/flutter/flutter/pull/31832) Allow DSS to be dragged when its children do not fill extent
* [#33627](https://github.com/flutter/flutter/pull/33627) SliverFillRemaining flag for different use cases
* [#32853](https://github.com/flutter/flutter/pull/32853) Add onBytesReceived callback to consolidateHttpClientResponseBytes()
* [#32857](https://github.com/flutter/flutter/pull/32857) Add debugNetworkImageHttpClientProvider
* [#32936](https://github.com/flutter/flutter/pull/32936) Add some sanity to the ImageStream listener API
* [#33729](https://github.com/flutter/flutter/pull/33729) Update consolidateHttpClientResponseBytes() to use compressionState
* [#33369](https://github.com/flutter/flutter/pull/33369) Add loading support to Image
## Typography & Accessibility
We're also continuing to push towards excellent typography and accessibility, including support for accessing OpenType font-specific features, as demonstrated in [this sample](https://github.com/timsneath/typography).
* [#31987](https://github.com/flutter/flutter/pull/31987) Text wrap width
* [#33230](https://github.com/flutter/flutter/pull/33230) Framework support for font features in text styles
* [#33808](https://github.com/flutter/flutter/pull/33808) fix ExpansionPanelList merge the header semantics when it is not necessary
* [#34368](https://github.com/flutter/flutter/pull/34368) Fix semantics_tester
* [#34434](https://github.com/flutter/flutter/pull/34434) Semantics fixes
## Fundamentals
As always, we continue to polish the fundamentals.
* [#30388](https://github.com/flutter/flutter/pull/30388) Add hintStyle in SearchDelegate
* [#30406](https://github.com/flutter/flutter/pull/30406) Add binaryMessenger constructor argument to platform channels
* [#30612](https://github.com/flutter/flutter/pull/30612) Added required parameters to FlexibleSpaceBarSettings
* [#30796](https://github.com/flutter/flutter/pull/30796) Unbounded TextField width error
* [#30942](https://github.com/flutter/flutter/pull/30942) rectMoreOrLess equals, prep for 64bit rects
* [#31282](https://github.com/flutter/flutter/pull/31282) Stop precaching the artifacts for dynamic mode.
* [#31485](https://github.com/flutter/flutter/pull/31485) Prevent exception being thrown on hasScrolledBody
* [#31520](https://github.com/flutter/flutter/pull/31520) Don't add empty OpacityLayer to the engine
* [#31526](https://github.com/flutter/flutter/pull/31526) replace no-op log reader with real implementation
* [#31757](https://github.com/flutter/flutter/pull/31757) Make FlutterProject factories synchronous
* [#31807](https://github.com/flutter/flutter/pull/31807) Make const available for classes that override AssetBundle
* [#31825](https://github.com/flutter/flutter/pull/31825) Fix missing return statements on function literals
* [#31861](https://github.com/flutter/flutter/pull/31861) Add Horizontal Padding to Constrained Chip Label Calculations
* [#31868](https://github.com/flutter/flutter/pull/31868) Handle notification errors
* [#31889](https://github.com/flutter/flutter/pull/31889) Start abstracting platform logic builds behind a shared interface
* [#32126](https://github.com/flutter/flutter/pull/32126) Bump multicast_dns version
* [#32192](https://github.com/flutter/flutter/pull/32192) Transform PointerEvents to the local coordinate system of the event receiver
* [#32328](https://github.com/flutter/flutter/pull/32328) Add breadcrumbs to TextOverflow
* [#32434](https://github.com/flutter/flutter/pull/32434) Support for replacing the TabController, after disposing the old one
* [#32528](https://github.com/flutter/flutter/pull/32528) Tapping a modal bottom sheet should not dismiss it by default
* [#33152](https://github.com/flutter/flutter/pull/33152) ModalRoute resumes previous focus on didPopNext
* [#33297](https://github.com/flutter/flutter/pull/33297) Instrument add to app flows
* [#33458](https://github.com/flutter/flutter/pull/33458) Add to app measurement
* [#33462](https://github.com/flutter/flutter/pull/33462) Fix text scaling of strut style
* [#33473](https://github.com/flutter/flutter/pull/33473) fix 23723 rounding error
* [#33474](https://github.com/flutter/flutter/pull/33474) Fixed for DropdownButton crashing when a style was used that didn't include a fontSize
* [#33475](https://github.com/flutter/flutter/pull/33475) Move declaration of semantic handlers from detectors to recognizers
* [#33488](https://github.com/flutter/flutter/pull/33488) use toFixedAsString and DoubleProperty in diagnosticProperties
* [#33802](https://github.com/flutter/flutter/pull/33802) Double double tap toggles instead of error
* [#33876](https://github.com/flutter/flutter/pull/33876) Reland "Framework support for font features in text styles"
* [#33886](https://github.com/flutter/flutter/pull/33886) Add currentSystemFrameTimeStamp to SchedulerBinding
* [#33955](https://github.com/flutter/flutter/pull/33955) Add localFocalPoint to ScaleDetector
* [#33999](https://github.com/flutter/flutter/pull/33999) Updating MediaQuery with viewPadding
* [#34055](https://github.com/flutter/flutter/pull/34055) Toggle toolbar exception fix
* [#34057](https://github.com/flutter/flutter/pull/34057) Add endIndent property to Divider and VerticalDivider
* [#34068](https://github.com/flutter/flutter/pull/34068) fix empty selection arrow when double clicked on empty read only text…
* [#34081](https://github.com/flutter/flutter/pull/34081) Report async callback errors that currently go unreported.
* [#34175](https://github.com/flutter/flutter/pull/34175) Don't show scrollbar if there isn't enough content
* [#34243](https://github.com/flutter/flutter/pull/34243) update the Flutter.Frame event to use new engine APIs
* [#34295](https://github.com/flutter/flutter/pull/34295) Prepare for Uint8List SDK breaking changes
* [#34298](https://github.com/flutter/flutter/pull/34298) Preserving SafeArea : Part 2
* [#34355](https://github.com/flutter/flutter/pull/34355) Text field vertical align
* [#34365](https://github.com/flutter/flutter/pull/34365) redux of a change to use new engine APIs for Flutter.Frame events
* [#34508](https://github.com/flutter/flutter/pull/34508) add route information to Flutter.Navigation events
* [#34512](https://github.com/flutter/flutter/pull/34512) Make sure fab semantics end up on top
* [#34515](https://github.com/flutter/flutter/pull/34515) OutlineInputBorder adjusts for borderRadius that is too large
* [#34519](https://github.com/flutter/flutter/pull/34519) fix page scroll position rounding error
* [#34526](https://github.com/flutter/flutter/pull/34526) retry on HttpException during cache download
* [#34529](https://github.com/flutter/flutter/pull/34529) Remove compilation trace and dynamic support code
* [#34573](https://github.com/flutter/flutter/pull/34573) Ensures flutter jar is added to all build types on plugin projects
* [#34587](https://github.com/flutter/flutter/pull/34587) Do not copy paths, rects, and rrects when layer offset is zero
* [#34932](https://github.com/flutter/flutter/pull/34932) Added onChanged property to TextFormField
* [#35092](https://github.com/flutter/flutter/pull/35092) Add FlutterProjectFactory so that it can be overridden internally.
* [#33272](https://github.com/flutter/flutter/pull/33272) Add mustRunAfter on mergeAssets task to force task ordering
* [#33535](https://github.com/flutter/flutter/pull/33535) Custom height parameters for DataTable header and data rows
* [#33628](https://github.com/flutter/flutter/pull/33628) DataTable Custom Horizontal Padding
## Tooling
Last but not least, we continue to polish and simplify our tooling as well, including providing a much clearer error message when the flutter tooling finds itself in a read-only directory (a common problem for Flutter developers that we're hoping this helps address).
* [#31342](https://github.com/flutter/flutter/pull/31342) check if project exists before regenerating platform specific tooling
* [#31399](https://github.com/flutter/flutter/pull/31399) add ignorable track-widget-creation flag to build aot
* [#31406](https://github.com/flutter/flutter/pull/31406) if there is no .ios or ios sub-project, don't attempt building for iOS
* [#31446](https://github.com/flutter/flutter/pull/31446) Allow filtering devices to only those supported by current project
* [#31591](https://github.com/flutter/flutter/pull/31591) make sure we exit early if the Runner.xcodeproj file is missing
* [#31804](https://github.com/flutter/flutter/pull/31804) only build asset when there is asset declared in pubspec
* [#31812](https://github.com/flutter/flutter/pull/31812) Fix #31764: Show appropriate error message when fonts pubspec.yaml isn't iterable
* [#32072](https://github.com/flutter/flutter/pull/32072) don't NPE with empty pubspec
* [#33041](https://github.com/flutter/flutter/pull/33041) Rename flutter packages to flutter pub
* [#33448](https://github.com/flutter/flutter/pull/33448) Use vswhere to find Visual Studio
* [#33472](https://github.com/flutter/flutter/pull/33472) add daemon command to enumerate supported platforms
* [#33924](https://github.com/flutter/flutter/pull/33924) Added –dart-flags option to flutter run
* [#33980](https://github.com/flutter/flutter/pull/33980) Increase daemon protocol version for getSupportedPlatforms
* [#33990](https://github.com/flutter/flutter/pull/33990) Add device category for daemon
* [#34181](https://github.com/flutter/flutter/pull/34181) Reland "Added –dart-flags option to flutter run (#33924)"
* [#34291](https://github.com/flutter/flutter/pull/34291) Check whether FLUTTER_ROOT and FLUTTER_ROOT/bin are writable.
* [#34353](https://github.com/flutter/flutter/pull/34353) Refactor Gradle plugin
* [#34517](https://github.com/flutter/flutter/pull/34517) pass .packages path to snapshot invocation
* [#34527](https://github.com/flutter/flutter/pull/34527) Don't crash on invalid .packages file
* [#34606](https://github.com/flutter/flutter/pull/34606) Remove portions of the Gradle script related to dynamic patching
* [#34616](https://github.com/flutter/flutter/pull/34616) Kill compiler process when test does not exit cleanly
* [#34624](https://github.com/flutter/flutter/pull/34624) Break down flutter doctor validations and results
* [#34683](https://github.com/flutter/flutter/pull/34683) add read only semantics flag
* [#34684](https://github.com/flutter/flutter/pull/34684) Add more structure to errors.
* [#34685](https://github.com/flutter/flutter/pull/34685) Close platform when tests are complete (dispose compiler and delete font files)
* [#34725](https://github.com/flutter/flutter/pull/34725) Fix NPE in flutter tools
* [#34736](https://github.com/flutter/flutter/pull/34736) Remove flags related to dynamic patching
* [#34785](https://github.com/flutter/flutter/pull/34785) Tweak the display name of emulators
* [#34794](https://github.com/flutter/flutter/pull/34794) Add emulatorID field to devices in daemon
* [#34802](https://github.com/flutter/flutter/pull/34802) Prefer ephemeral devices from command line run
* [#34859](https://github.com/flutter/flutter/pull/34859) Fix Vertical Alignment Regression
* [#35074](https://github.com/flutter/flutter/pull/35074) Attempt to enable tool coverage redux
* [#35084](https://github.com/flutter/flutter/pull/35084) Move findTargetDevices to DeviceManager
* [#33284](https://github.com/flutter/flutter/pull/33284) make sure we build test targets too
* [#33867](https://github.com/flutter/flutter/pull/33867) Remove environment variable guards for command line desktop and web
* [#33283](https://github.com/flutter/flutter/pull/33283) Fix relative paths and snapshot logic in tool
## Full Issue List
You can see the full list of issues addressed in this release [here](/release/release-notes/changelogs/changelog-1.7.8).
| website/src/release/release-notes/release-notes-1.7.8.md/0 | {
"file_path": "website/src/release/release-notes/release-notes-1.7.8.md",
"repo_id": "website",
"token_count": 10508
} | 1,318 |
---
title: What's new
description: >-
A list of what's new on docs.flutter.dev and related documentation sites.
---
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][].
[release notes]: /release/release-notes
[flutter-announce]: {{site.groups}}/forum/#!forum/flutter-announce
[Dart Announce]: {{site.groups}}/a/dartlang.org/g/announce
[Dart changelog]: {{site.github}}/dart-lang/sdk/blob/main/CHANGELOG.md
## 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][3.19-umbrella]
and the [Flutter 3.19 technical blog post][3.19-tech].
You might also check out the [Dart 3.3 release][] blog post.
[3.19-tech]: {{site.flutter-medium}}/whats-new-in-flutter-3-19-58b1aae242d2
[3.19-umbrella]: {{site.flutter-medium}}/starting-2024-strong-with-flutter-and-dart-cae9845264fe
[Dart 3.3 release]: {{site.medium}}/dartlang/new-in-dart-3-3-extension-types-javascript-interop-and-more-325bf2bf6c13
**Docs updated or added since the 3.16 release**
* A new page on [migrating from Material 2 to Material 3][]
is added. Thanks to [@TahaTesser][] for writing this guide.
* Material 3 uses theming in new and different ways than
Material 2. The [Use themes to share colors and font styles][]
cookbook recipe is updated to reflect these changes.
* The [Flutter install][] pages have been updated. Please
[let us know][] if you have any feedback.
* The [Concurrency and isolates][] page has been reworked.
[@TahaTesser]: {{site.github}}/TahaTesser
[Concurrency and isolates]: /perf/isolates
[Flutter install]: /get-started/install
[let us know]: {{site.github}}/flutter/website/issues/new/choose
[migrating from Material 2 to Material 3]: /release/breaking-changes/material-3-migration
[Use themes to share colors and font styles]: /cookbook/design/themes
**Other updates**
* Check out the just-published
[Flutter and Dart 2024 Roadmap][].
* Check out [Harness the Gemini API in your Dart and Flutter apps][].
[Flutter and Dart 2024 Roadmap]: {{site.github}}/flutter/flutter/wiki/Roadmap
[Harness the Gemini API in your Dart and Flutter apps]: {{site.flutter-medium}}/harness-the-gemini-api-in-your-dart-and-flutter-apps-00573e560381
---
For past releases, check out the
[What's new archive][] page.
[What's new archive]: /release/archive-whats-new
| website/src/release/whats-new.md/0 | {
"file_path": "website/src/release/whats-new.md",
"repo_id": "website",
"token_count": 891
} | 1,319 |
---
title: Security
description: >
An overview of the Flutter's team philosophy and processes for security.
---
The Flutter team takes the security of Flutter and the applications
created with it seriously. This page describes how to report any
vulnerabilities you might find, and lists best practices to minimize
the risk of introducing a vulnerability.
## Security philosophy
Flutter security strategy is based on five key pillars:
* **Identify**: Track and prioritize key security risks by
identifying core assets, key threats, and vulnerabilities.
* **Detect**: Detect and identify vulnerabilities using
techniques and tools like vulnerability scanning,
static application security testing, and fuzzing.
* **Protect**: Eliminate risks by mitigating known
vulnerabilities and protect critical assets against source threats.
* **Respond**: Define processes to report, triage, and
respond to vulnerabilities or attacks.
* **Recover**: Build capabilities to contain and recover
from an incident with minimal impact.
## Reporting vulnerabilities
Before reporting a security vulnerability found
by a static analysis tool,
consider checking our list of [known false positives][].
To report a vulnerability, email `[email protected]`
with a description of the issue,
the steps you took to create the issue,
affected versions, and if known, mitigations for the issue.
We should reply within three working days.
We use GitHub's security advisory feature to track
open security issues. You should expect a close collaboration
as we work to resolve the issue that you have reported.
Please reach out to `[email protected]` again if
you don't receive prompt attention and regular updates.
You might also reach out to the team using our public
[Discord chat channels][]; however, when reporting an issue,
e-mail `[email protected]`.
To avoid revealing information about vulnerabilities
in public that could put users at risk,
**don't post to Discord or file a GitHub issue**.
For more details on how we handle security vulnerabilities,
see our [security policy][].
[Discord chat channels]: {{site.repo.flutter}}/wiki/Chat
[known false positives]: /reference/security-false-positives
[security policy]: {{site.repo.flutter}}/security/policy
## Flagging existing issues as security-related
If you believe that an existing issue is security-related,
we ask that you send an email to `[email protected]`.
The email should include the issue ID and a short description
of why it should be handled according to this security policy.
## Supported versions
We commit to publishing security updates for the version of
Flutter currently on the `stable` branch.
## Expectations
We treat security issues equivalent to a P0 priority level
and release a beta or hotfix for any major security issues
found in the most recent stable version of our SDK.
Any vulnerability reported for flutter websites like
docs.flutter.dev doesn't require a release and will be
fixed in the website itself.
## Bug Bounty programs
Contributing teams can include Flutter within the scope
of their bug bounty programs. To have your program listed,
contact `[email protected]`.
Google considers Flutter to be in scope for the
[Google Open Source Software Vulnerability Reward Program][google-oss-vrp].
For expediency, reporters should contact `[email protected]`
before using Google's vulnerability reporting flow.
[google-oss-vrp]: https://bughunters.google.com/open-source-security
## Receiving security updates
The best way to receive security updates is to subscribe to the
[flutter-announce][] mailing list or watch updates to the
[Discord channel][]. We also announce security updates in the
technical release blog post.
[Discord channel]: https://discord.gg/BS8KZyg
[flutter-announce]: {{site.groups}}/forum/#!forum/flutter-announce
## Best practices
* **Keep current with the latest Flutter SDK releases.**
We regularly update Flutter, and these updates might fix security
defects discovered in previous versions. Check the Flutter
[change log][] for security-related updates.
* **Keep your application's dependencies up to date.**
Make sure you [upgrade your package dependencies][]
to keep the dependencies up to date.
Avoid pinning to specific versions
for your dependencies and, if you do, make sure you check
periodically to see if your dependencies have had security updates,
and update the pin accordingly.
* **Keep your copy of Flutter up to date.**
Private, customized versions of Flutter tend
to fall behind the current version and might not
include important security fixes and enhancements.
Instead, routinely update your copy of Flutter.
If you're making changes to improve Flutter,
be sure to update your fork and consider sharing your
changes with the community.
[change log]: {{site.repo.flutter}}/wiki/Changelog
[upgrade your package dependencies]: /release/upgrade
| website/src/security/index.md/0 | {
"file_path": "website/src/security/index.md",
"repo_id": "website",
"token_count": 1181
} | 1,320 |
```nocode
flutter: SemanticsNode#0
flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)
flutter: │
flutter: └─SemanticsNode#1
flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)
flutter: │ textDirection: ltr
flutter: │
flutter: └─SemanticsNode#2
flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)
flutter: │ sortKey: OrdinalSortKey#824a2(order: 0.0)
flutter: │
flutter: └─SemanticsNode#3
flutter: │ Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)
flutter: │ flags: scopesRoute
flutter: │
flutter: └─SemanticsNode#4
flutter: Rect.fromLTRB(278.0, 267.0, 522.0, 333.0)
flutter: actions: tap
flutter: flags: isButton, hasEnabledState, isEnabled
flutter: label:
flutter: "Clickable text here!
flutter: Click Me!"
flutter: textDirection: ltr
flutter:
flutter: Clicked!
```
| website/src/testing/trees/semantic-tree.md/0 | {
"file_path": "website/src/testing/trees/semantic-tree.md",
"repo_id": "website",
"token_count": 480
} | 1,321 |
---
title: Using the Debug console
description: Learn how to use the DevTools 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.
{{site.alert.note}}
This page is up to date for DevTools 2.23.0.
{{site.alert.end}}
The Debug console is available from the [Inspector][],
[Debugger][], and [Memory][] views.
[Inspector]: /tools/devtools/inspector
[Debugger]: /tools/devtools/debugger
[Memory]: /tools/devtools/memory
## Watch application output
The console shows the application's standard output (`stdout`):

## Explore inspected widgets
If you click a widget on the **Inspector** screen,
the variable for this widget displays in the **Console**:
{:width="100%"}
## 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`:
{:width="100%"}
## Browse heap snapshot
To drop a variable to the console from a heap snapshot,
do the following:
1. Navigate to **Devtools > Memory > Diff Snapshots**.
1. Record a memory heap snapshot.
1. Click on the context menu `[⋮]` to view the number of
**Instances** for the desired **Class**.
1. Select whether you want to store a single instance as
a console variable, or whether you want to store _all_
currently alive instances in the app.
{:width="100%"}
The Console screen displays both live and static
inbound and outbound references, as well as field values:
{:width="100%"}
| website/src/tools/devtools/console.md/0 | {
"file_path": "website/src/tools/devtools/console.md",
"repo_id": "website",
"token_count": 686
} | 1,322 |
---
short-title: 2.13.1 release notes
description: Release notes for Dart and Flutter DevTools version 2.13.1.
toc: false
---
{% include_relative release-notes-2.13.1-src.md %}
| website/src/tools/devtools/release-notes/release-notes-2.13.1.md/0 | {
"file_path": "website/src/tools/devtools/release-notes/release-notes-2.13.1.md",
"repo_id": "website",
"token_count": 61
} | 1,323 |
---
short-title: 2.21.1 release notes
description: Release notes for Dart and Flutter DevTools version 2.21.1.
toc: false
---
{% include_relative release-notes-2.21.1-src.md %}
| website/src/tools/devtools/release-notes/release-notes-2.21.1.md/0 | {
"file_path": "website/src/tools/devtools/release-notes/release-notes-2.21.1.md",
"repo_id": "website",
"token_count": 61
} | 1,324 |
---
short-title: 2.28.2 release notes
description: Release notes for Dart and Flutter DevTools version 2.28.2.
toc: false
---
{% include_relative release-notes-2.28.2-src.md %}
| website/src/tools/devtools/release-notes/release-notes-2.28.2.md/0 | {
"file_path": "website/src/tools/devtools/release-notes/release-notes-2.28.2.md",
"repo_id": "website",
"token_count": 61
} | 1,325 |
---
short-title: 2.33.0 release notes
description: Release notes for Dart and Flutter DevTools version 2.33.0.
toc: false
---
{% include_relative release-notes-2.33.0-src.md %}
| website/src/tools/devtools/release-notes/release-notes-2.33.0.md/0 | {
"file_path": "website/src/tools/devtools/release-notes/release-notes-2.33.0.md",
"repo_id": "website",
"token_count": 61
} | 1,326 |
---
title: Flutter SDK overview
short-title: Flutter SDK
description: Flutter libraries and command-line tools.
---
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][].
## What's in the Flutter SDK
The following is available through the Flutter SDK:
* [Dart SDK][]
* Heavily optimized, mobile-first 2D rendering engine with
excellent support for text
* Modern react-style framework
* Rich set of widgets implementing Material Design and iOS styles
* APIs for unit and integration tests
* Interop and plugin APIs to connect to the system and 3rd-party SDKs
* Headless test runner for running tests on Windows, Linux, and Mac
* [Dart DevTools][] for testing, debugging, and profiling your app
* `flutter` and `dart` command-line tools for creating, building, testing,
and compiling your apps
Note: For more information about the Flutter SDK, see its
[README file][].
## `flutter` command-line tool
The [`flutter` CLI tool][] (`flutter/bin/flutter`) is how developers
(or IDEs on behalf of developers) interact with Flutter.
## `dart` command-line tool
The [`dart` CLI tool][] is available with the Flutter SDK at `flutter/bin/dart`.
[Dart DevTools]: /tools/devtools
[Dart SDK]: {{site.dart-site}}/tools/sdk
[`dart` CLI tool]: {{site.dart-site}}/tools/dart-tool
[`flutter` CLI tool]: /reference/flutter-cli
[Install]: /get-started/install
[README file]: {{site.repo.flutter}}/blob/master/README.md
| website/src/tools/sdk.md/0 | {
"file_path": "website/src/tools/sdk.md",
"repo_id": "website",
"token_count": 450
} | 1,327 |
---
layout: toc
title: Design & theming
description: Content covering designing Flutter apps.
sitemap: false
---
| website/src/ui/design/index.md/0 | {
"file_path": "website/src/ui/design/index.md",
"repo_id": "website",
"token_count": 32
} | 1,328 |
---
layout: toc
title: Responsive & adaptive design
short-title: Adaptive design
description: >
Content covering making Flutter apps adaptive to
different device features and layouts.
sitemap: false
---
| website/src/ui/layout/responsive/index.md/0 | {
"file_path": "website/src/ui/layout/responsive/index.md",
"repo_id": "website",
"token_count": 53
} | 1,329 |
---
title: Layout widgets
short-title: Layout
description: A catalog of Flutter's widgets for building layouts.
---
{% include docs/catalogpage.html category="Layout" %}
| website/src/ui/widgets/layout.md/0 | {
"file_path": "website/src/ui/widgets/layout.md",
"repo_id": "website",
"token_count": 47
} | 1,330 |
// Copyright 2024 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 'dart:async';
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:path/path.dart' as path;
import '../utils.dart';
final class RefreshExcerptsCommand extends Command<int> {
static const String _verboseFlag = 'verbose';
static const String _deleteCacheFlag = 'delete-cache';
static const String _failOnUpdateFlag = 'fail-on-update';
RefreshExcerptsCommand() {
argParser.addFlag(
_verboseFlag,
defaultsTo: false,
help: 'Show verbose logging.',
);
argParser.addFlag(
_deleteCacheFlag,
defaultsTo: false,
help: 'Delete dart build tooling and cache files after running.',
);
argParser.addFlag(
_failOnUpdateFlag,
defaultsTo: false,
help: 'Fails if updates were needed.',
);
}
@override
String get description => 'Updates all code excerpts on the site.';
@override
String get name => 'refresh-excerpts';
@override
Future<int> run() async => _refreshExcerpts(
verboseLogging: argResults.get<bool>(_verboseFlag, false),
deleteCache: argResults.get<bool>(_deleteCacheFlag, false),
failOnUpdate: argResults.get<bool>(_failOnUpdateFlag, false));
}
Future<int> _refreshExcerpts({
bool verboseLogging = false,
bool deleteCache = false,
bool failOnUpdate = false,
}) async {
// TODO: Replace diffutils with cross-platform solution.
final diffVersionOutput =
Process.runSync('diff', ['--version']).stdout.toString();
final diffVersionLine = RegExp(r'^diff.*(3\.\d+)$', multiLine: true)
.firstMatch(diffVersionOutput);
if (diffVersionLine == null) {
stderr.writeln(
'Error: diffutils must be installed to refresh code excerpts!',
);
return 1;
} else {
final diffVersion = double.tryParse(diffVersionLine[1] ?? '');
if (diffVersion == null || diffVersion < 3.6) {
stderr.writeln(
'Error: diffutils version >=3.6 required - your version: $diffVersion!',
);
return 1;
}
}
final repositoryRoot = Directory.current.path;
final temporaryRoot = Directory.systemTemp.path;
final fragments = path.join(temporaryRoot, '_excerpter_fragments');
// Delete any existing fragments.
final fragmentsDirectory = Directory(fragments);
if (fragmentsDirectory.existsSync()) {
if (verboseLogging) {
print('Deleting previously generated $fragments.');
}
fragmentsDirectory.deleteSync(recursive: true);
}
print('Running the code excerpt fragment generator...');
// Run the code excerpter tool to generate the fragments used for updates.
final excerptsGenerated = Process.runSync(Platform.resolvedExecutable, [
'run',
'build_runner',
'build',
'--delete-conflicting-outputs',
'--config',
'excerpt',
'--output',
fragments,
]);
if (verboseLogging) {
print(excerptsGenerated.stdout);
}
// If the excerpt fragments were not generated successfully,
// then output the error log and return 1 to indicate failure.
if (excerptsGenerated.exitCode != 0) {
stderr.writeln('Error: Excerpt generation failed:');
stderr.writeln(excerptsGenerated.stderr);
return 1;
}
print('Code excerpt fragments generated successfully.');
// Verify the fragments directory for the /examples was generated properly.
if (!Directory(path.join(fragments, 'examples')).existsSync()) {
stderr.writeln(
'Error: The examples fragments folder was not generated!',
);
return 1;
}
// A collection of replacements for the code excerpt updater tool
// to run by default.
// They must not contain (unencoded/unescaped) spaces.
const replacements = [
// Allows use of //!<br> to force a line break (against dart format)
r'/\/\/!<br>//g;',
// Replace commented out ellipses: /*...*/ --> ...
r'/\/\*(\s*\.\.\.\s*)\*\//$1/g;',
// Replace brackets with commented out ellipses: {/*-...-*/} --> ...
r'/\{\/\*-(\s*\.\.\.\s*)-\*\/\}/$1/g;',
// Remove markers declaring an analysis issue or runtime error.
r'/\/\/!(analysis-issue|runtime-error)[^\n]*//g;',
// Remove analyzer ignore for file markers.
r'/\x20*\/\/\s+ignore_for_file:[^\n]+\n//g;',
// Remove analyzer inline ignores.
r'/\x20*\/\/\s+ignore:[^\n]+//g;',
];
final srcDirectoryPath = path.join(repositoryRoot, 'src');
final updaterArguments = <String>[
'--fragment-dir-path',
path.join(fragments, 'examples'),
'--src-dir-path',
'examples',
if (verboseLogging) '--log-fine',
'--yaml',
'--no-escape-ng-interpolation',
'--replace=${replacements.join('')}',
'--write-in-place',
srcDirectoryPath,
];
print('Running the code excerpt updater...');
// Open a try block so we can guarantee
// any temporary files are deleted.
try {
// Run the code excerpt updater tool to update the code excerpts
// in the /src directory.
final excerptsUpdated = Process.runSync(Platform.resolvedExecutable, [
'run',
'code_excerpt_updater',
...updaterArguments,
]);
final updateOutput = excerptsUpdated.stdout.toString();
final updateErrors = excerptsUpdated.stderr.toString();
final bool success;
// Inform the user if the updater failed, didn't need to make any updates,
// or successfully refreshed each excerpt.
if (excerptsUpdated.exitCode != 0 || updateErrors.contains('Error')) {
stderr.writeln('Error: Excerpt generation failed:');
stderr.write(updateErrors);
success = false;
} else if (updateOutput.contains('0 out of')) {
if (verboseLogging) {
print(updateOutput);
}
print('All code excerpts are already up to date!');
success = true;
} else {
stdout.write(updateOutput);
if (failOnUpdate) {
stderr.writeln('Error: Some code excerpts needed to be updated!');
success = false;
} else {
print('Code excerpts successfully refreshed!');
success = true;
}
}
return success ? 0 : 1;
} finally {
// Clean up Dart build cache files if desired.
if (deleteCache) {
if (verboseLogging) {
print('Removing cached build files.');
}
final dartBuildCache = Directory(path.join('.dart_tool', 'build'));
if (dartBuildCache.existsSync()) {
dartBuildCache.deleteSync(recursive: true);
}
}
}
}
| website/tool/flutter_site/lib/src/commands/refresh_excerpts.dart/0 | {
"file_path": "website/tool/flutter_site/lib/src/commands/refresh_excerpts.dart",
"repo_id": "website",
"token_count": 2359
} | 1,331 |
#import "GeneratedPluginRegistrant.h"
| codelabs/adaptive_app/step_03/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/adaptive_app/step_03/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 0 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/adaptive_app/step_03/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/adaptive_app/step_03/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 1 |
import 'package:adaptive_app/main.dart';
import 'package:adaptive_app/src/app_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:googleapis/youtube/v3.dart';
import 'package:provider/provider.dart';
class FakeFlutterDevPlaylists extends ChangeNotifier
implements FlutterDevPlaylists {
@override
List<PlaylistItem> playlistItems({required String playlistId}) => [];
@override
List<Playlist> get playlists => [];
}
void main() {
testWidgets('smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(
ChangeNotifierProvider<FlutterDevPlaylists>(
create: (context) => FakeFlutterDevPlaylists(),
child: const PlaylistsApp(),
),
);
});
}
| codelabs/adaptive_app/step_05/test/widget_test.dart/0 | {
"file_path": "codelabs/adaptive_app/step_05/test/widget_test.dart",
"repo_id": "codelabs",
"token_count": 280
} | 2 |
.dockerignore
Dockerfile
build/
.dart_tool/
.git/
.github/
.gitignore
.idea/
.packages
| codelabs/adaptive_app/step_06/yt_cors_proxy/.dockerignore/0 | {
"file_path": "codelabs/adaptive_app/step_06/yt_cors_proxy/.dockerignore",
"repo_id": "codelabs",
"token_count": 38
} | 3 |
include: package:lints/recommended.yaml
linter:
rules:
avoid_print: false
directives_ordering: true
prefer_single_quotes: true
sort_pub_dependencies: true
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
| codelabs/adaptive_app/step_07/yt_cors_proxy/analysis_options.yaml/0 | {
"file_path": "codelabs/adaptive_app/step_07/yt_cors_proxy/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 94
} | 4 |
#import "GeneratedPluginRegistrant.h"
| codelabs/animated-responsive-layout/step_03/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "codelabs/animated-responsive-layout/step_03/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "codelabs",
"token_count": 13
} | 5 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/animated-responsive-layout/step_03/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/animated-responsive-layout/step_03/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 6 |
#include "Generated.xcconfig"
| codelabs/animated-responsive-layout/step_05/ios/Flutter/Release.xcconfig/0 | {
"file_path": "codelabs/animated-responsive-layout/step_05/ios/Flutter/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 7 |
name: animated_responsive_layout
description: "A new Flutter project."
publish_to: 'none'
version: 0.1.0
environment:
sdk: '>=3.3.0-279.2.beta <4.0.0'
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
assets:
- assets/avatar_1.png
- assets/avatar_2.png
- assets/avatar_3.png
- assets/avatar_4.png
- assets/avatar_5.png
- assets/avatar_6.png
- assets/avatar_7.png
- assets/thumbnail_1.png
| codelabs/animated-responsive-layout/step_06/pubspec.yaml/0 | {
"file_path": "codelabs/animated-responsive-layout/step_06/pubspec.yaml",
"repo_id": "codelabs",
"token_count": 243
} | 8 |
// Copyright 2022 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/animation.dart';
class BarAnimation extends ReverseAnimation {
BarAnimation({required AnimationController parent})
: super(
CurvedAnimation(
parent: parent,
curve: const Interval(0, 1 / 5),
reverseCurve: const Interval(1 / 5, 4 / 5),
),
);
}
class OffsetAnimation extends CurvedAnimation {
OffsetAnimation({required super.parent})
: super(
curve: const Interval(
2 / 5,
3 / 5,
curve: Curves.easeInOutCubicEmphasized,
),
reverseCurve: Interval(
4 / 5,
1,
curve: Curves.easeInOutCubicEmphasized.flipped,
),
);
}
class RailAnimation extends CurvedAnimation {
RailAnimation({required super.parent})
: super(
curve: const Interval(0 / 5, 4 / 5),
reverseCurve: const Interval(3 / 5, 1),
);
}
class RailFabAnimation extends CurvedAnimation {
RailFabAnimation({required super.parent})
: super(
curve: const Interval(3 / 5, 1),
);
}
class ScaleAnimation extends CurvedAnimation {
ScaleAnimation({required super.parent})
: super(
curve: const Interval(
3 / 5,
4 / 5,
curve: Curves.easeInOutCubicEmphasized,
),
reverseCurve: Interval(
3 / 5,
1,
curve: Curves.easeInOutCubicEmphasized.flipped,
),
);
}
class ShapeAnimation extends CurvedAnimation {
ShapeAnimation({required super.parent})
: super(
curve: const Interval(
2 / 5,
3 / 5,
curve: Curves.easeInOutCubicEmphasized,
),
);
}
class SizeAnimation extends CurvedAnimation {
SizeAnimation({required super.parent})
: super(
curve: const Interval(
0 / 5,
3 / 5,
curve: Curves.easeInOutCubicEmphasized,
),
reverseCurve: Interval(
2 / 5,
1,
curve: Curves.easeInOutCubicEmphasized.flipped,
),
);
}
| codelabs/animated-responsive-layout/step_07/lib/animations.dart/0 | {
"file_path": "codelabs/animated-responsive-layout/step_07/lib/animations.dart",
"repo_id": "codelabs",
"token_count": 1110
} | 9 |
include: ../../analysis_options.yaml
| codelabs/animated-responsive-layout/step_08/analysis_options.yaml/0 | {
"file_path": "codelabs/animated-responsive-layout/step_08/analysis_options.yaml",
"repo_id": "codelabs",
"token_count": 12
} | 10 |
// Copyright 2022 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 '../models/data.dart' as data;
import 'email_widget.dart';
class ReplyListView extends StatelessWidget {
const ReplyListView({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: 8.0),
child: ListView(
children: [
const SizedBox(height: 8),
...List.generate(data.replies.length, (index) {
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: EmailWidget(
email: data.replies[index],
isPreview: false,
isThreaded: true,
showHeadline: index == 0,
),
);
}),
],
),
);
}
}
| codelabs/animated-responsive-layout/step_08/lib/widgets/reply_list_view.dart/0 | {
"file_path": "codelabs/animated-responsive-layout/step_08/lib/widgets/reply_list_view.dart",
"repo_id": "codelabs",
"token_count": 437
} | 11 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/animated-responsive-layout/step_08/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/animated-responsive-layout/step_08/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 12 |
// Copyright 2022 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 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../classes/classes.dart';
part 'playback_event.dart';
part 'playback_state.dart';
part 'playback_bloc.freezed.dart';
class PlaybackBloc extends Bloc<PlaybackEvent, PlaybackState> {
PlaybackBloc() : super(PlaybackState.initial()) {
on<PlaybackEvent>(
(event, emit) => event.map(
changeSong: (event) => _changeSong(event, emit),
moveToInSong: (event) => _moveToInSong(event, emit),
setVolume: (event) => _setVolume(event, emit),
songProgress: (event) => _songProgress(event, emit),
toggleMute: (event) => _toggleMute(event, emit),
togglePlayPause: (event) => _togglePlayPause(event, emit),
),
);
}
static const _playbackUpdateInterval = Duration(milliseconds: 100);
StreamSubscription<Duration>? _currentlyPlayingSubscription;
Stream<Duration> _startPlayingStream() async* {
while (state.songWithProgress!.progress <
state.songWithProgress!.song.length) {
await Future<void>.delayed(_playbackUpdateInterval);
yield _playbackUpdateInterval;
if (state.songWithProgress!.progress >=
state.songWithProgress!.song.length) {
add(const PlaybackEvent.togglePlayPause());
break;
}
}
}
void _handlePlaybackProgress(Duration progress) => add(
PlaybackEvent.songProgress(progress),
);
void _togglePlayPause(TogglePlayPause event, Emitter<PlaybackState> emit) {
state.isPlaying ? _pausePlayback() : _resumePlayback();
emit(state.copyWith(isPlaying: !state.isPlaying));
}
void _pausePlayback() => _currentlyPlayingSubscription!.cancel();
void _resumePlayback() => _currentlyPlayingSubscription =
_startPlayingStream().listen(_handlePlaybackProgress);
void _changeSong(ChangeSong event, Emitter<PlaybackState> emit) {
emit(
state.copyWith(
isPlaying: true,
songWithProgress: SongWithProgress(
progress: const Duration(),
song: event.song,
),
),
);
_resumePlayback();
}
void _songProgress(SongProgress event, Emitter<PlaybackState> emit) => emit(
state.copyWith(
songWithProgress: state.songWithProgress!.copyWith(
progress: state.songWithProgress!.progress + event.duration,
),
),
);
void _setVolume(SetVolume event, Emitter<PlaybackState> emit) => emit(
state.copyWith(
volume: event.value,
isMuted: false,
previousVolume: null,
),
);
void _toggleMute(ToggleMute event, Emitter<PlaybackState> emit) {
if (state.isMuted) {
emit(
state.copyWith(
isMuted: false,
volume: state.previousVolume!,
previousVolume: null,
),
);
} else {
emit(
state.copyWith(
isMuted: true,
volume: 0,
previousVolume: state.volume,
),
);
}
}
void _moveToInSong(MoveToInSong event, Emitter<PlaybackState> emit) {
_pausePlayback();
final targetMilliseconds =
state.songWithProgress!.song.length.inMilliseconds * event.percent;
emit(
state.copyWith(
isPlaying: false,
songWithProgress: state.songWithProgress!.copyWith(
progress: Duration(milliseconds: targetMilliseconds.toInt()),
),
),
);
}
@override
Future<void> close() async {
await _currentlyPlayingSubscription?.cancel();
await super.close();
}
}
| codelabs/boring_to_beautiful/final/lib/src/shared/playback/bloc/playback_bloc.dart/0 | {
"file_path": "codelabs/boring_to_beautiful/final/lib/src/shared/playback/bloc/playback_bloc.dart",
"repo_id": "codelabs",
"token_count": 1503
} | 13 |
// Copyright 2022 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';
class CenterRow extends StatelessWidget {
const CenterRow({
super.key,
required this.child,
});
final Widget child;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: Center(
child: child,
),
),
],
);
}
}
| codelabs/boring_to_beautiful/final/lib/src/shared/views/center_row.dart/0 | {
"file_path": "codelabs/boring_to_beautiful/final/lib/src/shared/views/center_row.dart",
"repo_id": "codelabs",
"token_count": 208
} | 14 |
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <desktop_window/desktop_window_plugin.h>
#include <dynamic_color/dynamic_color_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) desktop_window_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "DesktopWindowPlugin");
desktop_window_plugin_register_with_registrar(desktop_window_registrar);
g_autoptr(FlPluginRegistrar) dynamic_color_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "DynamicColorPlugin");
dynamic_color_plugin_register_with_registrar(dynamic_color_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
}
| codelabs/boring_to_beautiful/final/linux/flutter/generated_plugin_registrant.cc/0 | {
"file_path": "codelabs/boring_to_beautiful/final/linux/flutter/generated_plugin_registrant.cc",
"repo_id": "codelabs",
"token_count": 352
} | 15 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/boring_to_beautiful/step_01/android/gradle.properties/0 | {
"file_path": "codelabs/boring_to_beautiful/step_01/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 16 |
// Copyright 2022 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 'dart:math';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../../shared/providers/artists.dart';
import './artist_card.dart';
class ArtistsScreen extends StatelessWidget {
const ArtistsScreen({super.key});
@override
Widget build(BuildContext context) {
final artistsProvider = ArtistsProvider();
final artists = artistsProvider.artists;
return LayoutBuilder(builder: (context, constraints) {
return Scaffold(
primary: false,
appBar: AppBar(
title: const Text('ARTISTS'),
toolbarHeight: kToolbarHeight * 2,
),
body: GridView.builder(
padding: const EdgeInsets.all(15),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: max(1, (constraints.maxWidth ~/ 400).toInt()),
childAspectRatio: 2.5,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemCount: artists.length,
itemBuilder: (context, index) {
final artist = artists[index];
return GestureDetector(
child: ArtistCard(
artist: artist,
),
onTap: () => GoRouter.of(context).go('/artists/${artist.id}'),
);
},
),
);
});
}
}
| codelabs/boring_to_beautiful/step_01/lib/src/features/artists/view/artists_screen.dart/0 | {
"file_path": "codelabs/boring_to_beautiful/step_01/lib/src/features/artists/view/artists_screen.dart",
"repo_id": "codelabs",
"token_count": 658
} | 17 |
// Copyright 2022 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.
class Event {
const Event({
required this.date,
required this.title,
required this.location,
required this.link,
});
final String date;
final String title;
final String location;
final String link;
}
| codelabs/boring_to_beautiful/step_01/lib/src/shared/classes/event.dart/0 | {
"file_path": "codelabs/boring_to_beautiful/step_01/lib/src/shared/classes/event.dart",
"repo_id": "codelabs",
"token_count": 116
} | 18 |
// Copyright 2022 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 'dart:math';
import 'package:flutter/material.dart';
import 'package:material_color_utilities/material_color_utilities.dart';
class NoAnimationPageTransitionsBuilder extends PageTransitionsBuilder {
const NoAnimationPageTransitionsBuilder();
@override
Widget buildTransitions<T>(
PageRoute<T> route,
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return child;
}
}
class ThemeSettingChange extends Notification {
ThemeSettingChange({required this.settings});
final ThemeSettings settings;
}
class ThemeProvider extends InheritedWidget {
const ThemeProvider(
{super.key,
required this.settings,
required this.lightDynamic,
required this.darkDynamic,
required super.child});
final ValueNotifier<ThemeSettings> settings;
final ColorScheme? lightDynamic;
final ColorScheme? darkDynamic;
final pageTransitionsTheme = const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
TargetPlatform.linux: NoAnimationPageTransitionsBuilder(),
TargetPlatform.macOS: NoAnimationPageTransitionsBuilder(),
TargetPlatform.windows: NoAnimationPageTransitionsBuilder(),
},
);
Color custom(CustomColor custom) {
if (custom.blend) {
return blend(custom.color);
} else {
return custom.color;
}
}
Color blend(Color targetColor) {
return Color(
Blend.harmonize(targetColor.value, settings.value.sourceColor.value));
}
Color source(Color? target) {
Color source = settings.value.sourceColor;
if (target != null) {
source = blend(target);
}
return source;
}
ColorScheme colors(Brightness brightness, Color? targetColor) {
final dynamicPrimary = brightness == Brightness.light
? lightDynamic?.primary
: darkDynamic?.primary;
return ColorScheme.fromSeed(
seedColor: dynamicPrimary ?? source(targetColor),
brightness: brightness,
);
}
ShapeBorder get shapeMedium => RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
);
CardTheme cardTheme() {
return CardTheme(
elevation: 0,
shape: shapeMedium,
clipBehavior: Clip.antiAlias,
);
}
ListTileThemeData listTileTheme(ColorScheme colors) {
return ListTileThemeData(
shape: shapeMedium,
selectedColor: colors.secondary,
);
}
AppBarTheme appBarTheme(ColorScheme colors) {
return AppBarTheme(
elevation: 0,
backgroundColor: colors.surface,
foregroundColor: colors.onSurface,
);
}
TabBarTheme tabBarTheme(ColorScheme colors) {
return TabBarTheme(
labelColor: colors.secondary,
unselectedLabelColor: colors.onSurfaceVariant,
indicator: BoxDecoration(
border: Border(
bottom: BorderSide(
color: colors.secondary,
width: 2,
),
),
),
);
}
BottomAppBarTheme bottomAppBarTheme(ColorScheme colors) {
return BottomAppBarTheme(
color: colors.surface,
elevation: 0,
);
}
BottomNavigationBarThemeData bottomNavigationBarTheme(ColorScheme colors) {
return BottomNavigationBarThemeData(
type: BottomNavigationBarType.fixed,
backgroundColor: colors.surfaceVariant,
selectedItemColor: colors.onSurface,
unselectedItemColor: colors.onSurfaceVariant,
elevation: 0,
landscapeLayout: BottomNavigationBarLandscapeLayout.centered,
);
}
NavigationRailThemeData navigationRailTheme(ColorScheme colors) {
return const NavigationRailThemeData();
}
DrawerThemeData drawerTheme(ColorScheme colors) {
return DrawerThemeData(
backgroundColor: colors.surface,
);
}
ThemeData light([Color? targetColor]) {
final colorScheme = colors(Brightness.light, targetColor);
return ThemeData.light(useMaterial3: true).copyWith(
// Add page transitions
colorScheme: colorScheme,
appBarTheme: appBarTheme(colorScheme),
cardTheme: cardTheme(),
listTileTheme: listTileTheme(colorScheme),
bottomAppBarTheme: bottomAppBarTheme(colorScheme),
bottomNavigationBarTheme: bottomNavigationBarTheme(colorScheme),
navigationRailTheme: navigationRailTheme(colorScheme),
tabBarTheme: tabBarTheme(colorScheme),
drawerTheme: drawerTheme(colorScheme),
scaffoldBackgroundColor: colorScheme.background,
);
}
ThemeData dark([Color? targetColor]) {
final colorScheme = colors(Brightness.dark, targetColor);
return ThemeData.dark(useMaterial3: true).copyWith(
// Add page transitions
colorScheme: colorScheme,
appBarTheme: appBarTheme(colorScheme),
cardTheme: cardTheme(),
listTileTheme: listTileTheme(colorScheme),
bottomAppBarTheme: bottomAppBarTheme(colorScheme),
bottomNavigationBarTheme: bottomNavigationBarTheme(colorScheme),
navigationRailTheme: navigationRailTheme(colorScheme),
tabBarTheme: tabBarTheme(colorScheme),
drawerTheme: drawerTheme(colorScheme),
scaffoldBackgroundColor: colorScheme.background,
);
}
ThemeMode themeMode() {
return settings.value.themeMode;
}
ThemeData theme(BuildContext context, [Color? targetColor]) {
final brightness = MediaQuery.of(context).platformBrightness;
return brightness == Brightness.light
? light(targetColor)
: dark(targetColor);
}
static ThemeProvider of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ThemeProvider>()!;
}
@override
bool updateShouldNotify(covariant ThemeProvider oldWidget) {
return oldWidget.settings != settings;
}
}
class ThemeSettings {
ThemeSettings({
required this.sourceColor,
required this.themeMode,
});
final Color sourceColor;
final ThemeMode themeMode;
}
Color randomColor() {
return Color(Random().nextInt(0xFFFFFFFF));
}
// Custom Colors
const linkColor = CustomColor(
name: 'Link Color',
color: Color(0xFF00B0FF),
);
class CustomColor {
const CustomColor({
required this.name,
required this.color,
this.blend = true,
});
final String name;
final Color color;
final bool blend;
Color value(ThemeProvider provider) {
return provider.custom(this);
}
}
| codelabs/boring_to_beautiful/step_01/lib/src/shared/providers/theme.dart/0 | {
"file_path": "codelabs/boring_to_beautiful/step_01/lib/src/shared/providers/theme.dart",
"repo_id": "codelabs",
"token_count": 2258
} | 19 |
// Copyright 2022 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';
class OutlinedCard extends StatefulWidget {
const OutlinedCard({
super.key,
required this.child,
this.clickable = true,
});
final Widget child;
final bool clickable;
@override
State<OutlinedCard> createState() => _OutlinedCardState();
}
class _OutlinedCardState extends State<OutlinedCard> {
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: widget.clickable
? SystemMouseCursors.click
: SystemMouseCursors.basic,
child: Container(
// Add box decoration here
child: widget.child,
),
);
}
}
| codelabs/boring_to_beautiful/step_01/lib/src/shared/views/outlined_card.dart/0 | {
"file_path": "codelabs/boring_to_beautiful/step_01/lib/src/shared/views/outlined_card.dart",
"repo_id": "codelabs",
"token_count": 286
} | 20 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/boring_to_beautiful/step_03/android/gradle.properties/0 | {
"file_path": "codelabs/boring_to_beautiful/step_03/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 21 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/boring_to_beautiful/step_05/android/gradle.properties/0 | {
"file_path": "codelabs/boring_to_beautiful/step_05/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 22 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/boring_to_beautiful/step_07/android/gradle.properties/0 | {
"file_path": "codelabs/boring_to_beautiful/step_07/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 23 |
package com.example.brick_breaker
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| codelabs/brick_breaker/step_05/android/app/src/main/kotlin/com/example/brick_breaker/MainActivity.kt/0 | {
"file_path": "codelabs/brick_breaker/step_05/android/app/src/main/kotlin/com/example/brick_breaker/MainActivity.kt",
"repo_id": "codelabs",
"token_count": 36
} | 24 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/brick_breaker/step_06/android/gradle.properties/0 | {
"file_path": "codelabs/brick_breaker/step_06/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 25 |
const gameWidth = 820.0;
const gameHeight = 1600.0;
const ballRadius = gameWidth * 0.02;
| codelabs/brick_breaker/step_06/lib/src/config.dart/0 | {
"file_path": "codelabs/brick_breaker/step_06/lib/src/config.dart",
"repo_id": "codelabs",
"token_count": 31
} | 26 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| codelabs/brick_breaker/step_06/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "codelabs/brick_breaker/step_06/macos/Runner/Configs/Release.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 27 |
import 'dart:async';
import 'dart:math' as math;
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'components/components.dart';
import 'config.dart';
class BrickBreaker extends FlameGame
with HasCollisionDetection, KeyboardEvents {
BrickBreaker()
: super(
camera: CameraComponent.withFixedResolution(
width: gameWidth,
height: gameHeight,
),
);
final rand = math.Random();
double get width => size.x;
double get height => size.y;
@override
FutureOr<void> onLoad() async {
super.onLoad();
camera.viewfinder.anchor = Anchor.topLeft;
world.add(PlayArea());
world.add(Ball(
radius: ballRadius,
position: size / 2,
velocity: Vector2((rand.nextDouble() - 0.5) * width, height * 0.2)
.normalized()
..scale(height / 4)));
world.add(Bat(
size: Vector2(batWidth, batHeight),
cornerRadius: const Radius.circular(ballRadius / 2),
position: Vector2(width / 2, height * 0.95)));
debugMode = true;
}
@override
KeyEventResult onKeyEvent(
KeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
super.onKeyEvent(event, keysPressed);
switch (event.logicalKey) {
case LogicalKeyboardKey.arrowLeft:
world.children.query<Bat>().first.moveBy(-batStep);
case LogicalKeyboardKey.arrowRight:
world.children.query<Bat>().first.moveBy(batStep);
}
return KeyEventResult.handled;
}
}
| codelabs/brick_breaker/step_07/lib/src/brick_breaker.dart/0 | {
"file_path": "codelabs/brick_breaker/step_07/lib/src/brick_breaker.dart",
"repo_id": "codelabs",
"token_count": 663
} | 28 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| codelabs/dart-patterns-and-records/step_03/android/gradle.properties/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_03/android/gradle.properties",
"repo_id": "codelabs",
"token_count": 30
} | 29 |
name: patterns_codelab
description: A new Flutter project.
publish_to: 'none'
version: 0.1.0
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.1
flutter:
uses-material-design: true
| codelabs/dart-patterns-and-records/step_03/pubspec.yaml/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_03/pubspec.yaml",
"repo_id": "codelabs",
"token_count": 119
} | 30 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_05/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_05/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 31 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_06_a/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_a/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 32 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/dart-patterns-and-records/step_06_b/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_06_b/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 33 |
// 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 'data.dart';
void main() {
runApp(const DocumentApp());
}
class DocumentApp extends StatelessWidget {
const DocumentApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: DocumentScreen(
document: Document(),
),
);
}
}
class DocumentScreen extends StatelessWidget {
final Document document;
const DocumentScreen({
required this.document,
super.key,
});
@override
Widget build(BuildContext context) {
final (title, :modified) = document.metadata;
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
children: [
Center(
child: Text(
'Last modified $modified',
),
),
],
),
);
}
}
| codelabs/dart-patterns-and-records/step_07_a/lib/main.dart/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_07_a/lib/main.dart",
"repo_id": "codelabs",
"token_count": 418
} | 34 |
#include "Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_11_a/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_11_a/ios/Flutter/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 12
} | 35 |
#include "ephemeral/Flutter-Generated.xcconfig"
| codelabs/dart-patterns-and-records/step_11_b/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_11_b/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "codelabs",
"token_count": 19
} | 36 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| codelabs/dart-patterns-and-records/step_12/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "codelabs/dart-patterns-and-records/step_12/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "codelabs",
"token_count": 32
} | 37 |
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')),
),
),
],
),
],
);
| codelabs/deeplink_cookbook/lib/main.dart/0 | {
"file_path": "codelabs/deeplink_cookbook/lib/main.dart",
"repo_id": "codelabs",
"token_count": 260
} | 38 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.