text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
name: deeplink_store_example
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: ^3.2.0
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
shrine_images: ^2.0.2
go_router: ^13.0.0
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^3.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
assets:
- packages/shrine_images/0-0.jpg
- packages/shrine_images/1-0.jpg
- packages/shrine_images/2-0.jpg
- packages/shrine_images/3-0.jpg
- packages/shrine_images/4-0.jpg
- packages/shrine_images/5-0.jpg
- packages/shrine_images/6-0.jpg
- packages/shrine_images/7-0.jpg
- packages/shrine_images/8-0.jpg
- packages/shrine_images/9-0.jpg
- packages/shrine_images/10-0.jpg
- packages/shrine_images/11-0.jpg
- packages/shrine_images/12-0.jpg
- packages/shrine_images/13-0.jpg
- packages/shrine_images/14-0.jpg
- packages/shrine_images/15-0.jpg
- packages/shrine_images/16-0.jpg
- packages/shrine_images/17-0.jpg
- packages/shrine_images/18-0.jpg
- packages/shrine_images/19-0.jpg
- packages/shrine_images/20-0.jpg
- packages/shrine_images/21-0.jpg
- packages/shrine_images/22-0.jpg
- packages/shrine_images/23-0.jpg
- packages/shrine_images/24-0.jpg
- packages/shrine_images/25-0.jpg
- packages/shrine_images/26-0.jpg
- packages/shrine_images/27-0.jpg
- packages/shrine_images/28-0.jpg
- packages/shrine_images/29-0.jpg
- packages/shrine_images/30-0.jpg
- packages/shrine_images/31-0.jpg
- packages/shrine_images/32-0.jpg
- packages/shrine_images/33-0.jpg
- packages/shrine_images/34-0.jpg
- packages/shrine_images/35-0.jpg
- packages/shrine_images/36-0.jpg
- packages/shrine_images/37-0.jpg
- packages/shrine_images/2.0x/0-0.jpg
- packages/shrine_images/2.0x/1-0.jpg
- packages/shrine_images/2.0x/2-0.jpg
- packages/shrine_images/2.0x/3-0.jpg
- packages/shrine_images/2.0x/4-0.jpg
- packages/shrine_images/2.0x/5-0.jpg
- packages/shrine_images/2.0x/6-0.jpg
- packages/shrine_images/2.0x/7-0.jpg
- packages/shrine_images/2.0x/8-0.jpg
- packages/shrine_images/2.0x/9-0.jpg
- packages/shrine_images/2.0x/10-0.jpg
- packages/shrine_images/2.0x/11-0.jpg
- packages/shrine_images/2.0x/12-0.jpg
- packages/shrine_images/2.0x/13-0.jpg
- packages/shrine_images/2.0x/14-0.jpg
- packages/shrine_images/2.0x/15-0.jpg
- packages/shrine_images/2.0x/16-0.jpg
- packages/shrine_images/2.0x/17-0.jpg
- packages/shrine_images/2.0x/18-0.jpg
- packages/shrine_images/2.0x/19-0.jpg
- packages/shrine_images/2.0x/20-0.jpg
- packages/shrine_images/2.0x/21-0.jpg
- packages/shrine_images/2.0x/22-0.jpg
- packages/shrine_images/2.0x/23-0.jpg
- packages/shrine_images/2.0x/24-0.jpg
- packages/shrine_images/2.0x/25-0.jpg
- packages/shrine_images/2.0x/26-0.jpg
- packages/shrine_images/2.0x/27-0.jpg
- packages/shrine_images/2.0x/28-0.jpg
- packages/shrine_images/2.0x/29-0.jpg
- packages/shrine_images/2.0x/30-0.jpg
- packages/shrine_images/2.0x/31-0.jpg
- packages/shrine_images/2.0x/32-0.jpg
- packages/shrine_images/2.0x/33-0.jpg
- packages/shrine_images/2.0x/34-0.jpg
- packages/shrine_images/2.0x/35-0.jpg
- packages/shrine_images/2.0x/36-0.jpg
- packages/shrine_images/2.0x/37-0.jpg
| samples/deeplink_store_example/pubspec.yaml/0 | {
"file_path": "samples/deeplink_store_example/pubspec.yaml",
"repo_id": "samples",
"token_count": 2628
} | 1,151 |
// 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:fluent_ui/fluent_ui.dart';
import 'package:flutter/gestures.dart';
import 'package:url_launcher/url_launcher.dart' as url_launcher;
class PolicyDialog extends StatelessWidget {
const PolicyDialog({super.key});
@override
Widget build(BuildContext context) {
return ContentDialog(
title: const Text('Terms & Conditions'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
RichText(
textAlign: TextAlign.left,
text: TextSpan(
text: '• ',
style: const TextStyle(color: Colors.black, fontSize: 18),
children: [
TextSpan(
text: 'https://policies.google.com/terms',
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.blue.normal),
recognizer: TapGestureRecognizer()
..onTap = () async {
final url =
Uri.parse('https://policies.google.com/terms');
if (await url_launcher.canLaunchUrl(url)) {
await url_launcher.launchUrl(url);
}
},
)
],
),
),
RichText(
textAlign: TextAlign.left,
text: TextSpan(
text: '• ',
style: const TextStyle(color: Colors.black, fontSize: 18),
children: [
TextSpan(
text: 'https://unsplash.com/terms',
style: TextStyle(
fontWeight: FontWeight.bold, color: Colors.blue.normal),
recognizer: TapGestureRecognizer()
..onTap = () async {
final url = Uri.parse('https://unsplash.com/terms');
if (await url_launcher.canLaunchUrl(url)) {
await url_launcher.launchUrl(url);
}
},
)
],
),
),
],
),
actions: [
FilledButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Accept'),
),
],
);
}
}
| samples/desktop_photo_search/fluent_ui/lib/src/widgets/policy_dialog.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/widgets/policy_dialog.dart",
"repo_id": "samples",
"token_count": 1379
} | 1,152 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="dev.flutter.federated_plugin">
</manifest>
| samples/experimental/federated_plugin/federated_plugin/android/src/main/AndroidManifest.xml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/android/src/main/AndroidManifest.xml",
"repo_id": "samples",
"token_count": 46
} | 1,153 |
#import "GeneratedPluginRegistrant.h"
| samples/experimental/federated_plugin/federated_plugin/example/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,154 |
name: federated_plugin
description: A new flutter plugin project to demonstrate how to implement federated plugin.
version: 0.0.1
publish_to: "none"
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
federated_plugin_platform_interface:
path: ../federated_plugin_platform_interface
federated_plugin_web:
path: ../federated_plugin_web
federated_plugin_windows:
path: ../federated_plugin_windows
federated_plugin_macos:
path: ../federated_plugin_macos
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
flutter:
plugin:
platforms:
android:
package: dev.flutter.federated_plugin
pluginClass: FederatedPlugin
ios:
pluginClass: SwiftFederatedPlugin
web:
default_package: federated_plugin_web
windows:
default_package: federated_plugin_windows
macos:
default_package: federated_plugin_macos
| samples/experimental/federated_plugin/federated_plugin/pubspec.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/pubspec.yaml",
"repo_id": "samples",
"token_count": 385
} | 1,155 |
// Copyright 2020 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:federated_plugin_platform_interface/battery_method_channel.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('MethodChannel test', () {
const batteryLevel = 89;
testWidgets('getBatteryLevel method test', (tester) async {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('battery'),
(call) async {
if (call.method == 'getBatteryLevel') {
return batteryLevel;
}
return 0;
},
);
final locationMethodChannel = BatteryMethodChannel();
final result = await locationMethodChannel.getBatteryLevel();
expect(result, batteryLevel);
});
});
}
| samples/experimental/federated_plugin/federated_plugin_platform_interface/test/federated_plugin_platform_interface_test.dart/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_platform_interface/test/federated_plugin_platform_interface_test.dart",
"repo_id": "samples",
"token_count": 346
} | 1,156 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'rule.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class RuleAdapter extends TypeAdapter<Rule> {
@override
final int typeId = 0;
@override
Rule read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Rule(
name: fields[0] as String,
description: fields[1] as String,
group: fields[2] as String,
state: fields[3] as String,
incompatible: (fields[4] as List).cast<String>(),
sets: (fields[5] as List).cast<String>(),
details: fields[6] as String,
);
}
@override
void write(BinaryWriter writer, Rule obj) {
writer
..writeByte(7)
..writeByte(0)
..write(obj.name)
..writeByte(1)
..write(obj.description)
..writeByte(2)
..write(obj.group)
..writeByte(3)
..write(obj.state)
..writeByte(4)
..write(obj.incompatible)
..writeByte(5)
..write(obj.sets)
..writeByte(6)
..write(obj.details);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RuleAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Rule _$RuleFromJson(Map<String, dynamic> json) => Rule(
name: json['name'] as String,
description: json['description'] as String,
group: json['group'] as String,
state: json['state'] as String,
incompatible: (json['incompatible'] as List<dynamic>)
.map((e) => e as String)
.toList(),
sets: (json['sets'] as List<dynamic>).map((e) => e as String).toList(),
details: json['details'] as String,
);
Map<String, dynamic> _$RuleToJson(Rule instance) => <String, dynamic>{
'name': instance.name,
'description': instance.description,
'group': instance.group,
'state': instance.state,
'incompatible': instance.incompatible,
'sets': instance.sets,
'details': instance.details,
};
| samples/experimental/linting_tool/lib/model/rule.g.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/model/rule.g.dart",
"repo_id": "samples",
"token_count": 923
} | 1,157 |
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include <file_selector_windows/file_selector_windows.h>
#include <url_launcher_windows/url_launcher_windows.h>
#include <window_size/window_size_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
FileSelectorWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FileSelectorWindows"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
WindowSizePluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("WindowSizePlugin"));
}
| samples/experimental/linting_tool/windows/flutter/generated_plugin_registrant.cc/0 | {
"file_path": "samples/experimental/linting_tool/windows/flutter/generated_plugin_registrant.cc",
"repo_id": "samples",
"token_count": 212
} | 1,158 |
-keep class androidx.health.connect.client.** { *; }
-keep class kotlin.coroutines.** { *; }
| samples/experimental/pedometer/example/android/app/proguard-rules.pro/0 | {
"file_path": "samples/experimental/pedometer/example/android/app/proguard-rules.pro",
"repo_id": "samples",
"token_count": 35
} | 1,159 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/experimental/pedometer/example/android/gradle.properties/0 | {
"file_path": "samples/experimental/pedometer/example/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,160 |
#import <CoreMotion/CoreMotion.h>
#import <CoreMotion/CMPedometer.h>
#import <Foundation/Foundation.h>
// TODO(https://github.com/dart-lang/native/issues/835): Generate this wrapper
// automatically.
CMPedometerHandler wrapCallback(CMPedometerHandler callback);
| samples/experimental/pedometer/src/pedometerHelper.h/0 | {
"file_path": "samples/experimental/pedometer/src/pedometerHelper.h",
"repo_id": "samples",
"token_count": 86
} | 1,161 |
// Copyright 2023 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 'dart:ui' as ui;
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:flutter/material.dart';
class WonkyChar extends StatefulWidget {
final String text;
final double size;
final double baseRotation;
final int animDurationMillis;
final List<WonkyAnimSetting> animationSettings;
const WonkyChar({
super.key,
required this.text,
required this.size,
this.baseRotation = 0,
this.animDurationMillis = 1000,
this.animationSettings = const <WonkyAnimSetting>[],
});
@override
State<WonkyChar> createState() => WonkyCharState();
}
class WonkyCharState extends State<WonkyChar>
with SingleTickerProviderStateMixin {
bool loopingAnimation = true;
late AnimationController _animController;
final List<Animation<double>> _curves = [];
late final List<Animation> _fvAnimations = [];
final List<String> _fvAxes = [];
// default curve and animations in case user sets nothing for them
late final defaultCurve = CurvedAnimation(
parent: _animController,
curve: const Interval(0, 1, curve: Curves.linear));
late Animation _scaleAnimation =
Tween<double>(begin: 1, end: 1).animate(defaultCurve);
late Animation _offsetXAnimation =
Tween<double>(begin: 0, end: 0).animate(defaultCurve);
late Animation _offsetYAnimation =
Tween<double>(begin: 0, end: 0).animate(defaultCurve);
late Animation _rotationAnimation =
Tween<double>(begin: 0, end: 0).animate(defaultCurve);
late Animation _colorAnimation =
ColorTween(begin: Colors.black, end: Colors.black).animate(defaultCurve);
@override
void initState() {
super.initState();
initAnimations(widget.animationSettings);
_animController
..addListener(() {
setState(() {});
})
..addStatusListener((status) {
if (status == AnimationStatus.completed && loopingAnimation) {
_animController.reverse();
} else if (status == AnimationStatus.dismissed && loopingAnimation) {
_animController.forward();
}
});
_animController.forward();
}
@override
void dispose() {
_animController.dispose();
super.dispose();
}
void stopAnimation() {
_animController.stop();
}
@override
Widget build(BuildContext context) {
List<ui.FontVariation> fontVariations = [];
for (int i = 0; i < _fvAxes.length; i++) {
fontVariations
.add(ui.FontVariation(_fvAxes[i], _fvAnimations[i].value as double));
}
return Transform(
alignment: Alignment.center,
transform: Matrix4.translationValues(_offsetXAnimation.value as double,
_offsetYAnimation.value as double, 0)
..scale(_scaleAnimation.value)
..rotateZ(widget.baseRotation + (_rotationAnimation.value as double)),
child: IgnorePointer(
child: Text(
widget.text,
textAlign: TextAlign.center,
style: TextStyle(
color: _colorAnimation.value as Color?,
fontFamily: 'Amstelvar',
fontSize: widget.size,
fontVariations: fontVariations,
),
),
),
);
}
void initAnimations(List<WonkyAnimSetting> settings) {
_animController = AnimationController(
vsync: this,
duration: Duration(milliseconds: widget.animDurationMillis),
);
for (WonkyAnimSetting s in settings) {
final curve = CurvedAnimation(
parent: _animController,
curve: Interval(s.startAt, s.endAt, curve: s.curve),
);
late Animation animation;
if (s.property == 'color') {
animation = ColorTween(
begin: s.fromTo.fromValue() as Color?,
end: s.fromTo.toValue() as Color?)
.animate(curve);
} else {
animation = Tween<double>(
begin: s.fromTo.fromValue() as double,
end: s.fromTo.toValue() as double)
.animate(curve);
}
if (s.type == 'fv') {
_fvAxes.add(s.property);
_fvAnimations.add(animation);
} else if (s.type == 'basic') {
switch (s.property) {
case 'scale':
{
_scaleAnimation = animation;
}
case 'rotation':
{
_rotationAnimation = animation;
}
case 'offsetX':
{
_offsetXAnimation = animation;
}
case 'offsetY':
{
_offsetYAnimation = animation;
}
case 'color':
{
_colorAnimation = animation;
}
default:
{
if (kDebugMode) {
print(
'**ERROR** unrecognized property to animate: ${s.property}');
}
}
break;
}
}
// save refs to all curves just to persist in mem, don't need to touch them again
_curves.add(curve);
}
}
}
abstract class WCRange<T> {
WCRange();
T fromValue();
T toValue();
}
class RangeColor implements WCRange<Color> {
Color from;
Color to;
RangeColor({required this.from, required this.to});
@override
Color fromValue() {
return from;
}
@override
Color toValue() {
return to;
}
}
class RangeDbl implements WCRange<double> {
double from;
double to;
RangeDbl({required this.from, required this.to});
@override
double fromValue() {
return from;
}
@override
double toValue() {
return to;
}
}
class WonkyAnimSetting {
// just the animation
String type; // 'fv' for fontVariation, 'basic' for everything else
String property; //font variation axis, or 'size'/'rotation'/etc.
WCRange fromTo;
double startAt; // 0 to 1 rel to controller
double endAt; // same as start
Curve curve;
WonkyAnimSetting({
required this.type,
required this.property,
required this.fromTo,
required this.startAt,
required this.endAt,
required this.curve,
});
}
| samples/experimental/varfont_shader_puzzle/lib/components/wonky_char.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/components/wonky_char.dart",
"repo_id": "samples",
"token_count": 2563
} | 1,162 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. 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 '../auth/auth.dart';
class SignInPage extends StatelessWidget {
final Auth auth;
final ValueChanged<User> onSuccess;
const SignInPage({
required this.auth,
required this.onSuccess,
super.key,
});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SignInButton(auth: auth, onSuccess: onSuccess),
),
);
}
}
class SignInButton extends StatefulWidget {
final Auth auth;
final ValueChanged<User> onSuccess;
const SignInButton({
required this.auth,
required this.onSuccess,
super.key,
});
@override
State<SignInButton> createState() => _SignInButtonState();
}
class _SignInButtonState extends State<SignInButton> {
Future<bool>? _checkSignInFuture;
@override
void initState() {
super.initState();
_checkSignInFuture = _checkIfSignedIn();
}
// Check if the user is signed in. If the user is already signed in (for
// example, if they signed in and refreshed the page), invoke the `onSuccess`
// callback right away.
Future<bool> _checkIfSignedIn() async {
var alreadySignedIn = await widget.auth.isSignedIn;
if (alreadySignedIn) {
var user = await widget.auth.signIn();
widget.onSuccess(user);
}
return alreadySignedIn;
}
Future<void> _signIn() async {
try {
var user = await widget.auth.signIn();
widget.onSuccess(user);
} on SignInException {
_showError();
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<bool>(
future: _checkSignInFuture,
builder: (context, snapshot) {
// If signed in, or the future is incomplete, show a circular
// progress indicator.
var alreadySignedIn = snapshot.data;
if (snapshot.connectionState != ConnectionState.done ||
alreadySignedIn == true) {
return const CircularProgressIndicator();
}
// If sign in failed, show toast and the login button
if (snapshot.hasError) {
_showError();
}
return FilledButton(
child: const Text('Sign In with Google'),
onPressed: () => _signIn(),
);
},
);
}
void _showError() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Unable to sign in.'),
),
);
}
}
| samples/experimental/web_dashboard/lib/src/pages/sign_in.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/pages/sign_in.dart",
"repo_id": "samples",
"token_count": 983
} | 1,163 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A desktop-friendly dashboard app">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="web_dashboard">
<link rel="apple-touch-icon" href="/icons/Icon-192.png">
<title>web_dashboard</title>
<link rel="manifest" href="/manifest.json">
<!-- Firebase Setup -->
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.0/firebase-firestore.js"></script>
<script src="firebase_init.js"></script>
<!-- Uncomment and add Firebase client ID here: -->
<!-- <meta name="google-signin-client_id" content="<YOUR WEB CLIENT ID>"> -->
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/flutter_service_worker.js');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
| samples/experimental/web_dashboard/web/index.html/0 | {
"file_path": "samples/experimental/web_dashboard/web/index.html",
"repo_id": "samples",
"token_count": 538
} | 1,164 |
include: package:flutter_lints/flutter.yaml
linter:
rules:
# Remove or force lint rules by adding lines like the following.
# The lints below are disabled in order to make things smoother in early
# development. Consider enabling them once development is further along.
prefer_const_constructors: false # Annoying in early development
prefer_single_quotes: false # Annoying in early development
| samples/game_template/analysis_options.yaml/0 | {
"file_path": "samples/game_template/analysis_options.yaml",
"repo_id": "samples",
"token_count": 118
} | 1,165 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. 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:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'ads_controller.dart';
import 'preloaded_banner_ad.dart';
/// Displays a banner ad that conforms to the widget's size in the layout,
/// and reloads the ad when the user changes orientation.
///
/// Do not use this widget on platforms that AdMob currently doesn't support.
/// For example:
///
/// ```dart
/// if (kIsWeb) {
/// return Text('No ads here! (Yet.)');
/// } else {
/// return MyBannerAd();
/// }
/// ```
///
/// This widget is adapted from pkg:google_mobile_ads's example code,
/// namely the `anchored_adaptive_example.dart` file:
/// https://github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/example/lib/anchored_adaptive_example.dart
class BannerAdWidget extends StatefulWidget {
const BannerAdWidget({super.key});
@override
State<BannerAdWidget> createState() => _BannerAdWidgetState();
}
class _BannerAdWidgetState extends State<BannerAdWidget> {
static final _log = Logger('BannerAdWidget');
static const useAnchoredAdaptiveSize = false;
BannerAd? _bannerAd;
_LoadingState _adLoadingState = _LoadingState.initial;
late Orientation _currentOrientation;
@override
Widget build(BuildContext context) {
return OrientationBuilder(
builder: (context, orientation) {
if (_currentOrientation == orientation &&
_bannerAd != null &&
_adLoadingState == _LoadingState.loaded) {
_log.info(() => 'We have everything we need. Showing the ad '
'${_bannerAd.hashCode} now.');
return SizedBox(
width: _bannerAd!.size.width.toDouble(),
height: _bannerAd!.size.height.toDouble(),
child: AdWidget(ad: _bannerAd!),
);
}
// Reload the ad if the orientation changes.
if (_currentOrientation != orientation) {
_log.info('Orientation changed');
_currentOrientation = orientation;
_loadAd();
}
return const SizedBox();
},
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_currentOrientation = MediaQuery.of(context).orientation;
}
@override
void dispose() {
_log.info('disposing ad');
_bannerAd?.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
final adsController = context.read<AdsController>();
final ad = adsController.takePreloadedAd();
if (ad != null) {
_log.info("A preloaded banner was supplied. Using it.");
_showPreloadedAd(ad);
} else {
_loadAd();
}
}
/// Load (another) ad, disposing of the current ad if there is one.
Future<void> _loadAd() async {
if (!mounted) return;
_log.info('_loadAd() called.');
if (_adLoadingState == _LoadingState.loading ||
_adLoadingState == _LoadingState.disposing) {
_log.info('An ad is already being loaded or disposed. Aborting.');
return;
}
_adLoadingState = _LoadingState.disposing;
await _bannerAd?.dispose();
_log.fine('_bannerAd disposed');
if (!mounted) return;
setState(() {
_bannerAd = null;
_adLoadingState = _LoadingState.loading;
});
AdSize size;
if (useAnchoredAdaptiveSize) {
final AnchoredAdaptiveBannerAdSize? adaptiveSize =
await AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(
MediaQuery.of(context).size.width.truncate());
if (adaptiveSize == null) {
_log.warning('Unable to get height of anchored banner.');
size = AdSize.banner;
} else {
size = adaptiveSize;
}
} else {
size = AdSize.mediumRectangle;
}
if (!mounted) return;
assert(Platform.isAndroid || Platform.isIOS,
'AdMob currently does not support ${Platform.operatingSystem}');
_bannerAd = BannerAd(
// This is a test ad unit ID from
// https://developers.google.com/admob/android/test-ads. When ready,
// you replace this with your own, production ad unit ID,
// created in https://apps.admob.com/.
adUnitId: Theme.of(context).platform == TargetPlatform.android
? 'ca-app-pub-3940256099942544/6300978111'
: 'ca-app-pub-3940256099942544/2934735716',
size: size,
request: const AdRequest(),
listener: BannerAdListener(
onAdLoaded: (ad) {
_log.info(() => 'Ad loaded: ${ad.responseInfo}');
setState(() {
// When the ad is loaded, get the ad size and use it to set
// the height of the ad container.
_bannerAd = ad as BannerAd;
_adLoadingState = _LoadingState.loaded;
});
},
onAdFailedToLoad: (ad, error) {
_log.warning('Banner failedToLoad: $error');
ad.dispose();
},
onAdImpression: (ad) {
_log.info('Ad impression registered');
},
onAdClicked: (ad) {
_log.info('Ad click registered');
},
),
);
return _bannerAd!.load();
}
Future<void> _showPreloadedAd(PreloadedBannerAd ad) async {
// It's possible that the banner is still loading (even though it started
// preloading at the start of the previous screen).
_adLoadingState = _LoadingState.loading;
try {
_bannerAd = await ad.ready;
} on LoadAdError catch (error) {
_log.severe('Error when loading preloaded banner: $error');
unawaited(_loadAd());
return;
}
if (!mounted) return;
setState(() {
_adLoadingState = _LoadingState.loaded;
});
}
}
enum _LoadingState {
/// The state before we even start loading anything.
initial,
/// The ad is being loaded at this point.
loading,
/// The previous ad is being disposed of. After that is done, the next
/// ad will be loaded.
disposing,
/// An ad has been loaded already.
loaded,
}
| samples/game_template/lib/src/ads/banner_ad_widget.dart/0 | {
"file_path": "samples/game_template/lib/src/ads/banner_ad_widget.dart",
"repo_id": "samples",
"token_count": 2446
} | 1,166 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'player_progress_persistence.dart';
/// An in-memory implementation of [PlayerProgressPersistence].
/// Useful for testing.
class MemoryOnlyPlayerProgressPersistence implements PlayerProgressPersistence {
int level = 0;
@override
Future<int> getHighestLevelReached() async {
await Future<void>.delayed(const Duration(milliseconds: 500));
return level;
}
@override
Future<void> saveHighestLevelReached(int level) async {
await Future<void>.delayed(const Duration(milliseconds: 500));
this.level = level;
}
}
| samples/game_template/lib/src/player_progress/persistence/memory_player_progress_persistence.dart/0 | {
"file_path": "samples/game_template/lib/src/player_progress/persistence/memory_player_progress_persistence.dart",
"repo_id": "samples",
"token_count": 218
} | 1,167 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late GoogleMapController mapController;
final LatLng _center = const LatLng(-33.86, 151.20);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Sydney'), backgroundColor: Colors.green[700]),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
markers: {
const Marker(
markerId: MarkerId('Sydney'),
position: LatLng(-33.86, 151.20),
infoWindow: InfoWindow(
title: "Sydney",
snippet: "Capital of New South Wales",
),
)
},
),
),
);
}
}
| samples/google_maps/lib/main.dart/0 | {
"file_path": "samples/google_maps/lib/main.dart",
"repo_id": "samples",
"token_count": 752
} | 1,168 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/infinite_list/android/gradle.properties/0 | {
"file_path": "samples/infinite_list/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,169 |
// Copyright 2020 The Chromium 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/foundation.dart';
import 'package:flutter/material.dart';
import 'api/fetch.dart';
import 'api/item.dart';
import 'api/page.dart';
/// The [Catalog] holds items in memory, provides a synchronous access
/// to them via [getByIndex], and notifies listeners when there is any change.
class Catalog extends ChangeNotifier {
/// This is the maximum number of the items we want in memory in each
/// direction from the current position. For example, if the user
/// is currently looking at item number 400, we don't want item number
/// 0 to be kept in memory.
static const maxCacheDistance = 100;
/// The internal store of pages that we got from [fetchPage].
/// The key of the map is the starting index of the page, for faster
/// access.
final Map<int, ItemPage> _pages = {};
/// A set of pages (represented by their starting index) that have started
/// the fetch process but haven't ended it yet.
///
/// This is to prevent fetching of a page several times in a row. When a page
/// is already being fetched, we don't initiate another fetch request.
final Set<int> _pagesBeingFetched = {};
/// The size of the catalog. This is `null` at first, and only when the user
/// reaches the end of the catalog, it will hold the actual number.
int? itemCount;
/// After the catalog is disposed, we don't allow it to call
/// [notifyListeners].
bool _isDisposed = false;
@override
void dispose() {
_isDisposed = true;
super.dispose();
}
/// This is a synchronous method that returns the item at [index].
///
/// If the item is already in memory, this will just return it. Otherwise,
/// this method will initiate a fetch of the corresponding page, and will
/// return [Item.loading].
///
/// The UI will be notified via [notifyListeners] when the fetch
/// is completed. At that time, calling this method will return the newly
/// fetched item.
Item getByIndex(int index) {
// Compute the starting index of the page where this item is located.
// For example, if [index] is `42` and [itemsPerPage] is `20`,
// then `index ~/ itemsPerPage` (integer division)
// evaluates to `2`, and `2 * 20` is `40`.
var startingIndex = (index ~/ itemsPerPage) * itemsPerPage;
// If the corresponding page is already in memory, return immediately.
if (_pages.containsKey(startingIndex)) {
var item = _pages[startingIndex]!.items[index - startingIndex];
return item;
}
// We don't have the data yet. Start fetching it.
_fetchPage(startingIndex);
// In the meantime, return a placeholder.
return Item.loading();
}
/// This method initiates fetching of the [ItemPage] at [startingIndex].
Future<void> _fetchPage(int startingIndex) async {
if (_pagesBeingFetched.contains(startingIndex)) {
// Page is already being fetched. Ignore the redundant call.
return;
}
_pagesBeingFetched.add(startingIndex);
final page = await fetchPage(startingIndex);
_pagesBeingFetched.remove(startingIndex);
if (!page.hasNext) {
// The returned page has no next page. This means we now know the size
// of the catalog.
itemCount = startingIndex + page.items.length;
}
// Store the new page.
_pages[startingIndex] = page;
_pruneCache(startingIndex);
if (!_isDisposed) {
// Notify the widgets that are listening to the catalog that they
// should rebuild.
notifyListeners();
}
}
/// Removes item pages that are too far away from [currentStartingIndex].
void _pruneCache(int currentStartingIndex) {
// It's bad practice to modify collections while iterating over them.
// So instead, we'll store the keys to remove in a separate Set.
final keysToRemove = <int>{};
for (final key in _pages.keys) {
if ((key - currentStartingIndex).abs() > maxCacheDistance) {
// This page's starting index is too far away from the current one.
// We'll remove it.
keysToRemove.add(key);
}
}
for (final key in keysToRemove) {
_pages.remove(key);
}
}
}
| samples/infinite_list/lib/src/catalog.dart/0 | {
"file_path": "samples/infinite_list/lib/src/catalog.dart",
"repo_id": "samples",
"token_count": 1337
} | 1,170 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/infinite_list/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/infinite_list/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,171 |
#import "GeneratedPluginRegistrant.h"
| samples/ios_app_clip/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/ios_app_clip/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,172 |
name: material_3_demo
description:
A Flutter project showcasing supported Material 3 components, typography, color system and elevation.
Supports different light/dark mode, color seed, and comparison to Material 2.
publish_to: "none"
version: 1.0.0+1
environment:
sdk: ^3.3.0
flutter: ^3.19.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
url_launcher: ^6.1.8
web_startup_analyzer:
path: ../web/_packages/web_startup_analyzer
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
integration_test:
sdk: flutter
flutter:
uses-material-design: true
| samples/material_3_demo/pubspec.yaml/0 | {
"file_path": "samples/material_3_demo/pubspec.yaml",
"repo_id": "samples",
"token_count": 243
} | 1,173 |
# Navigation and Routing
A sample that shows how to use [go_router][https://pub.dev/packages/go_router]
API to handle common navigation scenarios.
## Goals
- Demonstrate common navigation scenarios:
- Parsing path parameters ('/user/:id')
- Sign in (redirection)
- Nested navigation using ShellRoute
- Demonstrate how [deep linking][] is configured on iOS and Android
- Demonstrate how to use the Link widget from `package:url_Launcher` with the
Router API.
| samples/navigation_and_routing/README.md/0 | {
"file_path": "samples/navigation_and_routing/README.md",
"repo_id": "samples",
"token_count": 127
} | 1,174 |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. 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/widgets.dart';
/// A mock authentication service
class BookstoreAuth extends ChangeNotifier {
bool _signedIn = false;
bool get signedIn => _signedIn;
Future<void> signOut() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign out.
_signedIn = false;
notifyListeners();
}
Future<bool> signIn(String username, String password) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign in. Allow any password.
_signedIn = true;
notifyListeners();
return _signedIn;
}
@override
bool operator ==(Object other) =>
other is BookstoreAuth && other._signedIn == _signedIn;
@override
int get hashCode => _signedIn.hashCode;
static BookstoreAuth of(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<BookstoreAuthScope>()!
.notifier!;
}
class BookstoreAuthScope extends InheritedNotifier<BookstoreAuth> {
const BookstoreAuthScope({
required super.notifier,
required super.child,
super.key,
});
}
| samples/navigation_and_routing/lib/src/auth.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/auth.dart",
"repo_id": "samples",
"token_count": 410
} | 1,175 |
// Copyright 2020 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/services.dart';
/// This class manages a [BasicMessageChannel] that can return an image loaded
/// from a native asset. The [BasicMessageChannel] uses [StandardMessageCodec]
/// since it supports [Uint8List], which is used to transport the image data.
class PlatformImageFetcher {
static const _basicMessageChannel =
BasicMessageChannel<dynamic>('platformImageDemo', StandardMessageCodec());
/// Method responsible for providing the platform image.
static Future<Uint8List> getImage() async {
final reply = await _basicMessageChannel.send('getImage') as Uint8List?;
if (reply == null) {
throw PlatformException(
code: 'Error',
message: 'Failed to load Platform Image',
details: null,
);
}
return reply;
}
}
| samples/platform_channels/lib/src/image_basic_message_channel.dart/0 | {
"file_path": "samples/platform_channels/lib/src/image_basic_message_channel.dart",
"repo_id": "samples",
"token_count": 293
} | 1,176 |
include: package:analysis_defaults/flutter.yaml
| samples/platform_design/analysis_options.yaml/0 | {
"file_path": "samples/platform_design/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,177 |
// Copyright 2020 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/cupertino.dart';
import 'package:flutter/material.dart';
import 'widgets.dart';
/// Page shown when a card in the songs tab is tapped.
///
/// On Android, this page sits at the top of your app. On iOS, this page is on
/// top of the songs tab's content but is below the tab bar itself.
class SongDetailTab extends StatelessWidget {
const SongDetailTab({
required this.id,
required this.song,
required this.color,
super.key,
});
final int id;
final String song;
final Color color;
Widget _buildBody() {
return SafeArea(
bottom: false,
left: false,
right: false,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Hero(
tag: id,
child: HeroAnimatingSongCard(
song: song,
color: color,
heroAnimation: const AlwaysStoppedAnimation(1),
),
// This app uses a flightShuttleBuilder to specify the exact widget
// to build while the hero transition is mid-flight.
//
// It could either be specified here or in SongsTab.
flightShuttleBuilder: (context, animation, flightDirection,
fromHeroContext, toHeroContext) {
return HeroAnimatingSongCard(
song: song,
color: color,
heroAnimation: animation,
);
},
),
const Divider(
height: 0,
color: Colors.grey,
),
Expanded(
child: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) => switch (index) {
0 => const Padding(
padding: EdgeInsets.only(left: 15, top: 16, bottom: 8),
child: Text(
'You might also like:',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
_ => const SongPlaceholderTile(),
},
),
),
],
),
);
}
// ===========================================================================
// Non-shared code below because we're using different scaffolds.
// ===========================================================================
Widget _buildAndroid(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(song)),
body: _buildBody(),
);
}
Widget _buildIos(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(song),
previousPageTitle: 'Songs',
),
child: _buildBody(),
);
}
@override
Widget build(context) {
return PlatformWidget(
androidBuilder: _buildAndroid,
iosBuilder: _buildIos,
);
}
}
| samples/platform_design/lib/song_detail_tab.dart/0 | {
"file_path": "samples/platform_design/lib/song_detail_tab.dart",
"repo_id": "samples",
"token_count": 1423
} | 1,178 |
include: package:analysis_defaults/flutter.yaml
| samples/platform_view_swift/analysis_options.yaml/0 | {
"file_path": "samples/platform_view_swift/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,179 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider_counter/main.dart';
void main() {
testWidgets('Counter increments smoke test', (tester) async {
// Build our app, provide it with a model, and trigger a frame.
await tester.pumpWidget(
ChangeNotifierProvider(
create: (context) => Counter(),
child: const MyApp(),
),
);
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| samples/provider_counter/test/widget_test.dart/0 | {
"file_path": "samples/provider_counter/test/widget_test.dart",
"repo_id": "samples",
"token_count": 351
} | 1,180 |
// 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';
import 'package:provider/provider.dart';
import 'package:provider_shopper/models/cart.dart';
class MyCart extends StatelessWidget {
const MyCart({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cart', style: Theme.of(context).textTheme.displayLarge),
backgroundColor: Colors.white,
),
body: Container(
color: Colors.yellow,
child: Column(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(32),
child: _CartList(),
),
),
const Divider(height: 4, color: Colors.black),
_CartTotal()
],
),
),
);
}
}
class _CartList extends StatelessWidget {
@override
Widget build(BuildContext context) {
var itemNameStyle = Theme.of(context).textTheme.titleLarge;
// This gets the current state of CartModel and also tells Flutter
// to rebuild this widget when CartModel notifies listeners (in other words,
// when it changes).
var cart = context.watch<CartModel>();
return ListView.builder(
itemCount: cart.items.length,
itemBuilder: (context, index) => ListTile(
leading: const Icon(Icons.done),
trailing: IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: () {
cart.remove(cart.items[index]);
},
),
title: Text(
cart.items[index].name,
style: itemNameStyle,
),
),
);
}
}
class _CartTotal extends StatelessWidget {
@override
Widget build(BuildContext context) {
var hugeStyle =
Theme.of(context).textTheme.displayLarge!.copyWith(fontSize: 48);
return SizedBox(
height: 200,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Another way to listen to a model's change is to include
// the Consumer widget. This widget will automatically listen
// to CartModel and rerun its builder on every change.
//
// The important thing is that it will not rebuild
// the rest of the widgets in this build method.
Consumer<CartModel>(
builder: (context, cart, child) =>
Text('\$${cart.totalPrice}', style: hugeStyle)),
const SizedBox(width: 24),
FilledButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Buying not supported yet.')));
},
style: TextButton.styleFrom(foregroundColor: Colors.white),
child: const Text('BUY'),
),
],
),
),
);
}
}
| samples/provider_shopper/lib/screens/cart.dart/0 | {
"file_path": "samples/provider_shopper/lib/screens/cart.dart",
"repo_id": "samples",
"token_count": 1365
} | 1,181 |
#include "Generated.xcconfig"
| samples/simple_shader/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "samples/simple_shader/ios/Flutter/Debug.xcconfig",
"repo_id": "samples",
"token_count": 12
} | 1,182 |
#include "ephemeral/Flutter-Generated.xcconfig"
| samples/simple_shader/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "samples/simple_shader/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "samples",
"token_count": 19
} | 1,183 |
package com.example.simplistic_calculator
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/simplistic_calculator/android/app/src/main/kotlin/com/example/simplistic_calculator/MainActivity.kt/0 | {
"file_path": "samples/simplistic_calculator/android/app/src/main/kotlin/com/example/simplistic_calculator/MainActivity.kt",
"repo_id": "samples",
"token_count": 42
} | 1,184 |
// Copyright 2020 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:test/test.dart';
import 'package:testing_app/models/favorites.dart';
void main() {
group('Testing App Provider Tests', () {
// Create an object of the provider.
var favorites = Favorites();
test('A new item should be added', () {
var number = 35;
// Add the number to the list.
favorites.add(number);
// Verify if the number was inserted.
expect(favorites.items.contains(number), true);
});
test('An item should be removed', () {
var number = 45;
// Add the number to the list.
favorites.add(number);
// Verify if the number was inserted.
expect(favorites.items.contains(number), true);
// Remove the number from the list.
favorites.remove(number);
// Verify if the number was removed successfully.
expect(favorites.items.contains(number), false);
});
});
}
| samples/testing_app/test/models/favorites_test.dart/0 | {
"file_path": "samples/testing_app/test/models/favorites_test.dart",
"repo_id": "samples",
"token_count": 361
} | 1,185 |
#!/bin/bash
set -e
flutter doctor -v
###############################################################################
# Helper functions
###############################################################################
# Runs `packages get` on given flutter module.
# $1 = path to flutter module
function flutter_packages_get() {
echo "Fetching dependencies and building '$1'."
pushd $1
flutter packages get
popd
}
# Runs xcode build for Debug and Release.
# $1 = path to directory containing the xcode project
# $2 = name of the xcworkspace
# $3 = name of the scheme
function build() {
echo "== Testing '$1' on Flutter's $FLUTTER_VERSION channel =="
pushd "$1"
pod install
xcodebuild -workspace "$2" \
-scheme "$3" CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_IDENTITY=- EXPANDED_CODE_SIGN_IDENTITY=- \
COMPILER_INDEX_STORE_ENABLE=NO CONFIGURATION=Debug | xcpretty
xcodebuild -workspace "$2" \
-scheme "$3" CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_IDENTITY=- EXPANDED_CODE_SIGN_IDENTITY=- \
COMPILER_INDEX_STORE_ENABLE=NO CONFIGURATION=Release \
-destination generic/platform=iOS | xcpretty
popd
}
###############################################################################
# Building preconditions
###############################################################################
echo "Pre-caching ios artifacts, such as the Flutter.framework"
flutter precache --no-web --no-linux --no-windows --no-fuchsia --no-android --no-macos
echo "Fetching dependencies and building 'prebuilt_module/flutter_module'."
pushd add_to_app/prebuilt_module/flutter_module
flutter packages get
flutter build ios-framework --xcframework --output="$(pwd)/../ios_using_prebuilt_module/Flutter"
popd
flutter_packages_get "add_to_app/books/flutter_module_books"
flutter_packages_get "add_to_app/fullscreen/flutter_module"
flutter_packages_get "add_to_app/multiple_flutters/multiple_flutters_module"
flutter_packages_get "add_to_app/plugin/flutter_module_using_plugin"
###############################################################################
# Build projects
###############################################################################
build "add_to_app/books/ios_books" "IosBooks.xcworkspace" "IosBooks"
build "add_to_app/fullscreen/ios_fullscreen" "IOSFullScreen.xcworkspace" "IOSFullScreen"
build "add_to_app/multiple_flutters/multiple_flutters_ios" "MultipleFluttersIos.xcworkspace" "MultipleFluttersIos"
build "add_to_app/plugin/ios_using_plugin" "IOSUsingPlugin.xcworkspace" "IOSUsingPlugin"
echo "== Testing 'add_to_app/prebuilt_module/ios_using_prebuilt_module' on Flutter's $FLUTTER_VERSION channel =="
pushd "add_to_app/prebuilt_module/ios_using_prebuilt_module"
xcodebuild CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_IDENTITY=- EXPANDED_CODE_SIGN_IDENTITY=- \
COMPILER_INDEX_STORE_ENABLE=NO CONFIGURATION=Debug | xcpretty
xcodebuild CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO \
CODE_SIGN_IDENTITY=- EXPANDED_CODE_SIGN_IDENTITY=- \
COMPILER_INDEX_STORE_ENABLE=NO CONFIGURATION=Release \
-destination generic/platform=iOS | xcpretty
popd
echo "-- Success --"
| samples/tool/ios_ci_script.sh/0 | {
"file_path": "samples/tool/ios_ci_script.sh",
"repo_id": "samples",
"token_count": 1021
} | 1,186 |
// Copyright 2018 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 'dart:io' show Platform;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart' show DeviceOrientation, SystemChrome;
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:veggieseasons/data/app_state.dart';
import 'package:veggieseasons/data/preferences.dart';
import 'package:veggieseasons/screens/home.dart';
import 'package:veggieseasons/styles.dart';
import 'package:veggieseasons/widgets/fade_transition_page.dart';
import 'package:window_size/window_size.dart';
import 'screens/details.dart';
import 'screens/favorites.dart';
import 'screens/list.dart';
import 'screens/search.dart';
import 'screens/settings.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
setupWindow();
runApp(
const RootRestorationScope(
restorationId: 'root',
child: VeggieApp(),
),
);
}
const double windowWidth = 480;
const double windowHeight = 854;
void setupWindow() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
setWindowTitle('Veggie Seasons');
setWindowMinSize(const Size(windowWidth, windowHeight));
setWindowMaxSize(const Size(windowWidth, windowHeight));
getCurrentScreen().then((screen) {
setWindowFrame(Rect.fromCenter(
center: screen!.frame.center,
width: windowWidth,
height: windowHeight,
));
});
}
}
final _rootNavigatorKey = GlobalKey<NavigatorState>();
final _shellNavigatorKey = GlobalKey<NavigatorState>();
class VeggieApp extends StatefulWidget {
const VeggieApp({super.key});
@override
State<StatefulWidget> createState() => _VeggieAppState();
}
class _VeggieAppState extends State<VeggieApp> with RestorationMixin {
final _RestorableAppState _appState = _RestorableAppState();
@override
String get restorationId => 'wrapper';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_appState, 'state');
}
@override
void dispose() {
_appState.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider.value(
value: _appState.value,
),
ChangeNotifierProvider(
create: (_) => Preferences()..load(),
),
],
child: CupertinoApp.router(
theme: Styles.veggieThemeData,
debugShowCheckedModeBanner: false,
restorationScopeId: 'app',
routerConfig: GoRouter(
navigatorKey: _rootNavigatorKey,
restorationScopeId: 'router',
initialLocation: '/list',
redirect: (context, state) {
if (state.path == '/') {
return '/list';
}
return null;
},
debugLogDiagnostics: true,
routes: [
ShellRoute(
navigatorKey: _shellNavigatorKey,
pageBuilder: (context, state, child) {
return CupertinoPage(
restorationId: 'router.shell',
child: HomeScreen(
restorationId: 'home',
child: child,
onTap: (index) {
if (index == 0) {
context.go('/list');
} else if (index == 1) {
context.go('/favorites');
} else if (index == 2) {
context.go('/search');
} else {
context.go('/settings');
}
},
),
);
},
routes: [
GoRoute(
path: '/list',
pageBuilder: (context, state) {
return FadeTransitionPage(
key: state.pageKey,
restorationId: 'route.list',
child: const ListScreen(restorationId: 'list'),
);
},
routes: [
_buildDetailsRoute(),
],
),
GoRoute(
path: '/favorites',
pageBuilder: (context, state) {
return FadeTransitionPage(
key: state.pageKey,
restorationId: 'route.favorites',
child: const FavoritesScreen(restorationId: 'favorites'),
);
},
routes: [
_buildDetailsRoute(),
],
),
GoRoute(
path: '/search',
pageBuilder: (context, state) {
return FadeTransitionPage(
key: state.pageKey,
restorationId: 'route.search',
child: const SearchScreen(restorationId: 'search'),
);
},
routes: [
_buildDetailsRoute(),
],
),
GoRoute(
path: '/settings',
pageBuilder: (context, state) {
return FadeTransitionPage(
key: state.pageKey,
restorationId: 'route.settings',
child: const SettingsScreen(restorationId: 'settings'),
);
},
routes: [
GoRoute(
parentNavigatorKey: _rootNavigatorKey,
path: 'categories',
pageBuilder: (context, state) {
return VeggieCategorySettingsScreen.pageBuilder(
context);
},
),
GoRoute(
parentNavigatorKey: _rootNavigatorKey,
path: 'calories',
pageBuilder: (context, state) {
return CalorieSettingsScreen.pageBuilder(context);
},
),
],
),
],
),
],
),
),
);
}
// GoRouter does not support relative routes,
// see https://github.com/flutter/flutter/issues/108177
GoRoute _buildDetailsRoute() {
return GoRoute(
parentNavigatorKey: _rootNavigatorKey,
path: 'details/:id',
pageBuilder: (context, state) {
final veggieId = int.parse(state.pathParameters['id']!);
return CupertinoPage(
restorationId: 'route.details',
fullscreenDialog: true,
child: DetailsScreen(
id: veggieId,
restorationId: 'details',
),
);
},
);
}
}
class _RestorableAppState extends RestorableListenable<AppState> {
@override
AppState createDefaultValue() {
return AppState();
}
@override
AppState fromPrimitives(Object? data) {
final appState = AppState();
final favorites = (data as List<dynamic>).cast<int>();
for (var id in favorites) {
appState.setFavorite(id, true);
}
return appState;
}
@override
Object toPrimitives() {
return value.favoriteVeggies.map((veggie) => veggie.id).toList();
}
}
| samples/veggieseasons/lib/main.dart/0 | {
"file_path": "samples/veggieseasons/lib/main.dart",
"repo_id": "samples",
"token_count": 3925
} | 1,187 |
// Copyright 2020 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
// Called by https://pub.dartlang.org/packages/peanut to generate example pages
// for hosting.
//
// Requires at least v3.2.0 of `package:peanut`
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'common.dart';
void main(List<String> args) async {
final buildDir = args[0];
final fileMap =
(jsonDecode(args[1]) as Map<String, dynamic>).cast<String, String>();
if (fileMap.length < 2) {
throw StateError('We are assuming there is more than one sample!');
}
// This is USUALLY the case – where we have more than one demo
for (var exampleDir in fileMap.values) {
for (var htmlFile in Directory(p.join(buildDir, exampleDir))
.listSync()
.whereType<File>()
.where((f) => p.extension(f.path) == '.html')) {
_updateHtml(htmlFile, buildDir, exampleDir);
}
}
// Move each sample into a subdirectory, 'web'
for (var exampleDir in fileMap.values) {
var oldDirectory = Directory(p.join(buildDir, exampleDir));
Directory(p.join(buildDir, 'web')).createSync();
oldDirectory.renameSync(p.join(buildDir, 'web', exampleDir));
}
// Build the sample index and copy the files into this directory
print('building the sample index...');
await run('samples_index', 'flutter', ['pub', 'get']);
await run('samples_index', 'flutter', ['pub', 'run', 'grinder', 'deploy']);
// Copy the contents of the samples_index/public directory to the build
// directory
logWrapped(ansiMagenta, ' Copying samples_index/public to build directory');
var contents = Directory(p.join('samples_index', 'public')).listSync();
for (var entity in contents) {
var newPath = p.join(buildDir, p.basename(entity.path));
entity.renameSync(newPath);
}
}
void _updateHtml(File htmlFile, String buildDir, String exampleDir) {
final content = htmlFile.readAsStringSync();
final filePath = p.relative(htmlFile.path, from: buildDir);
if (!content.contains(_standardMeta)) {
print('!!! missing standard meta! - $filePath');
}
final newContent = content
.replaceFirst('<head>', '<head>\n$_analytics')
.replaceFirst(_emptyTitle,
'<title>${_prettyName(exampleDir)} - Flutter web sample</title>');
if (newContent == content) {
print('!!! Did not replace contents in $filePath');
} else {
print('Replaced contents in $filePath');
htmlFile.writeAsStringSync(newContent, flush: true);
}
}
final _underscoreOrSlash = RegExp('_|/');
String _prettyName(String input) =>
input.split(_underscoreOrSlash).where((e) => e.isNotEmpty).map((e) {
return e.substring(0, 1).toUpperCase() + e.substring(1);
}).join(' ');
// flutter.github.io
const _analyticsId = 'UA-67589403-8';
const _analytics = '''
<script async src="https://www.googletagmanager.com/gtag/js?id=$_analyticsId"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '$_analyticsId');
</script>''';
const _emptyTitle = '<title></title>';
const _standardMeta = '''
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
$_emptyTitle''';
| samples/web/_tool/peanut_post_build.dart/0 | {
"file_path": "samples/web/_tool/peanut_post_build.dart",
"repo_id": "samples",
"token_count": 1171
} | 1,188 |
// Copyright 2020 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 'dart:io';
import 'package:checked_yaml/checked_yaml.dart';
import 'src/data.dart';
export 'src/data.dart';
Future<List<Sample>> getSamples() async {
var yamlFile = File('lib/src/samples.yaml');
var contents = await yamlFile.readAsString();
var index = checkedYamlDecode(
contents, (m) => m != null ? Index.fromJson(m) : null,
sourceUrl: yamlFile.uri);
if (index == null) throw ('unable to get load from ${yamlFile.uri}');
return index.samples;
}
| samples/web/samples_index/lib/samples_index.dart/0 | {
"file_path": "samples/web/samples_index/lib/samples_index.dart",
"repo_id": "samples",
"token_count": 223
} | 1,189 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
channel: master
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
- platform: android
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
- platform: ios
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
- platform: linux
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
- platform: macos
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
- platform: web
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
- platform: windows
create_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
base_revision: f41ae4f4c925336400b11dc02986c1b4d78a173c
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| samples/web_embedding/ng-flutter/flutter/.metadata/0 | {
"file_path": "samples/web_embedding/ng-flutter/flutter/.metadata",
"repo_id": "samples",
"token_count": 758
} | 1,190 |
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
| samples/web_embedding/ng-flutter/tsconfig.spec.json/0 | {
"file_path": "samples/web_embedding/ng-flutter/tsconfig.spec.json",
"repo_id": "samples",
"token_count": 125
} | 1,191 |
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: Page1(),
),
);
}
class Page1 extends StatelessWidget {
const Page1({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(_createRoute());
},
child: const Text('Go!'),
),
),
);
}
}
Route _createRoute() {
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => const Page2(),
// #docregion transitionsBuilder
transitionsBuilder: (context, animation, secondaryAnimation, child) {
// #docregion Tween
const begin = Offset(0.0, 1.0);
const end = Offset.zero;
const curve = Curves.ease;
var tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
// #enddocregion Tween
// #docregion SlideTransition
return SlideTransition(
position: animation.drive(tween),
child: child,
);
// #enddocregion SlideTransition
},
// #enddocregion transitionsBuilder
);
}
class Page2 extends StatelessWidget {
const Page2({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: const Center(
child: Text('Page 2'),
),
);
}
}
| website/examples/cookbook/animation/page_route_animation/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/animation/page_route_animation/lib/main.dart",
"repo_id": "website",
"token_count": 594
} | 1,192 |
name: tabs
description: Sample code for tabs cookbook recipe.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/design/tabs/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/design/tabs/pubspec.yaml",
"repo_id": "website",
"token_count": 89
} | 1,193 |
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleDragAndDrop(),
debugShowCheckedModeBanner: false,
),
);
}
const List<Item> _items = [
Item(
name: 'Spinach Pizza',
totalPriceCents: 1299,
uid: '1',
imageProvider: NetworkImage('https://flutter'
'.dev/docs/cookbook/img-files/effects/split-check/Food1.jpg'),
),
Item(
name: 'Veggie Delight',
totalPriceCents: 799,
uid: '2',
imageProvider: NetworkImage('https://flutter'
'.dev/docs/cookbook/img-files/effects/split-check/Food2.jpg'),
),
Item(
name: 'Chicken Parmesan',
totalPriceCents: 1499,
uid: '3',
imageProvider: NetworkImage('https://flutter'
'.dev/docs/cookbook/img-files/effects/split-check/Food3.jpg'),
),
];
@immutable
class ExampleDragAndDrop extends StatefulWidget {
const ExampleDragAndDrop({super.key});
@override
State<ExampleDragAndDrop> createState() => _ExampleDragAndDropState();
}
class _ExampleDragAndDropState extends State<ExampleDragAndDrop>
with TickerProviderStateMixin {
final List<Customer> _people = [
Customer(
name: 'Makayla',
imageProvider: const NetworkImage('https://flutter'
'.dev/docs/cookbook/img-files/effects/split-check/Avatar1.jpg'),
),
Customer(
name: 'Nathan',
imageProvider: const NetworkImage('https://flutter'
'.dev/docs/cookbook/img-files/effects/split-check/Avatar2.jpg'),
),
Customer(
name: 'Emilio',
imageProvider: const NetworkImage('https://flutter'
'.dev/docs/cookbook/img-files/effects/split-check/Avatar3.jpg'),
),
];
final GlobalKey _draggableKey = GlobalKey();
// #docregion AddCart
void _itemDroppedOnCustomerCart({
required Item item,
required Customer customer,
}) {
setState(() {
customer.items.add(item);
});
}
// #enddocregion AddCart
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF7F7F7),
appBar: _buildAppBar(),
body: _buildContent(),
);
}
PreferredSizeWidget _buildAppBar() {
return AppBar(
iconTheme: const IconThemeData(color: Color(0xFFF64209)),
title: Text(
'Order Food',
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontSize: 36,
color: const Color(0xFFF64209),
fontWeight: FontWeight.bold,
),
),
backgroundColor: const Color(0xFFF7F7F7),
elevation: 0,
);
}
Widget _buildContent() {
return Stack(
children: [
SafeArea(
child: Column(
children: [
Expanded(
child: _buildMenuList(),
),
_buildPeopleRow(),
],
),
),
],
);
}
Widget _buildMenuList() {
return ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: _items.length,
separatorBuilder: (context, index) {
return const SizedBox(
height: 12,
);
},
itemBuilder: (context, index) {
final item = _items[index];
return _buildMenuItem(
item: item,
);
},
);
}
Widget _buildMenuItem({
required Item item,
}) {
// #docregion LongPressDraggable
return LongPressDraggable<Item>(
data: item,
dragAnchorStrategy: pointerDragAnchorStrategy,
feedback: DraggingListItem(
dragKey: _draggableKey,
photoProvider: item.imageProvider,
),
// #docregion MenuListItem
child: MenuListItem(
name: item.name,
price: item.formattedTotalItemPrice,
photoProvider: item.imageProvider,
),
// #enddocregion MenuListItem
);
// #enddocregion LongPressDraggable
}
Widget _buildPeopleRow() {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 20,
),
child: Row(
children: _people.map(_buildPersonWithDropZone).toList(),
),
);
}
Widget _buildPersonWithDropZone(Customer customer) {
return Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6,
),
// #docregion DragTarget
child: DragTarget<Item>(
builder: (context, candidateItems, rejectedItems) {
// #docregion CustomerCart
return CustomerCart(
hasItems: customer.items.isNotEmpty,
highlighted: candidateItems.isNotEmpty,
customer: customer,
);
// #enddocregion CustomerCart
},
onAcceptWithDetails: (details) {
_itemDroppedOnCustomerCart(
item: details.data,
customer: customer,
);
},
),
// #enddocregion DragTarget
),
);
}
}
class CustomerCart extends StatelessWidget {
const CustomerCart({
super.key,
required this.customer,
this.highlighted = false,
this.hasItems = false,
});
final Customer customer;
final bool highlighted;
final bool hasItems;
@override
Widget build(BuildContext context) {
final textColor = highlighted ? Colors.white : Colors.black;
return Transform.scale(
scale: highlighted ? 1.075 : 1.0,
child: Material(
elevation: highlighted ? 8 : 4,
borderRadius: BorderRadius.circular(22),
color: highlighted ? const Color(0xFFF64209) : Colors.white,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 24,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipOval(
child: SizedBox(
width: 46,
height: 46,
child: Image(
image: customer.imageProvider,
fit: BoxFit.cover,
),
),
),
const SizedBox(height: 8),
Text(
customer.name,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: textColor,
fontWeight:
hasItems ? FontWeight.normal : FontWeight.bold,
),
),
Visibility(
visible: hasItems,
maintainState: true,
maintainAnimation: true,
maintainSize: true,
child: Column(
children: [
const SizedBox(height: 4),
Text(
customer.formattedTotalItemPrice,
style: Theme.of(context).textTheme.bodySmall!.copyWith(
color: textColor,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'${customer.items.length} item${customer.items.length != 1 ? 's' : ''}',
style: Theme.of(context).textTheme.titleMedium!.copyWith(
color: textColor,
fontSize: 12,
),
),
],
),
)
],
),
),
),
);
}
}
class MenuListItem extends StatelessWidget {
const MenuListItem({
super.key,
this.name = '',
this.price = '',
required this.photoProvider,
this.isDepressed = false,
});
final String name;
final String price;
final ImageProvider photoProvider;
final bool isDepressed;
@override
Widget build(BuildContext context) {
return Material(
elevation: 12,
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(12),
child: SizedBox(
width: 120,
height: 120,
child: Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 100),
curve: Curves.easeInOut,
height: isDepressed ? 115 : 120,
width: isDepressed ? 115 : 120,
child: Image(
image: photoProvider,
fit: BoxFit.cover,
),
),
),
),
),
const SizedBox(width: 30),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontSize: 18,
),
),
const SizedBox(height: 10),
Text(
price,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
],
),
),
],
),
),
);
}
}
class DraggingListItem extends StatelessWidget {
const DraggingListItem({
super.key,
required this.dragKey,
required this.photoProvider,
});
final GlobalKey dragKey;
final ImageProvider photoProvider;
@override
Widget build(BuildContext context) {
return FractionalTranslation(
translation: const Offset(-0.5, -0.5),
child: ClipRRect(
key: dragKey,
borderRadius: BorderRadius.circular(12),
child: SizedBox(
height: 150,
width: 150,
child: Opacity(
opacity: 0.85,
child: Image(
image: photoProvider,
fit: BoxFit.cover,
),
),
),
),
);
}
}
@immutable
class Item {
const Item({
required this.totalPriceCents,
required this.name,
required this.uid,
required this.imageProvider,
});
final int totalPriceCents;
final String name;
final String uid;
final ImageProvider imageProvider;
String get formattedTotalItemPrice =>
'\$${(totalPriceCents / 100.0).toStringAsFixed(2)}';
}
// #docregion CustomerClass
class Customer {
Customer({
required this.name,
required this.imageProvider,
List<Item>? items,
}) : items = items ?? [];
final String name;
final ImageProvider imageProvider;
final List<Item> items;
String get formattedTotalItemPrice {
final totalPriceCents =
items.fold<int>(0, (prev, item) => prev + item.totalPriceCents);
return '\$${(totalPriceCents / 100.0).toStringAsFixed(2)}';
}
}
// #enddocregion CustomerClass
| website/examples/cookbook/effects/drag_a_widget/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/effects/drag_a_widget/lib/main.dart",
"repo_id": "website",
"token_count": 5612
} | 1,194 |
// This file has only enough in it to satisfy `firestore_controller.dart`.
class PlayingCard {
const PlayingCard();
factory PlayingCard.fromJson(Map<String, dynamic> json) {
return const PlayingCard();
}
Map<String, dynamic> toJson() => {
// Nothing
};
}
| website/examples/cookbook/games/firestore_multiplayer/lib/game_internals/playing_card.dart/0 | {
"file_path": "website/examples/cookbook/games/firestore_multiplayer/lib/game_internals/playing_card.dart",
"repo_id": "website",
"token_count": 95
} | 1,195 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Floating App Bar';
return MaterialApp(
title: title,
home: Scaffold(
// No appbar provided to the Scaffold, only a body with a
// CustomScrollView.
body: CustomScrollView(
slivers: [
// Add the app bar to the CustomScrollView.
const SliverAppBar(
// Provide a standard title.
title: Text(title),
// Allows the user to reveal the app bar if they begin scrolling
// back up the list of items.
floating: true,
// Display a placeholder widget to visualize the shrinking size.
flexibleSpace: Placeholder(),
// Make the initial height of the SliverAppBar larger than normal.
expandedHeight: 200,
),
// #docregion SliverList
// Next, create a SliverList
SliverList(
// Use a delegate to build items as they're scrolled on screen.
delegate: SliverChildBuilderDelegate(
// The builder function returns a ListTile with a title that
// displays the index of the current item.
(context, index) => ListTile(title: Text('Item #$index')),
// Builds 1000 ListTiles
childCount: 1000,
),
),
// #enddocregion SliverList
],
),
),
);
}
}
| website/examples/cookbook/lists/floating_app_bar/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/lists/floating_app_bar/lib/main.dart",
"repo_id": "website",
"token_count": 748
} | 1,196 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// #docregion Routes
// #docregion OnGenerateRoute
return MaterialApp(
routes: {
ExtractArgumentsScreen.routeName: (context) =>
const ExtractArgumentsScreen(),
},
// #enddocregion Routes
// Provide a function to handle named routes.
// Use this function to identify the named
// route being pushed, and create the correct
// Screen.
onGenerateRoute: (settings) {
// If you push the PassArguments route
if (settings.name == PassArgumentsScreen.routeName) {
// Cast the arguments to the correct
// type: ScreenArguments.
final args = settings.arguments as ScreenArguments;
// Then, extract the required data from
// the arguments and pass the data to the
// correct screen.
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
// The code only supports
// PassArgumentsScreen.routeName right now.
// Other values need to be implemented if we
// add them. The assertion here will help remind
// us of that higher up in the call stack, since
// this assertion would otherwise fire somewhere
// in the framework.
assert(false, 'Need to implement ${settings.name}');
return null;
},
// #enddocregion OnGenerateRoute
title: 'Navigation with Arguments',
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// #docregion PushNamed
// A button that navigates to a named route.
// The named route extracts the arguments
// by itself.
ElevatedButton(
onPressed: () {
// When the user taps the button,
// navigate to a named route and
// provide the arguments as an optional
// parameter.
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
},
child: const Text('Navigate to screen that extracts arguments'),
),
// #enddocregion PushNamed
// A button that navigates to a named route.
// For this route, extract the arguments in
// the onGenerateRoute function and pass them
// to the screen.
ElevatedButton(
onPressed: () {
// When the user taps the button, navigate
// to a named route and provide the arguments
// as an optional parameter.
Navigator.pushNamed(
context,
PassArgumentsScreen.routeName,
arguments: ScreenArguments(
'Accept Arguments Screen',
'This message is extracted in the onGenerateRoute '
'function.',
),
);
},
child: const Text('Navigate to a named that accepts arguments'),
),
],
),
),
);
}
}
// #docregion ExtractArgumentsScreen
// A Widget that extracts the necessary arguments from
// the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
const ExtractArgumentsScreen({super.key});
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
// Extract the arguments from the current ModalRoute
// settings and cast them as ScreenArguments.
final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
// #enddocregion ExtractArgumentsScreen
// A Widget that accepts the necessary arguments via the
// constructor.
class PassArgumentsScreen extends StatelessWidget {
static const routeName = '/passArguments';
final String title;
final String message;
// This Widget accepts the arguments as constructor
// parameters. It does not extract the arguments from
// the ModalRoute.
//
// The arguments are extracted by the onGenerateRoute
// function provided to the MaterialApp widget.
const PassArgumentsScreen({
super.key,
required this.title,
required this.message,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(message),
),
);
}
}
// #docregion ScreenArguments
// You can pass any object to the arguments parameter.
// In this example, create a class that contains both
// a customizable title and message.
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}
// #enddocregion ScreenArguments
| website/examples/cookbook/navigation/navigate_with_arguments/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/navigation/navigate_with_arguments/lib/main.dart",
"repo_id": "website",
"token_count": 2388
} | 1,197 |
name: returning_data
description: Returning data
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/navigation/returning_data/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/navigation/returning_data/pubspec.yaml",
"repo_id": "website",
"token_count": 85
} | 1,198 |
name: key_value
publish_to: none
description: >-
Examples and code excerpts for a cookbook recipe that
shows how to use the shared_preferences package.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.2
flutter_test:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/persistence/key_value/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/persistence/key_value/pubspec.yaml",
"repo_id": "website",
"token_count": 148
} | 1,199 |
import 'dart:io';
import 'package:flutter/material.dart';
class MyImage extends StatelessWidget {
const MyImage({super.key});
@override
Widget build(BuildContext context) {
// #docregion ImageFile
return Image.file(File('path/to/my/picture.png'));
// #enddocregion ImageFile
}
}
| website/examples/cookbook/plugins/picture_using_camera/lib/image_file.dart/0 | {
"file_path": "website/examples/cookbook/plugins/picture_using_camera/lib/image_file.dart",
"repo_id": "website",
"token_count": 105
} | 1,200 |
// #docregion ScrollWidgetTest
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:scrolling/main.dart';
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Counter increments smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
));
final listFinder = find.byType(Scrollable);
final itemFinder = find.byKey(const ValueKey('item_50_text'));
// #docregion traceAction
await binding.traceAction(
() async {
// Scroll until the item to be found appears.
await tester.scrollUntilVisible(
itemFinder,
500.0,
scrollable: listFinder,
);
},
reportKey: 'scrolling_timeline',
);
// #enddocregion traceAction
});
}
// #enddocregion ScrollWidgetTest
| website/examples/cookbook/testing/integration/profiling/integration_test/scrolling_test.dart/0 | {
"file_path": "website/examples/cookbook/testing/integration/profiling/integration_test/scrolling_test.dart",
"repo_id": "website",
"token_count": 386
} | 1,201 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
// #docregion test1
testWidgets('finds a Text widget', (tester) async {
// Build an App with a Text widget that displays the letter 'H'.
await tester.pumpWidget(const MaterialApp(
home: Scaffold(
body: Text('H'),
),
));
// Find a widget that displays the letter 'H'.
expect(find.text('H'), findsOneWidget);
});
// #enddocregion test1
// #docregion test2
testWidgets('finds a widget using a Key', (tester) async {
// Define the test key.
const testKey = Key('K');
// Build a MaterialApp with the testKey.
await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));
// Find the MaterialApp widget using the testKey.
expect(find.byKey(testKey), findsOneWidget);
});
// #enddocregion test2
// #docregion test3
testWidgets('finds a specific instance', (tester) async {
const childWidget = Padding(padding: EdgeInsets.zero);
// Provide the childWidget to the Container.
await tester.pumpWidget(Container(child: childWidget));
// Search for the childWidget in the tree and verify it exists.
expect(find.byWidget(childWidget), findsOneWidget);
});
// #enddocregion test3
}
| website/examples/cookbook/testing/widget/finders/test/finders_test.dart/0 | {
"file_path": "website/examples/cookbook/testing/widget/finders/test/finders_test.dart",
"repo_id": "website",
"token_count": 444
} | 1,202 |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
User _$UserFromJson(Map<String, dynamic> json) => User(
json['name'] as String,
Address.fromJson(json['address'] as Map<String, dynamic>),
);
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
'name': instance.name,
'address': instance.address.toJson(),
};
| website/examples/development/data-and-backend/json/lib/nested/user.g.dart/0 | {
"file_path": "website/examples/development/data-and-backend/json/lib/nested/user.g.dart",
"repo_id": "website",
"token_count": 169
} | 1,203 |
// #docregion CssColors
import 'package:css_colors/css_colors.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: DemoPage(),
);
}
}
class DemoPage extends StatelessWidget {
const DemoPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(body: Container(color: CSSColors.orange));
}
}
// #enddocregion CssColors
| website/examples/development/plugin_api_migration/lib/css_colors.dart/0 | {
"file_path": "website/examples/development/plugin_api_migration/lib/css_colors.dart",
"repo_id": "website",
"token_count": 195
} | 1,204 |
name: example_utils
description: Utils for examples and code snippets on docs.flutter.dev.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter_lints: ^3.0.1
| website/examples/example_utils/pubspec.yaml/0 | {
"file_path": "website/examples/example_utils/pubspec.yaml",
"repo_id": "website",
"token_count": 65
} | 1,205 |
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
class MyButton extends StatelessWidget {
const MyButton({super.key});
// #docregion onPressed
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
developer.log('click');
},
child: const Text('Button'),
);
}
// #enddocregion onPressed
}
// #docregion onTap
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,
),
),
),
);
}
}
// #enddocregion onTap
// #docregion SampleApp
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,
),
),
),
),
);
}
}
// #enddocregion SampleApp
| website/examples/get-started/flutter-for/android_devs/lib/events.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/events.dart",
"repo_id": "website",
"token_count": 835
} | 1,206 |
import 'package:flutter/material.dart';
// #docregion Strings
class Strings {
static String welcomeMessage = 'Welcome To Flutter';
}
// #enddocregion Strings
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return
// #docregion AccessString
Text(Strings.welcomeMessage);
// #enddocregion AccessString
}
}
| website/examples/get-started/flutter-for/android_devs/lib/string_examples.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/string_examples.dart",
"repo_id": "website",
"token_count": 137
} | 1,207 |
import 'package:flutter/material.dart';
// #docregion CustomButton
class CustomButton extends StatelessWidget {
const CustomButton(this.label, {super.key});
final String label;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {},
child: Text(label),
);
}
}
// #enddocregion CustomButton
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
// #docregion UseCustomButton
@override
Widget build(BuildContext context) {
return const Center(
child: CustomButton('Hello'),
);
}
// #enddocregion UseCustomButton
}
| website/examples/get-started/flutter-for/ios_devs/lib/custom.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/custom.dart",
"repo_id": "website",
"token_count": 205
} | 1,208 |
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
],
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/localizations_example.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/localizations_example.dart",
"repo_id": "website",
"token_count": 242
} | 1,209 |
// #docregion Theme
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(),
);
}
}
// #enddocregion Theme
class SampleAppPage extends StatelessWidget {
const SampleAppPage({super.key});
@override
Widget build(BuildContext context) {
return const Text('Hello World!');
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/theme.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/theme.dart",
"repo_id": "website",
"token_count": 223
} | 1,210 |
import 'package:flutter/material.dart';
void main() => runApp(
const MyStatelessWidget(
text: 'StatelessWidget Example to show immutable data',
),
);
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget({
super.key,
required this.text,
});
final String text;
@override
Widget build(BuildContext context) {
return Center(
child: Text(
text,
textDirection: TextDirection.ltr,
),
);
}
}
| website/examples/get-started/flutter-for/react_native_devs/lib/stateless.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/stateless.dart",
"repo_id": "website",
"token_count": 191
} | 1,211 |
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
// #docregion ElevatedButton
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
developer.log('click');
},
child: const Text('Button'),
);
}
// #enddocregion ElevatedButton
}
// #docregion GestureDetector
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
developer.log('tap');
},
child: const FlutterLogo(size: 200),
),
),
);
}
}
// #enddocregion GestureDetector
// #docregion RotatingFlutterDetector
class RotatingFlutterDetector extends StatefulWidget {
const RotatingFlutterDetector({super.key});
@override
State<RotatingFlutterDetector> createState() =>
_RotatingFlutterDetectorState();
}
class _RotatingFlutterDetectorState extends State<RotatingFlutterDetector>
with SingleTickerProviderStateMixin {
late final AnimationController controller;
late final CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
curve = CurvedAnimation(parent: controller, curve: Curves.easeIn);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onDoubleTap: () {
if (controller.isCompleted) {
controller.reverse();
} else {
controller.forward();
}
},
child: RotationTransition(
turns: curve,
child: const FlutterLogo(size: 200),
),
),
),
);
}
}
// #enddocregion RotatingFlutterDetector
| website/examples/get-started/flutter-for/xamarin_devs/lib/gestures.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/gestures.dart",
"repo_id": "website",
"token_count": 809
} | 1,212 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
// #docregion Text
return const Text(
'I like Flutter!',
style: TextStyle(fontWeight: FontWeight.bold),
);
// #enddocregion Text
}
}
// #docregion AddRemoveElement
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),
),
);
}
}
// #enddocregion AddRemoveElement
| website/examples/get-started/flutter-for/xamarin_devs/lib/views.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/views.dart",
"repo_id": "website",
"token_count": 581
} | 1,213 |
// #docregion Imports
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test_migration/main.dart';
// #enddocregion Imports
void main() {
// #docregion Test1
testWidgets('do not select any item, verify please select text is displayed',
(tester) async {
// load the PlantsApp widget
await tester.pumpWidget(const PlantsApp());
// wait for data to load
await tester.pumpAndSettle();
// Find widget with 'please select'
final finder = find.text('Please select a plant from the list.');
// Check if widget is displayed
expect(finder, findsOneWidget);
});
// #enddocregion Test1
// #docregion Test2
testWidgets('tap on the first item (Alder), verify selected', (tester) async {
await tester.pumpWidget(const PlantsApp());
// wait for data to load
await tester.pumpAndSettle();
// find the item by text
final item = find.text('Alder');
// assert item is found
expect(item, findsOneWidget);
// Emulate a tap on the tile item.
await tester.tap(item);
await tester.pumpAndSettle();
// Species name should be displayed
expect(find.text('Alnus'), findsOneWidget);
// 'please select' text should not be displayed
expect(find.text('Please select a plant from the list.'), findsNothing);
});
// #enddocregion Test2
// #docregion Test3
testWidgets('scroll, tap on the last item (Zedoary), verify selected',
(tester) async {
await tester.pumpWidget(const PlantsApp());
// wait for data to load
await tester.pumpAndSettle();
// find the item by text
final item = find.text('Zedoary');
// finds Scrollable widget and scrolls until item is visible
// a 100,000 pixels is enough to reach the bottom of the list
await tester.scrollUntilVisible(
item,
100000,
);
// assert item is found
expect(item, findsOneWidget);
// Emulate a tap on the tile item.
await tester.tap(item);
await tester.pumpAndSettle();
// Wait for species name to be displayed
expect(find.text('Curcuma zedoaria'), findsOneWidget);
// 'please select' text should not be displayed
expect(find.text('Please select a plant from the list.'), findsNothing);
});
// #enddocregion Test3
}
| website/examples/integration_test_migration/integration_test/main_test.dart/0 | {
"file_path": "website/examples/integration_test_migration/integration_test/main_test.dart",
"repo_id": "website",
"token_count": 768
} | 1,214 |
import 'package:flutter/material.dart';
// #docregion AppLocalizationsImport
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
// #enddocregion AppLocalizationsImport
// #docregion LocalizationDelegatesImport
import 'package:flutter_localizations/flutter_localizations.dart';
// #enddocregion LocalizationDelegatesImport
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// #docregion MaterialApp
return const MaterialApp(
title: 'Localizations Sample App',
localizationsDelegates: [
AppLocalizations.delegate, // Add this line
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
Locale('en'), // English
Locale('es'), // Spanish
],
home: MyHomePage(),
);
// #enddocregion MaterialApp
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
// #docregion InternationalizedTitle
appBar: AppBar(
// The [AppBar] title text should update its message
// according to the system locale of the target platform.
// Switching between English and Spanish locales should
// cause this text to update.
title: Text(AppLocalizations.of(context)!.helloWorld),
),
// #enddocregion InternationalizedTitle
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// Add the following code
Localizations.override(
context: context,
locale: const Locale('en'),
// Using a Builder here to get the correct BuildContext.
// Alternatively, you can create a new widget and Localizations.override
// will pass the updated BuildContext to the new widget.
child: Builder(
builder: (context) {
// #docregion Placeholder
// Examples of internationalized strings.
return Column(
children: <Widget>[
// Returns 'Hello John'
Text(AppLocalizations.of(context)!.hello('John')),
// Returns 'no wombats'
Text(AppLocalizations.of(context)!.nWombats(0)),
// Returns '1 wombat'
Text(AppLocalizations.of(context)!.nWombats(1)),
// Returns '5 wombats'
Text(AppLocalizations.of(context)!.nWombats(5)),
// Returns 'he'
Text(AppLocalizations.of(context)!.pronoun('male')),
// Returns 'she'
Text(AppLocalizations.of(context)!.pronoun('female')),
// Returns 'they'
Text(AppLocalizations.of(context)!.pronoun('other')),
],
);
// #enddocregion Placeholder
},
),
),
],
),
),
);
}
}
void main() {
runApp(const MyApp());
}
| website/examples/internationalization/gen_l10n_example/lib/main.dart/0 | {
"file_path": "website/examples/internationalization/gen_l10n_example/lib/main.dart",
"repo_id": "website",
"token_count": 1556
} | 1,215 |
name: l10n_example
description: A minimal example of a localized Flutter app
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../example_utils
flutter:
uses-material-design: true
| website/examples/internationalization/minimal/pubspec.yaml/0 | {
"file_path": "website/examples/internationalization/minimal/pubspec.yaml",
"repo_id": "website",
"token_count": 110
} | 1,216 |
import 'package:flutter/material.dart';
void main() => runApp(const HomePage());
const red = Colors.red;
const green = Colors.green;
const blue = Colors.blue;
const big = TextStyle(fontSize: 30);
//////////////////////////////////////////////////
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return const FlutterLayoutArticle([
Example1(),
Example2(),
Example3(),
Example4(),
Example5(),
Example6(),
Example7(),
Example8(),
Example9(),
Example10(),
Example11(),
Example12(),
Example13(),
Example14(),
Example15(),
Example16(),
Example17(),
Example18(),
Example19(),
Example20(),
Example21(),
Example22(),
Example23(),
Example24(),
Example25(),
Example26(),
Example27(),
Example28(),
Example29(),
]);
}
}
//////////////////////////////////////////////////
abstract class Example extends StatelessWidget {
const Example({super.key});
String get code;
String get explanation;
}
//////////////////////////////////////////////////
class FlutterLayoutArticle extends StatefulWidget {
const FlutterLayoutArticle(
this.examples, {
super.key,
});
final List<Example> examples;
@override
State<FlutterLayoutArticle> createState() => _FlutterLayoutArticleState();
}
//////////////////////////////////////////////////
class _FlutterLayoutArticleState extends State<FlutterLayoutArticle> {
late int count;
late Widget example;
late String code;
late String explanation;
@override
void initState() {
count = 1;
code = const Example1().code;
explanation = const Example1().explanation;
super.initState();
}
@override
void didUpdateWidget(FlutterLayoutArticle oldWidget) {
super.didUpdateWidget(oldWidget);
var example = widget.examples[count - 1];
code = example.code;
explanation = example.explanation;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Layout Article',
home: SafeArea(
child: Material(
color: Colors.black,
child: FittedBox(
child: Container(
width: 400,
height: 670,
color: const Color(0xFFCCCCCC),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints.tightFor(
width: double.infinity, height: double.infinity),
child: widget.examples[count - 1])),
Container(
height: 50,
width: double.infinity,
color: Colors.black,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (int i = 0; i < widget.examples.length; i++)
Container(
width: 58,
padding: const EdgeInsets.only(left: 4, right: 4),
child: button(i + 1),
),
],
),
),
),
Container(
height: 273,
color: Colors.grey[50],
child: Scrollbar(
child: SingleChildScrollView(
key: ValueKey(count),
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
Center(child: Text(code)),
const SizedBox(height: 15),
Text(
explanation,
style: TextStyle(
color: Colors.blue[900],
fontStyle: FontStyle.italic),
),
],
),
),
),
),
),
],
),
),
),
),
),
);
}
Widget button(int exampleNumber) {
return Button(
key: ValueKey('button$exampleNumber'),
isSelected: count == exampleNumber,
exampleNumber: exampleNumber,
onPressed: () {
showExample(
exampleNumber,
widget.examples[exampleNumber - 1].code,
widget.examples[exampleNumber - 1].explanation,
);
},
);
}
void showExample(int exampleNumber, String code, String explanation) {
setState(() {
count = exampleNumber;
this.code = code;
this.explanation = explanation;
});
}
}
//////////////////////////////////////////////////
class Button extends StatelessWidget {
final bool isSelected;
final int exampleNumber;
final VoidCallback onPressed;
const Button({
super.key,
required this.isSelected,
required this.exampleNumber,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: isSelected ? Colors.grey : Colors.grey[800],
),
child: Text(exampleNumber.toString()),
onPressed: () {
Scrollable.ensureVisible(
context,
duration: const Duration(milliseconds: 350),
curve: Curves.easeOut,
alignment: 0.5,
);
onPressed();
},
);
}
}
//////////////////////////////////////////////////
class Example1 extends Example {
const Example1({super.key});
@override
final code = 'Container(color: red)';
@override
final explanation = 'The screen is the parent of the Container, '
'and it forces the Container to be exactly the same size as the screen.'
'\n\n'
'So the Container fills the screen and paints it red.';
@override
Widget build(BuildContext context) {
// #docregion Example1
return Container(color: red);
// #enddocregion Example1
}
}
//////////////////////////////////////////////////
class Example2 extends Example {
const Example2({super.key});
@override
final code = 'Container(width: 100, height: 100, color: red)';
@override
final String explanation =
'The red Container wants to be 100x100, but it can\'t, '
'because the screen forces it to be exactly the same size as the screen.'
'\n\n'
'So the Container fills the screen.';
@override
Widget build(BuildContext context) {
// #docregion Example2
return Container(width: 100, height: 100, color: red);
// #enddocregion Example2
}
}
//////////////////////////////////////////////////
class Example3 extends Example {
const Example3({super.key});
@override
final code = 'Center(\n'
' child: Container(width: 100, height: 100, color: red))';
@override
final String explanation =
'The screen forces the Center to be exactly the same size as the screen, '
'so the Center fills the screen.'
'\n\n'
'The Center tells the Container that it can be any size it wants, but not bigger than the screen.'
'Now the Container can indeed be 100x100.';
@override
Widget build(BuildContext context) {
// #docregion Example3
return Center(
child: Container(width: 100, height: 100, color: red),
);
// #enddocregion Example3
}
}
//////////////////////////////////////////////////
class Example4 extends Example {
const Example4({super.key});
@override
final code = 'Align(\n'
' alignment: Alignment.bottomRight,\n'
' child: Container(width: 100, height: 100, color: red))';
@override
final String explanation =
'This is different from the previous example in that it uses Align instead of Center.'
'\n\n'
'Align also tells the Container that it can be any size it wants, but if there is empty space it won\'t center the Container. '
'Instead, it aligns the Container to the bottom-right of the available space.';
@override
Widget build(BuildContext context) {
// #docregion Example4
return Align(
alignment: Alignment.bottomRight,
child: Container(width: 100, height: 100, color: red),
);
// #enddocregion Example4
}
}
//////////////////////////////////////////////////
class Example5 extends Example {
const Example5({super.key});
@override
final code = 'Center(\n'
' child: Container(\n'
' color: red,\n'
' width: double.infinity,\n'
' height: double.infinity))';
@override
final String explanation =
'The screen forces the Center to be exactly the same size as the screen, '
'so the Center fills the screen.'
'\n\n'
'The Center tells the Container that it can be any size it wants, but not bigger than the screen.'
'The Container wants to be of infinite size, but since it can\'t be bigger than the screen, it just fills the screen.';
@override
Widget build(BuildContext context) {
// #docregion Example5
return Center(
child: Container(
width: double.infinity, height: double.infinity, color: red),
);
// #enddocregion Example5
}
}
//////////////////////////////////////////////////
class Example6 extends Example {
const Example6({super.key});
@override
final code = 'Center(child: Container(color: red))';
@override
final String explanation =
'The screen forces the Center to be exactly the same size as the screen, '
'so the Center fills the screen.'
'\n\n'
'The Center tells the Container that it can be any size it wants, but not bigger than the screen.'
'\n\n'
'Since the Container has no child and no fixed size, it decides it wants to be as big as possible, so it fills the whole screen.'
'\n\n'
'But why does the Container decide that? '
'Simply because that\'s a design decision by those who created the Container widget. '
'It could have been created differently, and you have to read the Container documentation to understand how it behaves, depending on the circumstances. ';
@override
Widget build(BuildContext context) {
// #docregion Example6
return Center(
child: Container(color: red),
);
// #enddocregion Example6
}
}
//////////////////////////////////////////////////
class Example7 extends Example {
const Example7({super.key});
@override
final code = 'Center(\n'
' child: Container(color: red\n'
' child: Container(color: green, width: 30, height: 30)))';
@override
final String explanation =
'The screen forces the Center to be exactly the same size as the screen, '
'so the Center fills the screen.'
'\n\n'
'The Center tells the red Container that it can be any size it wants, but not bigger than the screen.'
'Since the red Container has no size but has a child, it decides it wants to be the same size as its child.'
'\n\n'
'The red Container tells its child that it can be any size it wants, but not bigger than the screen.'
'\n\n'
'The child is a green Container that wants to be 30x30.'
'\n\n'
'Since the red `Container` has no size but has a child, it decides it wants to be the same size as its child. '
'The red color isn\'t visible, since the green Container entirely covers all of the red Container.';
@override
Widget build(BuildContext context) {
// #docregion Example7
return Center(
child: Container(
color: red,
child: Container(color: green, width: 30, height: 30),
),
);
// #enddocregion Example7
}
}
//////////////////////////////////////////////////
class Example8 extends Example {
const Example8({super.key});
@override
final code = 'Center(\n'
' child: Container(color: red\n'
' padding: const EdgeInsets.all(20),\n'
' child: Container(color: green, width: 30, height: 30)))';
@override
final String explanation =
'The red Container sizes itself to its children size, but it takes its own padding into consideration. '
'So it is also 30x30 plus padding. '
'The red color is visible because of the padding, and the green Container has the same size as in the previous example.';
@override
Widget build(BuildContext context) {
// #docregion Example8
return Center(
child: Container(
padding: const EdgeInsets.all(20),
color: red,
child: Container(color: green, width: 30, height: 30),
),
);
// #enddocregion Example8
}
}
//////////////////////////////////////////////////
class Example9 extends Example {
const Example9({super.key});
@override
final code = 'ConstrainedBox(\n'
' constraints: BoxConstraints(\n'
' minWidth: 70, minHeight: 70,\n'
' maxWidth: 150, maxHeight: 150),\n'
' child: Container(color: red, width: 10, height: 10)))';
@override
final String explanation =
'You might guess that the Container has to be between 70 and 150 pixels, but you would be wrong. '
'The ConstrainedBox only imposes ADDITIONAL constraints from those it receives from its parent.'
'\n\n'
'Here, the screen forces the ConstrainedBox to be exactly the same size as the screen, '
'so it tells its child Container to also assume the size of the screen, '
'thus ignoring its \'constraints\' parameter.';
@override
Widget build(BuildContext context) {
// #docregion Example9
return ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 70,
minHeight: 70,
maxWidth: 150,
maxHeight: 150,
),
child: Container(color: red, width: 10, height: 10),
);
// #enddocregion Example9
}
}
//////////////////////////////////////////////////
class Example10 extends Example {
const Example10({super.key});
@override
final code = 'Center(\n'
' child: ConstrainedBox(\n'
' constraints: BoxConstraints(\n'
' minWidth: 70, minHeight: 70,\n'
' maxWidth: 150, maxHeight: 150),\n'
' child: Container(color: red, width: 10, height: 10))))';
@override
final String explanation =
'Now, Center allows ConstrainedBox to be any size up to the screen size.'
'\n\n'
'The ConstrainedBox imposes ADDITIONAL constraints from its \'constraints\' parameter onto its child.'
'\n\n'
'The Container must be between 70 and 150 pixels. It wants to have 10 pixels, so it will end up having 70 (the MINIMUM).';
@override
Widget build(BuildContext context) {
// #docregion Example10
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 70,
minHeight: 70,
maxWidth: 150,
maxHeight: 150,
),
child: Container(color: red, width: 10, height: 10),
),
);
// #enddocregion Example10
}
}
//////////////////////////////////////////////////
class Example11 extends Example {
const Example11({super.key});
@override
final code = 'Center(\n'
' child: ConstrainedBox(\n'
' constraints: BoxConstraints(\n'
' minWidth: 70, minHeight: 70,\n'
' maxWidth: 150, maxHeight: 150),\n'
' child: Container(color: red, width: 1000, height: 1000))))';
@override
final String explanation =
'Center allows ConstrainedBox to be any size up to the screen size.'
'The ConstrainedBox imposes ADDITIONAL constraints from its \'constraints\' parameter onto its child'
'\n\n'
'The Container must be between 70 and 150 pixels. It wants to have 1000 pixels, so it ends up having 150 (the MAXIMUM).';
@override
Widget build(BuildContext context) {
// #docregion Example11
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 70,
minHeight: 70,
maxWidth: 150,
maxHeight: 150,
),
child: Container(color: red, width: 1000, height: 1000),
),
);
// #enddocregion Example11
}
}
//////////////////////////////////////////////////
class Example12 extends Example {
const Example12({super.key});
@override
final code = 'Center(\n'
' child: ConstrainedBox(\n'
' constraints: BoxConstraints(\n'
' minWidth: 70, minHeight: 70,\n'
' maxWidth: 150, maxHeight: 150),\n'
' child: Container(color: red, width: 100, height: 100))))';
@override
final String explanation =
'Center allows ConstrainedBox to be any size up to the screen size.'
'ConstrainedBox imposes ADDITIONAL constraints from its \'constraints\' parameter onto its child.'
'\n\n'
'The Container must be between 70 and 150 pixels. It wants to have 100 pixels, and that\'s the size it has, since that\'s between 70 and 150.';
@override
Widget build(BuildContext context) {
// #docregion Example12
return Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 70,
minHeight: 70,
maxWidth: 150,
maxHeight: 150,
),
child: Container(color: red, width: 100, height: 100),
),
);
// #enddocregion Example12
}
}
//////////////////////////////////////////////////
class Example13 extends Example {
const Example13({super.key});
@override
final code = 'UnconstrainedBox(\n'
' child: Container(color: red, width: 20, height: 50));';
@override
final String explanation =
'The screen forces the UnconstrainedBox to be exactly the same size as the screen.'
'However, the UnconstrainedBox lets its child Container be any size it wants.';
@override
Widget build(BuildContext context) {
// #docregion Example13
return UnconstrainedBox(
child: Container(color: red, width: 20, height: 50),
);
// #enddocregion Example13
}
}
//////////////////////////////////////////////////
class Example14 extends Example {
const Example14({super.key});
@override
final code = 'UnconstrainedBox(\n'
' child: Container(color: red, width: 4000, height: 50));';
@override
final String explanation =
'The screen forces the UnconstrainedBox to be exactly the same size as the screen, '
'and UnconstrainedBox lets its child Container be any size it wants.'
'\n\n'
'Unfortunately, in this case the Container has 4000 pixels of width and is too big to fit in the UnconstrainedBox, '
'so the UnconstrainedBox displays the much dreaded "overflow warning".';
@override
Widget build(BuildContext context) {
// #docregion Example14
return UnconstrainedBox(
child: Container(color: red, width: 4000, height: 50),
);
// #enddocregion Example14
}
}
//////////////////////////////////////////////////
class Example15 extends Example {
const Example15({super.key});
@override
final code = 'OverflowBox(\n'
' minWidth: 0,'
' minHeight: 0,'
' maxWidth: double.infinity,'
' maxHeight: double.infinity,'
' child: Container(color: red, width: 4000, height: 50));';
@override
final String explanation =
'The screen forces the OverflowBox to be exactly the same size as the screen, '
'and OverflowBox lets its child Container be any size it wants.'
'\n\n'
'OverflowBox is similar to UnconstrainedBox, and the difference is that it won\'t display any warnings if the child doesn\'t fit the space.'
'\n\n'
'In this case the Container is 4000 pixels wide, and is too big to fit in the OverflowBox, '
'but the OverflowBox simply shows as much as it can, with no warnings given.';
@override
Widget build(BuildContext context) {
// #docregion Example15
return OverflowBox(
minWidth: 0,
minHeight: 0,
maxWidth: double.infinity,
maxHeight: double.infinity,
child: Container(color: red, width: 4000, height: 50),
);
// #enddocregion Example15
}
}
//////////////////////////////////////////////////
class Example16 extends Example {
const Example16({super.key});
@override
final code = 'UnconstrainedBox(\n'
' child: Container(color: Colors.red, width: double.infinity, height: 100));';
@override
final String explanation =
'This won\'t render anything, and you\'ll see an error in the console.'
'\n\n'
'The UnconstrainedBox lets its child be any size it wants, '
'however its child is a Container with infinite size.'
'\n\n'
'Flutter can\'t render infinite sizes, so it throws an error with the following message: '
'"BoxConstraints forces an infinite width."';
@override
Widget build(BuildContext context) {
// #docregion Example16
return UnconstrainedBox(
child: Container(color: Colors.red, width: double.infinity, height: 100),
);
// #enddocregion Example16
}
}
//////////////////////////////////////////////////
class Example17 extends Example {
const Example17({super.key});
@override
final code = 'UnconstrainedBox(\n'
' child: LimitedBox(maxWidth: 100,\n'
' child: Container(color: Colors.red,\n'
' width: double.infinity, height: 100));';
@override
final String explanation = 'Here you won\'t get an error anymore, '
'because when the LimitedBox is given an infinite size by the UnconstrainedBox, '
'it passes a maximum width of 100 down to its child.'
'\n\n'
'If you swap the UnconstrainedBox for a Center widget, '
'the LimitedBox won\'t apply its limit anymore (since its limit is only applied when it gets infinite constraints), '
'and the width of the Container is allowed to grow past 100.'
'\n\n'
'This explains the difference between a LimitedBox and a ConstrainedBox.';
@override
Widget build(BuildContext context) {
// #docregion Example17
return UnconstrainedBox(
child: LimitedBox(
maxWidth: 100,
child: Container(
color: Colors.red,
width: double.infinity,
height: 100,
),
),
);
// #enddocregion Example17
}
}
//////////////////////////////////////////////////
class Example18 extends Example {
const Example18({super.key});
@override
final code = 'FittedBox(\n'
' child: Text(\'Some Example Text.\'));';
@override
final String explanation =
'The screen forces the FittedBox to be exactly the same size as the screen.'
'The Text has some natural width (also called its intrinsic width) that depends on the amount of text, its font size, and so on.'
'\n\n'
'The FittedBox lets the Text be any size it wants, '
'but after the Text tells its size to the FittedBox, '
'the FittedBox scales the Text until it fills all of the available width.';
@override
Widget build(BuildContext context) {
// #docregion Example18
return const FittedBox(
child: Text('Some Example Text.'),
);
// #enddocregion Example18
}
}
//////////////////////////////////////////////////
class Example19 extends Example {
const Example19({super.key});
@override
final code = 'Center(\n'
' child: FittedBox(\n'
' child: Text(\'Some Example Text.\')));';
@override
final String explanation =
'But what happens if you put the FittedBox inside of a Center widget? '
'The Center lets the FittedBox be any size it wants, up to the screen size.'
'\n\n'
'The FittedBox then sizes itself to the Text, and lets the Text be any size it wants.'
'\n\n'
'Since both FittedBox and the Text have the same size, no scaling happens.';
@override
Widget build(BuildContext context) {
// #docregion Example19
return const Center(
child: FittedBox(
child: Text('Some Example Text.'),
),
);
// #enddocregion Example19
}
}
////////////////////////////////////////////////////
class Example20 extends Example {
const Example20({super.key});
@override
final code = 'Center(\n'
' child: FittedBox(\n'
' child: Text(\'…\')));';
@override
final String explanation =
'However, what happens if FittedBox is inside of a Center widget, but the Text is too large to fit the screen?'
'\n\n'
'FittedBox tries to size itself to the Text, but it can\'t be bigger than the screen. '
'It then assumes the screen size, and resizes Text so that it fits the screen, too.';
@override
Widget build(BuildContext context) {
// #docregion Example20
return const Center(
child: FittedBox(
child: Text(
'This is some very very very large text that is too big to fit a regular screen in a single line.'),
),
);
// #enddocregion Example20
}
}
//////////////////////////////////////////////////
class Example21 extends Example {
const Example21({super.key});
@override
final code = 'Center(\n'
' child: Text(\'…\'));';
@override
final String explanation = 'If, however, you remove the FittedBox, '
'the Text gets its maximum width from the screen, '
'and breaks the line so that it fits the screen.';
@override
Widget build(BuildContext context) {
// #docregion Example21
return const Center(
child: Text(
'This is some very very very large text that is too big to fit a regular screen in a single line.'),
);
// #enddocregion Example21
}
}
//////////////////////////////////////////////////
class Example22 extends Example {
const Example22({super.key});
@override
final code = 'FittedBox(\n'
' child: Container(\n'
' height: 20, width: double.infinity));';
@override
final String explanation =
'FittedBox can only scale a widget that is BOUNDED (has non-infinite width and height).'
'Otherwise, it won\'t render anything, and you\'ll see an error in the console.';
@override
Widget build(BuildContext context) {
// #docregion Example22
return FittedBox(
child: Container(
height: 20,
width: double.infinity,
color: Colors.red,
),
);
// #enddocregion Example22
}
}
//////////////////////////////////////////////////
class Example23 extends Example {
const Example23({super.key});
@override
final code = 'Row(children:[\n'
' Container(color: red, child: Text(\'Hello!\'))\n'
' Container(color: green, child: Text(\'Goodbye!\'))]';
@override
final String explanation =
'The screen forces the Row to be exactly the same size as the screen.'
'\n\n'
'Just like an UnconstrainedBox, the Row won\'t impose any constraints onto its children, '
'and instead lets them be any size they want.'
'\n\n'
'The Row then puts them side-by-side, and any extra space remains empty.';
@override
Widget build(BuildContext context) {
// #docregion Example23
return Row(
children: [
Container(color: red, child: const Text('Hello!', style: big)),
Container(color: green, child: const Text('Goodbye!', style: big)),
],
);
// #enddocregion Example23
}
}
//////////////////////////////////////////////////
class Example24 extends Example {
const Example24({super.key});
@override
final code = 'Row(children:[\n'
' Container(color: red, child: Text(\'…\'))\n'
' Container(color: green, child: Text(\'Goodbye!\'))]';
@override
final String explanation =
'Since the Row won\'t impose any constraints onto its children, '
'it\'s quite possible that the children might be too big to fit the available width of the Row.'
'In this case, just like an UnconstrainedBox, the Row displays the "overflow warning".';
@override
Widget build(BuildContext context) {
// #docregion Example24
return Row(
children: [
Container(
color: red,
child: const Text(
'This is a very long text that '
'won\'t fit the line.',
style: big,
),
),
Container(color: green, child: const Text('Goodbye!', style: big)),
],
);
// #enddocregion Example24
}
}
//////////////////////////////////////////////////
class Example25 extends Example {
const Example25({super.key});
@override
final code = 'Row(children:[\n'
' Expanded(\n'
' child: Container(color: red, child: Text(\'…\')))\n'
' Container(color: green, child: Text(\'Goodbye!\'))]';
@override
final String explanation =
'When a Row\'s child is wrapped in an Expanded widget, the Row won\'t let this child define its own width anymore.'
'\n\n'
'Instead, it defines the Expanded width according to the other children, and only then the Expanded widget forces the original child to have the Expanded\'s width.'
'\n\n'
'In other words, once you use Expanded, the original child\'s width becomes irrelevant, and is ignored.';
@override
Widget build(BuildContext context) {
// #docregion Example25
return Row(
children: [
Expanded(
child: Center(
child: Container(
color: red,
child: const Text(
'This is a very long text that won\'t fit the line.',
style: big,
),
),
),
),
Container(color: green, child: const Text('Goodbye!', style: big)),
],
);
// #enddocregion Example25
}
}
//////////////////////////////////////////////////
class Example26 extends Example {
const Example26({super.key});
@override
final code = 'Row(children:[\n'
' Expanded(\n'
' child: Container(color: red, child: Text(\'…\')))\n'
' Expanded(\n'
' child: Container(color: green, child: Text(\'Goodbye!\'))]';
@override
final String explanation =
'If all of Row\'s children are wrapped in Expanded widgets, each Expanded has a size proportional to its flex parameter, '
'and only then each Expanded widget forces its child to have the Expanded\'s width.'
'\n\n'
'In other words, Expanded ignores the preferred width of its children.';
@override
Widget build(BuildContext context) {
// #docregion Example26
return Row(
children: [
Expanded(
child: Container(
color: red,
child: const Text(
'This is a very long text that won\'t fit the line.',
style: big,
),
),
),
Expanded(
child: Container(
color: green,
child: const Text(
'Goodbye!',
style: big,
),
),
),
],
);
// #enddocregion Example26
}
}
//////////////////////////////////////////////////
class Example27 extends Example {
const Example27({super.key});
@override
final code = 'Row(children:[\n'
' Flexible(\n'
' child: Container(color: red, child: Text(\'…\')))\n'
' Flexible(\n'
' child: Container(color: green, child: Text(\'Goodbye!\'))]';
@override
final String explanation =
'The only difference if you use Flexible instead of Expanded, '
'is that Flexible lets its child be SMALLER than the Flexible width, '
'while Expanded forces its child to have the same width of the Expanded.'
'\n\n'
'But both Expanded and Flexible ignore their children\'s width when sizing themselves.'
'\n\n'
'This means that it\'s IMPOSSIBLE to expand Row children proportionally to their sizes. '
'The Row either uses the exact child\'s width, or ignores it completely when you use Expanded or Flexible.';
@override
Widget build(BuildContext context) {
// #docregion Example27
return Row(
children: [
Flexible(
child: Container(
color: red,
child: const Text(
'This is a very long text that won\'t fit the line.',
style: big,
),
),
),
Flexible(
child: Container(
color: green,
child: const Text(
'Goodbye!',
style: big,
),
),
),
],
);
// #enddocregion Example27
}
}
//////////////////////////////////////////////////
class Example28 extends Example {
const Example28({super.key});
@override
final code = 'Scaffold(\n'
' body: Container(color: blue,\n'
' child: Column(\n'
' children: [\n'
' Text(\'Hello!\'),\n'
' Text(\'Goodbye!\')])))';
@override
final String explanation =
'The screen forces the Scaffold to be exactly the same size as the screen, '
'so the Scaffold fills the screen.'
'\n\n'
'The Scaffold tells the Container that it can be any size it wants, but not bigger than the screen.'
'\n\n'
'When a widget tells its child that it can be smaller than a certain size, '
'we say the widget supplies "loose" constraints to its child. More on that later.';
@override
Widget build(BuildContext context) {
// #docregion Example28
return Scaffold(
body: Container(
color: blue,
child: const Column(
children: [
Text('Hello!'),
Text('Goodbye!'),
],
),
),
);
// #enddocregion Example28
}
}
//////////////////////////////////////////////////
class Example29 extends Example {
const Example29({super.key});
@override
final code = 'Scaffold(\n'
' body: Container(color: blue,\n'
' child: SizedBox.expand(\n'
' child: Column(\n'
' children: [\n'
' Text(\'Hello!\'),\n'
' Text(\'Goodbye!\')]))))';
@override
final String explanation =
'If you want the Scaffold\'s child to be exactly the same size as the Scaffold itself, '
'you can wrap its child with SizedBox.expand.'
'\n\n'
'When a widget tells its child that it must be of a certain size, '
'we say the widget supplies "tight" constraints to its child. More on that later.';
@override
Widget build(BuildContext context) {
// #docregion Example29
return Scaffold(
body: SizedBox.expand(
child: Container(
color: blue,
child: const Column(
children: [
Text('Hello!'),
Text('Goodbye!'),
],
),
),
),
);
// #enddocregion Example29
}
}
//////////////////////////////////////////////////
| website/examples/layout/constraints/lib/main.dart/0 | {
"file_path": "website/examples/layout/constraints/lib/main.dart",
"repo_id": "website",
"token_count": 13878
} | 1,217 |
name: gallery
description: >-
Legacy examples referenced in "Layouts in Flutter":
https://docs.flutter.dev/ui/layout.
version: 1.0.0
environment:
sdk: ^3.2.0
dependencies:
animations: ^2.0.11
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../example_utils
flutter:
uses-material-design: true
assets:
- assets/demos/bottom_navigation_background.png
- assets/places/india_chennai_flower_market.png
- assets/places/india_thanjavur_market.png
- assets/places/india_tanjore_bronze_works.png
- assets/places/india_tanjore_market_merchant.png
- assets/places/india_tanjore_thanjavur_temple.png
- assets/places/india_pondicherry_salt_farm.png
- assets/places/india_chennai_highway.png
- assets/places/india_chettinad_silk_maker.png
- assets/places/india_tanjore_thanjavur_temple_carvings.png
- assets/places/india_chettinad_produce.png
- assets/places/india_tanjore_market_technology.png
- assets/places/india_pondicherry_beach.png
- assets/places/india_pondicherry_fisherman.png
| website/examples/layout/gallery/pubspec.yaml/0 | {
"file_path": "website/examples/layout/gallery/pubspec.yaml",
"repo_id": "website",
"token_count": 439
} | 1,218 |
import 'package:flutter/material.dart';
import 'common.dart';
class CallbackPasser extends StatelessWidget {
const CallbackPasser({super.key});
// #docregion methods
@override
Widget build(BuildContext context) {
return SomeWidget(
// Construct the widget, passing it a reference to the method above.
MyListItem(myTapCallback),
);
}
void myTapCallback(Item item) {
print('user tapped on $item');
}
// #enddocregion methods
}
class Item {
// Empty.
}
class MyHomepage extends StatelessWidget {
const MyHomepage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: const CallbackPasser(),
);
}
}
class MyListItem extends StatelessWidget {
MyListItem(this.callback, {super.key});
final void Function(Item) callback;
final Item item = Item();
@override
Widget build(BuildContext context) {
return Row(
children: [
const Text('Item!'),
TextButton(
onPressed: () => callback(item),
child: const Text('Add'),
),
],
);
}
}
| website/examples/state_mgmt/simple/lib/src/passing_callbacks.dart/0 | {
"file_path": "website/examples/state_mgmt/simple/lib/src/passing_callbacks.dart",
"repo_id": "website",
"token_count": 412
} | 1,219 |
name: native_debugging
description: Demonstration of native code debugging
sdk: ^3.3.0
version: 1.0.0+1
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
url_launcher: ^6.2.4
dev_dependencies:
example_utils:
path: ../../example_utils
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/testing/native_debugging/pubspec.yaml/0 | {
"file_path": "website/examples/testing/native_debugging/pubspec.yaml",
"repo_id": "website",
"token_count": 153
} | 1,220 |
import 'package:flutter/material.dart';
import 'global/device_type.dart';
class AppModel with ChangeNotifier {
bool getDefaultTouchMode() => DeviceType.isMobile;
// Main menu, selected page
int _selectedIndex = 0;
int get selectedIndex => _selectedIndex;
set selectedIndex(int value) => notify(() => _selectedIndex = value);
// Touch mode, determines density of views
late bool _touchMode = getDefaultTouchMode();
bool get touchMode => _touchMode;
set touchMode(bool value) => notify(() => _touchMode = value);
void toggleTouchMode() => touchMode = !touchMode;
// Indicates whether a user is logged in or not
bool _isLoggedIn = false;
bool get isLoggedIn => _isLoggedIn;
set isLoggedIn(bool value) {
if (value == false) {
reset();
}
notify(() => _isLoggedIn = value);
}
void login() => notify(() => _isLoggedIn = true);
void logout() {
_selectedIndex = 0;
notify(() => _isLoggedIn = false);
}
void reset() {
_selectedIndex = 0;
_touchMode = getDefaultTouchMode();
}
// Helper method for single-line state changes
void notify(VoidCallback stateChange) {
stateChange.call();
notifyListeners();
}
}
| website/examples/ui/layout/adaptive_app_demos/lib/app_model.dart/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/lib/app_model.dart",
"repo_id": "website",
"token_count": 394
} | 1,221 |
name: adaptive_app_demos
description: Demo code for adaptive app development techniques.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
bitsdojo_window: ^0.1.6
flextras: ^1.0.0
provider: ^6.1.1
universal_platform: ^1.0.0
platform: ^3.1.4
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/ui/layout/adaptive_app_demos/pubspec.yaml/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/pubspec.yaml",
"repo_id": "website",
"token_count": 179
} | 1,222 |
import 'package:flutter/scheduler.dart';
void setSlowAnimations() {
timeDilation = 5.0;
}
| website/examples/visual_debugging/lib/slow_animations.dart/0 | {
"file_path": "website/examples/visual_debugging/lib/slow_animations.dart",
"repo_id": "website",
"token_count": 36
} | 1,223 |
- title: Get started
children:
- title: Install Flutter
permalink: /get-started/install
- title: Test drive
permalink: /get-started/test-drive
- title: Write your first app
permalink: /get-started/codelab
- title: Learn more
permalink: /get-started/learn-more
- divider
- title: From another platform?
children:
- title: Flutter for Android devs
permalink: /get-started/flutter-for/android-devs
- title: Flutter for SwiftUI devs
permalink: /get-started/flutter-for/swiftui-devs
- title: Flutter for UIKit devs
permalink: /get-started/flutter-for/uikit-devs
- title: Flutter for React Native devs
permalink: /get-started/flutter-for/react-native-devs
- title: Flutter for web devs
permalink: /get-started/flutter-for/web-devs
- title: Flutter for Xamarin.Forms devs
permalink: /get-started/flutter-for/xamarin-forms-devs
- divider
- title: Introduction to declarative UI
permalink: /get-started/flutter-for/declarative
- title: Flutter versus Swift concurrency
permalink: /get-started/flutter-for/dart-swift-concurrency
- title: "Dart language overview"
permalink: https://dart.dev/overview
- title: Stay up to date
permalink: /release
children:
- title: Upgrade
permalink: /release/upgrade
- title: SDK archive
permalink: /release/archive
- divider
- title: What's new
permalink: /release/whats-new
- title: Release notes
permalink: /release/release-notes
- title: Breaking changes
permalink: /release/breaking-changes
- title: Compatibility policy
permalink: /release/compatibility-policy
- title: Codelabs & samples
children:
- title: Codelabs
permalink: /codelabs
- title: Cookbook
permalink: /cookbook
- title: Samples and demos
permalink: https://flutter.github.io/samples/
- title: App solutions
children:
- title: Games
children:
- title: Overview
permalink: /resources/games-toolkit
- title: Add achievements and leaderboards
permalink: /cookbook/games/achievements-leaderboard
- title: Add advertising
permalink: /cookbook/plugins/google-mobile-ads
- title: Add multiplayer support
permalink: /cookbook/games/firestore-multiplayer
- title: Add in-app purchases
permalink: https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#0
- title: Add user authentication
permalink: https://firebase.google.com/codelabs/firebase-auth-in-flutter-apps#0
- title: Debug using Crashlytics
permalink: https://firebase.google.com/docs/crashlytics/get-started?platform=flutter
- title: News
children:
- title: Build a news app
permalink: /resources/news-toolkit
- title: Monetization
children:
- title: Overview
permalink: https://flutter.dev/monetization
- title: Add in-app purchases
permalink: https://codelabs.developers.google.com/codelabs/flutter-in-app-purchases#0
- title: Maps
children:
- title: Add maps to your app
permalink: https://developers.google.com/maps/flutter-package
- divider
- header: User interface
- title: Introduction
permalink: /ui
- title: Widget catalog
permalink: /ui/widgets
- title: Layout
permalink: /ui/layout
children:
- title: Introduction
permalink: /ui/layout
match-page-url-exactly: true
- title: Build a layout
permalink: /ui/layout/tutorial
- title: Lists & grids
permalink: /ui/layout/lists
children:
- title: Create and use lists
permalink: /cookbook/lists/basic-list
- title: Create a horizontal list
permalink: /cookbook/lists/horizontal-list
- title: Create a grid view
permalink: /cookbook/lists/grid-lists
- title: Create lists with different types of items
permalink: /cookbook/lists/mixed-list
- title: Create lists with spaced items
permalink: /cookbook/lists/spaced-items
- title: Work with long lists
permalink: /cookbook/lists/long-lists
- title: Scrolling
permalink: /ui/layout/scrolling
children:
- title: Overview
permalink: /ui/layout/scrolling
- title: Use slivers to achieve fancy scrolling
permalink: /ui/layout/scrolling/slivers
- title: Place a floating app bar above a list
permalink: /cookbook/lists/floating-app-bar
- title: Create a scrolling parallax effect
permalink: /cookbook/effects/parallax-scrolling
# TODO(parlough): Rename this to 'Responsive design'
# and add 'Adaptive design' under 'Design & theming'.
- title: Adaptive design
permalink: /ui/layout/responsive
children:
- title: Adaptive and responsive app design
permalink: /ui/layout/responsive/adaptive-responsive
- title: Build an adaptive app
permalink: /ui/layout/responsive/building-adaptive-apps
- title: Update app UI based on orientation
permalink: /cookbook/design/orientation
- title: Design & theming
permalink: /ui/design
children:
- title: Share styles with themes
permalink: /cookbook/design/themes
- title: Material design
permalink: /ui/design/material
- title: Migrate to Material 3
permalink: /release/breaking-changes/material-3-migration
- title: Text
permalink: /ui/design/text
children:
- title: Fonts & typography
permalink: /ui/design/text/typography
- title: Use a custom font
permalink: /cookbook/design/fonts
- title: Export fonts from a package
permalink: /cookbook/design/package-fonts
- title: Google Fonts package
permalink: https://pub.dev/packages/google_fonts
# Consider renaming this 'Custom drawing & graphics'
# once more docs are added
- title: Custom graphics
permalink: /ui/design/graphics
children:
- title: Use custom fragment shaders
permalink: /ui/design/graphics/fragment-shaders
- title: Interactivity
permalink: /ui/interactivity
children:
- title: Add interactivity to your app
permalink: /ui/interactivity
match-page-url-exactly: true
- title: Gestures
permalink: /ui/interactivity/gestures
children:
- title: Introduction
permalink: /ui/interactivity/gestures
match-page-url-exactly: true
- title: Handle taps
permalink: /cookbook/gestures/handling-taps
- title: Drag an object outside an app
permalink: /ui/interactivity/gestures/drag-outside
- title: Drag a UI element within an app
permalink: /cookbook/effects/drag-a-widget
- title: Add Material touch ripples
permalink: /cookbook/gestures/ripples
- title: Implement swipe to dismiss
permalink: /cookbook/gestures/dismissible
- title: Input & forms
permalink: /ui/interactivity/input
children:
- title: Create and style a text field
permalink: /cookbook/forms/text-input
- title: Retrieve the value of a text field
permalink: /cookbook/forms/retrieve-input
- title: Handle changes to a text field
permalink: /cookbook/forms/text-field-changes
- title: Manage focus in text fields
permalink: /cookbook/forms/focus
- title: Build a form with validation
permalink: /cookbook/forms/validation
- title: Display a snackbar
permalink: /cookbook/design/snackbars
- title: Implement actions & shortcuts
permalink: /ui/interactivity/actions-and-shortcuts
- title: Manage keyboard focus
permalink: /ui/interactivity/focus
- title: Assets & media
permalink: /ui/assets
children:
- title: Add assets and images
permalink: /ui/assets/assets-and-images
- title: Display images from the internet
permalink: /cookbook/images/network-image
- title: Fade in images with a placeholder
permalink: /cookbook/images/fading-in-images
- title: Play and pause a video
permalink: /cookbook/plugins/play-video
- title: Navigation & routing
permalink: /ui/navigation
children:
- title: Overview
permalink: /ui/navigation
match-page-url-exactly: true
- title: Add tabs to your app
permalink: /cookbook/design/tabs
- title: Navigate to a new screen and back
permalink: /cookbook/navigation/navigation-basics
- title: Send data to a new screen
permalink: /cookbook/navigation/passing-data
- title: Return data from a screen
permalink: /cookbook/navigation/returning-data
- title: Add a drawer to a screen
permalink: /cookbook/design/drawer
- title: Setup deep linking
permalink: /ui/navigation/deep-linking
- title: Setup app links for Android
permalink: /cookbook/navigation/set-up-app-links
- title: Setup universal links for iOS
permalink: /cookbook/navigation/set-up-universal-links
- title: Configure web URL strategies
permalink: /ui/navigation/url-strategies
- title: Animations & transitions
permalink: /ui/animations
children:
- title: Introduction
permalink: /ui/animations
match-page-url-exactly: true
- title: Tutorial
permalink: /ui/animations/tutorial
- title: Implicit animations
permalink: /ui/animations/implicit-animations
- title: Animate the properties of a container
permalink: /cookbook/animation/animated-container
- title: Fade a widget in and out
permalink: /cookbook/animation/opacity-animation
- title: Hero animations
permalink: /ui/animations/hero-animations
- title: Animate a page route transition
permalink: /cookbook/animation/page-route-animation
- title: Animate using a physic simulation
permalink: /cookbook/animation/physics-simulation
- title: Staggered animations
permalink: /ui/animations/staggered-animations
- title: Create a staggered menu animation
permalink: /cookbook/effects/staggered-menu-animation
- title: API overview
permalink: /ui/animations/overview
- title: Accessibility & internationalization
permalink: /ui/accessibility-and-internationalization
children:
- title: Accessibility
permalink: /ui/accessibility-and-internationalization/accessibility
- title: Internationalization
permalink: /ui/accessibility-and-internationalization/internationalization
- divider
- header: Beyond UI
- title: Data & backend
permalink: /data-and-backend
children:
- title: State management
permalink: /data-and-backend/state-mgmt
children:
- title: Introduction
permalink: /data-and-backend/state-mgmt/intro
- title: Think declaratively
permalink: /data-and-backend/state-mgmt/declarative
- title: Ephemeral vs app state
permalink: /data-and-backend/state-mgmt/ephemeral-vs-app
- title: Simple app state management
permalink: /data-and-backend/state-mgmt/simple
- title: Options
permalink: /data-and-backend/state-mgmt/options
- title: Networking & http
permalink: /data-and-backend/networking
children:
- title: Overview
permalink: /data-and-backend/networking
match-page-url-exactly: true
- title: Fetch data from the internet
permalink: /cookbook/networking/fetch-data
- title: Make authenticated requests
permalink: /cookbook/networking/authenticated-requests
- title: Send data to the internet
permalink: /cookbook/networking/send-data
- title: Update data over the internet
permalink: /cookbook/networking/update-data
- title: Delete data on the internet
permalink: /cookbook/networking/delete-data
- title: Communicate with WebSockets
permalink: /cookbook/networking/web-sockets
- title: Serialization
permalink: /data-and-backend/serialization
children:
- title: JSON serialization
permalink: /data-and-backend/serialization/json
- title: Parse JSON in the background
permalink: /cookbook/networking/background-parsing
- title: Persistence
permalink: /data-and-backend/persistence
children:
- title: Store key-value data on disk
permalink: /cookbook/persistence/key-value
- title: Read and write files
permalink: /cookbook/persistence/reading-writing-files
- title: Persist data with SQLite
permalink: /cookbook/persistence/sqlite
- title: Firebase
permalink: /data-and-backend/firebase
- title: Google APIs
permalink: /data-and-backend/google-apis
- title: Platform integration
permalink: /platform-integration
children:
- title: Supported platforms
permalink: /reference/supported-platforms
- title: Build desktop apps with Flutter
permalink: /platform-integration/desktop
- title: Write platform-specific code
permalink: /platform-integration/platform-channels
- title: Automatic platform adaptations
permalink: /platform-integration/platform-adaptations
- title: Android
permalink: /platform-integration/android
children:
- title: Add Android as build target
permalink: /platform-integration/android/install-android
- title: Add a splash screen
permalink: /platform-integration/android/splash-screen
- title: Bind to native code
permalink: /platform-integration/android/c-interop
- title: Host a native Android view
permalink: /platform-integration/android/platform-views
- title: Restore state on Android
permalink: /platform-integration/android/restore-state-android
- title: Target ChromeOS with Android
permalink: /platform-integration/android/chromeos
- title: iOS
permalink: /platform-integration/ios
children:
- title: Add iOS as build target
permalink: /platform-integration/ios/install-ios
- title: Leverage Apple's system libraries
permalink: /platform-integration/ios/apple-frameworks
- title: Add a launch screen
permalink: /platform-integration/ios/launch-screen
- title: Add iOS App Clip support
permalink: /platform-integration/ios/ios-app-clip
- title: Add iOS app extensions
permalink: /platform-integration/ios/app-extensions
- title: Bind to native code
permalink: /platform-integration/ios/c-interop
- title: Host a native iOS view
permalink: /platform-integration/ios/platform-views
- title: Enable debugging on iOS
permalink: /platform-integration/ios/ios-debugging
- title: Restore state on iOS
permalink: /platform-integration/ios/restore-state-ios
- title: Linux
permalink: /platform-integration/linux
children:
- title: Add Linux as build target
permalink: /platform-integration/linux/install-linux
- title: Build a Linux app
permalink: /platform-integration/linux/building
- title: macOS
permalink: /platform-integration/macos
children:
- title: Add macOS as build target
permalink: /platform-integration/macos/install-macos
- title: Build a macOS app
permalink: /platform-integration/macos/building
- title: C interop
permalink: /platform-integration/macos/c-interop
- title: Web
permalink: /platform-integration/web
children:
- title: Add web as build target
permalink: /platform-integration/web/install-web
- title: Build a web app
permalink: /platform-integration/web/building
- title: Web FAQ
permalink: /platform-integration/web/faq
- title: Web renderers
permalink: /platform-integration/web/renderers
- title: Custom app initialization
permalink: /platform-integration/web/initialization
- title: Displaying images on the web
permalink: /platform-integration/web/web-images
- title: Windows
permalink: /platform-integration/windows
children:
- title: Add Windows as build target
permalink: /platform-integration/windows/install-windows
- title: Build a Windows app
permalink: /platform-integration/windows/building
- title: Packages & plugins
permalink: /packages-and-plugins
children:
- title: Use packages & plugins
permalink: /packages-and-plugins/using-packages
- title: Develop packages & plugins
permalink: /packages-and-plugins/developing-packages
- divider
- title: Flutter Favorites
permalink: /packages-and-plugins/favorites
- title: Package repository
permalink: https://pub.dev/flutter
- title: Testing & debugging
permalink: /testing
children:
- header: Testing
- title: Testing overview
permalink: /testing/overview
match-page-url-exactly: true
- title: Unit testing
children:
- title: Introduction
permalink: /cookbook/testing/unit/introduction
- title: Mock dependencies
permalink: /cookbook/testing/unit/mocking
- title: Widget testing
children:
- title: Introduction
permalink: /cookbook/testing/widget/introduction
- title: Find widgets
permalink: /cookbook/testing/widget/finders
- title: Simulate scrolling
permalink: /cookbook/testing/widget/scrolling
- title: Simulate user interaction
permalink: /cookbook/testing/widget/tap-drag
- title: Integration testing
children:
- title: Introduction
permalink: /cookbook/testing/integration/introduction
match-page-url-exactly: true
- title: Write and run an integration test
permalink: /testing/integration-tests
- title: Profile an integration test
permalink: /cookbook/testing/integration/profiling
- title: Test a plugin
permalink: /testing/testing-plugins
- title: Handle plugin code in tests
permalink: /testing/plugins-in-tests
- header: Debugging
- title: Debugging tools
permalink: /testing/debugging
- title: Debug your app programmatically
permalink: /testing/code-debugging
- title: Use a native language debugger
permalink: /testing/native-debugging
- title: Flutter's build modes
permalink: /testing/build-modes
- title: Common Flutter errors
permalink: /testing/common-errors
- title: Handle errors
permalink: /testing/errors
match-page-url-exactly: true
- title: Report errors to a service
permalink: /cookbook/maintenance/error-reporting
- title: Performance & optimization
permalink: /perf
children:
- title: Overview
permalink: /perf
match-page-url-exactly: true
- title: Impeller
permalink: /perf/impeller
- title: Performance best practices
permalink: /perf/best-practices
- title: App size
permalink: /perf/app-size
- title: Deferred components
permalink: /perf/deferred-components
# - title: Memory
# permalink: /perf/memory
# - title: Power usage
# permalink: /perf/power
- title: Rendering performance
permalink: /perf/rendering-performance
- title: Performance profiling
permalink: /perf/ui-performance
- title: Performance profiling for web
permalink: /perf/web-performance
- title: Shader compilation jank
permalink: /perf/shader
- title: Performance metrics
permalink: /perf/metrics
- title: Concurrency and isolates
permalink: /perf/isolates
- title: Performance FAQ
permalink: /perf/faq
- title: Appendix
permalink: /perf/appendix
- title: Deployment
permalink: /deployment
children:
- title: Obfuscate Dart code
permalink: /deployment/obfuscate
- title: Create flavors of an app
permalink: /deployment/flavors
- title: Build and release an Android app
permalink: /deployment/android
- title: Build and release an iOS app
permalink: /deployment/ios
- title: Build and release a macOS app
permalink: /deployment/macos
- title: Build and release a Linux app
permalink: /deployment/linux
- title: Build and release a Windows app
permalink: /deployment/windows
- title: Build and release a web app
permalink: /deployment/web
- title: Set up continuous deployment
permalink: /deployment/cd
- title: Add to an existing app
permalink: /add-to-app
children:
- title: Introduction
permalink: /add-to-app
match-page-url-exactly: true
- title: Add to an Android app
permalink: /add-to-app/android
children:
- title: Set up Android project
permalink: /add-to-app/android/project-setup
- title: Add a single Flutter screen
permalink: /add-to-app/android/add-flutter-screen
- title: Add a Flutter Fragment
permalink: /add-to-app/android/add-flutter-fragment
- title: Add a Flutter View
permalink: /add-to-app/android/add-flutter-view
- title: Use a Flutter plugin
permalink: /add-to-app/android/plugin-setup
- title: Add to an iOS app
permalink: /add-to-app/ios
children:
- title: Set up iOS project
permalink: /add-to-app/ios/project-setup
- title: Add a single Flutter screen
permalink: /add-to-app/ios/add-flutter-screen
- title: Debug embedded Flutter module
permalink: /add-to-app/debugging
- title: Add multiple Flutter instances
permalink: /add-to-app/multiple-flutters
- title: Loading sequence and performance
permalink: /add-to-app/performance
- divider
- title: Tools & editors
permalink: /tools
children:
- title: Android Studio & IntelliJ
permalink: /tools/android-studio
- title: Visual Studio Code
permalink: /tools/vs-code
- title: DevTools
permalink: /tools/devtools
children:
- title: Overview
permalink: /tools/devtools/overview
- title: Install from Android Studio & IntelliJ
permalink: /tools/devtools/android-studio
- title: Install from VS Code
permalink: /tools/devtools/vscode
- title: Install from command line
permalink: /tools/devtools/cli
- title: Flutter inspector
permalink: /tools/devtools/inspector
- title: Performance view
permalink: /tools/devtools/performance
- title: CPU Profiler view
permalink: /tools/devtools/cpu-profiler
- title: Memory view
permalink: /tools/devtools/memory
- title: Debug console view
permalink: /tools/devtools/console
- title: Network view
permalink: /tools/devtools/network
- title: Debugger
permalink: /tools/devtools/debugger
- title: Logging view
permalink: /tools/devtools/logging
- title: App size tool
permalink: /tools/devtools/app-size
- title: DevTools extensions
permalink: /tools/devtools/extensions
- title: Release notes
permalink: /tools/devtools/release-notes
- title: SDK overview
permalink: /tools/sdk
- title: Flutter's pubspec options
permalink: /tools/pubspec
- title: Automated fixes
permalink: /tools/flutter-fix
- title: Code formatting
permalink: /tools/formatting
- title: Flutter concepts
children:
- title: Architectural overview
permalink: /resources/architectural-overview
- title: Inside Flutter
permalink: /resources/inside-flutter
- title: Understanding constraints
permalink: /ui/layout/constraints
- title: Flutter's build modes
permalink: /testing/build-modes
- title: Hot reload
permalink: /tools/hot-reload
- title: Resources
permalink: /resources
children:
- header: Learning
- title: FAQ
permalink: /resources/faq
- title: Books
permalink: /resources/books
- title: Videos
permalink: /resources/videos
- title: Courses
permalink: /resources/courses
- title: Learn Dart
permalink: /resources/bootstrap-into-dart
- header: Contributing
- title: Create useful bug reports
permalink: /resources/bug-reports
- title: Contribute to Flutter
permalink: https://github.com/flutter/flutter/blob/main/CONTRIBUTING.md
- title: Design documents
permalink: /resources/design-docs
- title: Reference
permalink: /reference
expanded: true
children:
- title: Who is Dash?
permalink: /dash
- title: Widget index
permalink: /reference/widgets
- title: API reference
permalink: https://api.flutter.dev
- title: flutter CLI reference
permalink: /reference/flutter-cli
| website/src/_data/sidenav.yml/0 | {
"file_path": "website/src/_data/sidenav.yml",
"repo_id": "website",
"token_count": 9937
} | 1,224 |
{{site.alert.note}}
This codelab uses embedded DartPads to display examples and exercises.
If you see empty boxes instead of DartPads, check out
[Troubleshooting DartPad]({{site.dart-site}}/tools/dartpad/troubleshoot).
{{site.alert.end}}
| website/src/_includes/docs/dartpad-troubleshooting.md/0 | {
"file_path": "website/src/_includes/docs/dartpad-troubleshooting.md",
"repo_id": "website",
"token_count": 80
} | 1,225 |
## Configure Android development
{% assign devos = include.devos %}
{% assign target = include.target %}
{% assign compiler = include.compiler %}
{% assign attempt-time = include.attempt %}
{% case devos %}
{% when 'Windows' -%}
{% assign terminal='PowerShell' %}
{% assign prompt='C:\>' %}
{% when "macOS" -%}
{% assign terminal='your Terminal' %}
{% assign prompt='$' %}
{% else -%}
{% assign terminal='a shell' %}
{% assign prompt='$' %}
{% endcase -%}
### Configure the Android toolchain in Android Studio
{% include docs/help-link.md location='android-studio' section='#android-setup' %}
To create Android apps with Flutter, verify that the following Android
components have been installed.
* **Android SDK Platform, API {{ site.appnow.android_sdk }}**
* **Android SDK Command-line Tools**
* **Android SDK Build-Tools**
* **Android SDK Platform-Tools**
* **Android Emulator**
If you haven't installed these, or you don't know, continue with the following procedure.
Otherwise, you can skip to the [next section][check-dev].
[check-dev]: #check-your-development-setup
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="android-studio-start" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="first-start-tab" href="#first-start" role="tab" aria-controls="first-start" aria-selected="true">First time using Android Studio</a>
</li>
<li class="nav-item">
<a class="nav-link" id="later-start-tab" href="#later-start" role="tab" aria-controls="later-start" aria-selected="false">Current Android Studio User</a>
</li>
</ul>
{% comment %} Tab panes {% endcomment -%}
<div class="tab-content">
<div class="tab-pane active"
id="first-start"
role="tabpanel"
aria-labelledby="first-start-tab"
markdown="1">
1. Launch **Android Studio**.
The **Welcome to Android Studio** dialog displays.
1. Follow the **Android Studio Setup Wizard**.
1. Install the following components:
* **Android SDK Platform, API {{ site.appnow.android_sdk }}**
* **Android SDK Command-line Tools**
* **Android SDK Build-Tools**
* **Android SDK Platform-Tools**
* **Android Emulator**
</div>
<div class="tab-pane"
id="later-start"
role="tabpanel"
aria-labelledby="later-start-tab"
markdown="1">
1. Launch **Android Studio**.
1. Go to the **Settings** dialog to view the **SDK Manager**.
1. If you have a project open,
go to **Tools** <span aria-label="and then">></span> **SDK Manager**.
1. If the **Welcome to Android Studio** dialog displays,
click the **More Options** icon that follows the **Open** button
and click **SDK Manager** from the dropdown menu.
1. Click **SDK Platforms**.
1. Verify that **Android API {{ site.appnow.android_sdk }}** has been selected.
If the **Status** column displays **Update available** or **Not installed**:
{:type="a"}
1. Select **Android API {{ site.appnow.android_sdk }}**.
1. Click **Apply**.
1. When the **Confirm Change** dialog displays, click **OK**.
The **SDK Quickfix Installation** dialog displays with a
completion meter.
1. When the install finishes, click **Finish**.
After you installed the latest SDK,
the **Status** column might display **Update available**.
This means some additional system images might not be installed.
You can ignore this and continue.
1. Click **SDK Tools**.
1. Verify that the following SDK Tools have been selected:
* **Android SDK Command-line Tools**
* **Android SDK Build-Tools**
* **Android SDK Platform-Tools**
* **Android Emulator**
1. If the **Status** column for any of the preceding tools displays
**Update available** or **Not installed**:
{:type="a"}
1. Select the needed tools.
1. Click **Apply**.
1. When the **Confirm Change** dialog displays, click **OK**.
The **SDK Quickfix Installation** dialog displays with a
completion meter.
1. When the install finishes, click **Finish**.
</div>
</div>
{% comment %} End: Tab panes. {% endcomment -%}
### Configure your target Android device
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="android-devices-vp" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="virtual-tab" href="#virtual" role="tab" aria-controls="virtual" aria-selected="true">Virtual Device</a>
</li>
<li class="nav-item">
<a class="nav-link" id="physical-tab" href="#physical" role="tab" aria-controls="physical" aria-selected="false">Physical Device</a>
</li>
</ul>
{% comment %} Tab panes {% endcomment -%}
<div class="tab-content">
<div class="tab-pane active" id="virtual" role="tabpanel" aria-labelledby="virtual-tab" markdown="1">
{% include docs/install/devices/android-emulator.md devos=devos %}
</div>
<div class="tab-pane" id="physical" role="tabpanel" aria-labelledby="physical-tab" markdown="1">
{% include docs/install/devices/android-physical.md devos=devos %}
</div>
</div>
{% comment %} End: Tab panes. {% endcomment -%}
{% if attempt-time == 'first' %}
### Agree to Android licenses
{% include docs/help-link.md location='android-licenses' section='#android-setup' %}
Before you can use Flutter and after you install all prerequisites,
agree to the licenses of the Android SDK platform.
1. Open an elevated console window.
1. Run the following command to enable signing licenses.
```terminal
{{prompt}} flutter doctor --android-licenses
```
If you accepted the Android Studio licenses at another time,
this command returns:
```terminal
[========================================] 100% Computing updates...
All SDK package licenses accepted.
```
You can skip the next step.
1. Before agreeing to the terms of each license,
read each with care.
#### Troubleshooting licensing issues
<details markdown="1">
<summary>How to fix the error of finding Java install</summary>
You might have an issue with the Android SDK locating the Java SDK.
```terminal
$ flutter doctor --android-licenses
ERROR: JAVA_HOME is set to an invalid directory: /Applications/Android\ Studio.app/Contents/jre/Contents/Home
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
Android sdkmanager tool was found, but failed to run
(/Users/atsansone/Library/Android/sdk/cmdline-tools/latest/bin/sdkmanager): "exited code 1".
Try re-installing or updating your Android SDK,
visit https://flutter.dev/docs/get-started/install/macos#android-setup for detailed instructions.
```
The `flutter doctor` command returns this error because of how the `JAVA_HOME`
variable was set. When you add the path to `JAVA_HOME`, you can add a backslash
to the space between `Android` and `Studio` or enclose the entire path in
matching quotes. You cannot do _both_.
Look for your `JAVA_HOME` path in your appropriate shell resource file.
Change it from:
```conf
export JAVA_HOME="/Applications/Android\ Studio.app/Contents/jre/Contents/Home"
```
to:
```conf
export JAVA_HOME="/Applications/Android Studio.app/Contents/jre/Contents/Home"
```
Do not include the backslash between `Android` and `Studio`.
To load this updated environment variable, reload your shell.
This example uses the `zsh` resource file.
```terminal
source ~/.zshrc
```
</details>
{% endif %}
| website/src/_includes/docs/install/compiler/android.md/0 | {
"file_path": "website/src/_includes/docs/install/compiler/android.md",
"repo_id": "website",
"token_count": 2416
} | 1,226 |
{% assign terminal=include.terminal %}
{% assign target = include.target %}
{% assign dir = include.dir %}
### Add Flutter to your `PATH`
{:.no_toc}
To run Flutter commands in {{terminal}},
add Flutter to the `PATH` environment variable.
1. Check which shell starts when you open a new console window.
This would be your _default shell_.
```terminal
$ echo $SHELL
```
This differs from another command that tells you which shell runs
in your current console.
```terminal
$ echo $0
```
1. To add Flutter to your `PATH`, expand the entry for your default shell, then
choose the command.
{% assign shells = site.data.shells %}
{% for shell in shells %}
<details markdown="1" {% if shell.name == 'bash' %}open{% endif %}>
<summary>Show <tt>{{shell.name}}</tt> command</summary>
```terminal
$ {{shell.set-path}}
```
</details>
{% endfor %}
1. To apply this change, restart all open terminal sessions.
| website/src/_includes/docs/install/reqs/linux/set-path.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/linux/set-path.md",
"repo_id": "website",
"token_count": 322
} | 1,227 |
{% comment %}
Include parameters:
- toc_content: The HTML toc content
- class: CSS classes to add to toc element.
- header: header text, default 'Contents'
If you don't want the back-to-top button style `site-toc__back-to-top` as `display: none`.
{% endcomment -%}
{% assign toc = include.toc_content -%}
{% comment %}
A TOC without <li> elements is empty. Only generate a TOC <div> for non-empty TOCs.
{% endcomment -%}
{% if toc contains "<li" -%}
{% assign toc = toc | replace: 'id="toc" ', '' %}
<div
id="site-toc--inline"
class="site-toc site-toc--inline {{include.class}}"
>
<header class="site-toc__title">
{{include.header | default: 'Contents'}}
</header>
{{ toc }}
</div>
{% endif -%}
| website/src/_includes/inline-toc.html/0 | {
"file_path": "website/src/_includes/inline-toc.html",
"repo_id": "website",
"token_count": 283
} | 1,228 |
# Generates and stores active entry data for paths
# based on the data declared in `_data/sidenav.yml`.
# This stored active entry data is used in `active_nav_for_page`
# and the `active_nav_for_page` filter it declares to
# determine which entries to indicate as active in the sidenav
# on each page.
module ActiveNavGenerator
class ActiveNavGenerator < Jekyll::Generator
def generate(site)
# @param [Hash] result The subset of the the map to store activenav data for this part
# @param [Array<Integer>] path The path of indices leading to this entry's part of sidenav
# @param [Array<String>] parts The parts of this entry's permalink split by `/`
# @param [Integer] index The index of the part of the path being added
# @param [Boolean] match_path_exactly If this entry shouldn't allow children of its permalink to match
def add_part(result, path, parts, index, match_path_exactly: false)
is_last = index == parts.length - 1
current = result[parts[index]]
if current.nil?
# If the current part isn't in the results map yet, add a new hash.
current = {}
result[parts[index]] = current
end
# If this is the last part of the path,
# store the activenav data.
if is_last
active = current['active']
# Only override activenav data if
# it doesn't already exist for this part.
if active.nil? or match_path_exactly
current['active'] = path
if match_path_exactly
current['allow-children'] = false
end
end
else
unless current.key?('paths')
current['paths'] = {}
end
# Continue to the next part
add_part(current['paths'], path, parts, index + 1, match_path_exactly: match_path_exactly)
end
end
# @param [Hash] results The map where to store resulting activenav data
# @param [String] permalink The permalink to add the activenav data map
# @param [Array<Integer>] path The indices of parents in the sidenav
# @param [Boolean] match_path_exactly If this entry shouldn't allow children of its permalink to match
def add_link(results, permalink, path, match_path_exactly: false)
# Skip external links.
return if permalink.start_with? 'http'
# Throw an error if a permalink does not start with a `/`.
raise "#{permalink} does not begin with a '/'" unless permalink.start_with? '/'
# Split the specified permalink into parts.
parts = permalink.split('/')
# Add activenav data for the specified permalink
add_part(results, path, parts, 1, match_path_exactly: match_path_exactly)
end
# @param [Hash] results The map where to store activenav data
# @param [Hash] nav_tree The sidenav data or a collection of children entries
# @param [Array<int>] path The indices of parents in the sidenav
def visit_permalinks(results, nav_tree, path)
# Visit each entry in the sidenav/children
nav_tree.each_with_index do |entry, i|
permalink = entry['permalink']
new_path = path + [i + 1]
# Only consider paths which actually have a permalink,
# skipping headers, dividers, etc.
if permalink.is_a? String
add_link(results, permalink, new_path,
match_path_exactly: entry['match-page-url-exactly'] == true)
end
# If the current sidenav entry has children,
# visit those to build their activenav data.
children = entry['children']
if children.is_a? Array
visit_permalinks(results, children, new_path)
end
end
end
sidenav = site.data['sidenav']
new_sidenav_hash = sidenav.hash
# Only regenerate activenav data if the sidenav has changed.
# If it hasn't changed, use the cached activenav results:
unless (defined?(@last_sidenav_hash)).nil? or @last_sidenav_hash != new_sidenav_hash
site.data['activenav'] = @last_activenav_results
return
end
# If last_sidenav_hash is nil, it means this will be
# the first time generating active nav data.
first_generation = @last_sidenav_hash.nil?
@last_sidenav_hash = new_sidenav_hash
results = {}
visit_permalinks(results, site.data['sidenav'], [])
@last_activenav_results = results
site.data['activenav'] = results
# If this isn't the first time generating activenav data,
# mark each page for regeneration since
# the sidenav needs to be regenerated.
unless first_generation
puts(' Regenerating with new sidenav data!')
site.regenerator.clear
end
end
end
end
| website/src/_plugins/active_nav_generator.rb/0 | {
"file_path": "website/src/_plugins/active_nav_generator.rb",
"repo_id": "website",
"token_count": 1912
} | 1,229 |
@use 'variables' as *;
@use '../vendor/bootstrap';
body {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
overflow-x: hidden;
}
.container main {
overflow-x: hidden;
}
h1 {
margin-bottom: bootstrap.bs-spacer(12);
}
h2 {
margin: bootstrap.bs-spacer(12) 0 bootstrap.bs-spacer(8);
clear: both;
}
h3 {
margin: bootstrap.bs-spacer(8) 0 bootstrap.bs-spacer(4);
}
dd {
margin-bottom: .75rem;
}
.card-deck.card-deck--responsive {
.card {
flex: 0 0 calc((100% / 3) - #{bootstrap.bs-spacer(4)});
margin-bottom: bootstrap.bs-spacer(4);
}
}
.card-footer.card-footer--transparent {
border: none;
background-color: transparent;
}
.card-footer.card-footer--links {
> *:not(:last-child) {
margin-right: bootstrap.bs-spacer(4);
}
}
.card-image-holder {
align-items: center;
display: flex;
height: 200px;
justify-content: center;
img {
height: auto;
max-width: 100%;
max-height: 100%;
width: auto;
}
svg {
height: 100%;
width: 100%;
}
}
.card-title-material-3 {
color: $site-color-body;
}
.d-block.h1 > .material-symbols {
font-size: 3rem;
}
.card-image-holder-material-3 {
align-items: center;
z-index: -1;
background-size: 0;
opacity: .999;
background-color: var(--bg-color, white);
img {
max-width: 100%;
max-height: 100%;
width: auto;
z-index: 1;
}
}
.card-image-material-3-hover {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
opacity: 0;
transition: .25s ease;
z-index: -1;
img {
max-width: 100%;
max-height: 100%;
width: auto;
z-index: -1;
}
}
.card-image-holder-material-3:hover .card-image-material-3-hover {
opacity: 1;
}
.card-app-type {
border-color: $site-color-nav-links;
}
.fixed-col {
@include bootstrap.media-breakpoint-up(md) {
bottom: 0;
overflow-y: auto;
position: absolute; // position will be fixed once js has initialized
top: 0;
}
}
.material-symbols {
font-family: $site-font-family-icon;
font-variation-settings:
'FILL' 0,
'wght' 400,
'GRAD' 0,
'opsz' 24;
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
vertical-align: middle;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-webkit-font-feature-settings: 'liga';
-webkit-font-smoothing: antialiased;
}
.site-mobile-screenshot {
display: block;
margin: 0 auto;
max-height: none;
max-width: 100%;
@include bootstrap.media-breakpoint-up(xs) {
max-width: bootstrap.breakpoint-min(xxs);
}
&--border { border: 1px solid $site-color-light-grey; }
}
.site-image-right {
display: block;
margin: 0 auto;
max-height: 60vh;
max-width: 100%;
&.site-figure {
max-height: none;
}
@include bootstrap.media-breakpoint-up(md) {
float: right;
margin: 0 0 bootstrap.bs-spacer(10) bootstrap.bs-spacer(10);
max-height: none;
max-width: calc((100%/2.5) - #{bootstrap.bs-spacer(10)});
}
}
.site-figure {
display: flex;
justify-content: center;
.site-figure-container {
flex: 0 1 auto;
max-width: 100%;
img { width: 100%; }
figcaption {
margin-top: bootstrap.bs-spacer(4);
text-align: center;
}
}
.site-figure-container-lg {
flex: 0 1 auto;
width: 100%;
img { width: 100%; }
figcaption {
margin-top: bootstrap.bs-spacer(4);
text-align: center;
}
}
}
.site-illustration {
// Illustrations should be visible in their entirety without the need
// for scrolling up and down.
max-height: 60vh;
}
.btn.btn-icon {
align-items: center;
display: flex;
justify-content: center;
.material-symbols {
margin-right: bootstrap.bs-spacer(2);
}
}
.btn.btn-cta {
font-size: 18px;
font-weight: 500;
padding: bootstrap.bs-spacer(4) bootstrap.bs-spacer(6);
@include bootstrap.media-breakpoint-up(sm) {
min-width: 250px;
}
}
.embedded-video-wrapper {
width: 100%;
padding-bottom: 56.25%; // 16:9 aspect ratio
position: relative;
&__frame {
height: 100%;
position: absolute;
width: 100%;
}
}
.table-wrapper {
overflow-x: auto;
}
// If table head has empty children, just hide it
// since markdown-it-table doesn't support headless tables.
thead:has(th:empty) {
display: none;
}
.searchbar {
> * {
max-width: 640px;
width:100%
}
}
.install-help {
text-align: right;
margin-top: -2.5rem;
a {
display: inline-flex;
align-items: center;
&:hover {
text-decoration: none;
}
}
.material-symbols {
font-size: 20px;
margin-right: 0.125rem;
}
}
blockquote {
background-color: $site-color-codeblock-bg;
padding: bootstrap.bs-spacer(3) bootstrap.bs-spacer(4);
border-left: solid 5px bootstrap.$border-color;
margin-bottom: bootstrap.bs-spacer(4);
p {
margin-bottom: 0;
}
}
summary {
margin-bottom: 1rem;
}
main {
ol + img, ul + img, ol + p, ul + p, p + p + img,
li:not(.toc-entry, .breadcrumb-item):last-child, ul + p:last-child {
margin-bottom: 1rem;
}
}
td ol, td ul, td dl, td p {
margin-bottom: 0;
}
p + ul, p + ol, p + dl {
margin-top: .5rem;
margin-bottom: .5rem;
}
li.breadcrumb-item:last-child {
margin-bottom: 0;
}
td ol, td ul, td dl, td p {
margin-bottom: 0;
}
.figure-caption {
font-size: bootstrap.$font-size-sm;
font-style: italic;
color: #041E3C;
}
aside {
.alert {
h2, h3, h4, h5, h6 {
margin: 0.5rem 0;
font-size: 1.5rem;
}
}
}
.card-os-bug {
position: relative;
::before {
content: "";
position: absolute;
top: 0.5rem;
left: 0.5rem;
width: 24px;
height: 24px;
background-position: center center;
background-size: contain;
background-color: transparent;
background-repeat: no-repeat;
z-index: 1; /* Place in front of card */
}
}
.card-macos {
@extend .card-os-bug;
::before {
background-image: url("/assets/images/docs/brand-svg/macos-bug.svg");
}
}
.card-windows {
@extend .card-os-bug;
::before {
background-image: url("/assets/images/docs/brand-svg/windows-bug.svg");
}
}
.card-linux {
@extend .card-os-bug;
::before {
background-image: url("/assets/images/docs/brand-svg/linux.svg");
}
}
.card-chromeos {
@extend .card-os-bug;
::before {
background-image: url("/assets/images/docs/brand-svg/chromeos.svg");
}
}
| website/src/_sass/base/_base.scss/0 | {
"file_path": "website/src/_sass/base/_base.scss",
"repo_id": "website",
"token_count": 2822
} | 1,230 |
@use '../base/variables' as *;
@use '../vendor/bootstrap';
.snackbar {
align-items: center;
bottom: $site-snackbar-padding;
display: flex;
justify-content: center;
left: $site-snackbar-padding;
position: fixed;
right: $site-snackbar-padding;
z-index: bootstrap.$zindex-popover;
&__container {
align-items: center;
background-color: #323232;
color: $site-color-white;
display: inline-flex;
justify-content: space-between;
padding: bootstrap.bs-spacer(2) bootstrap.bs-spacer(4);
}
&__action {
margin-left: bootstrap.bs-spacer(4);
position: relative;
top: 1px;
}
}
| website/src/_sass/components/_snackbar.scss/0 | {
"file_path": "website/src/_sass/components/_snackbar.scss",
"repo_id": "website",
"token_count": 251
} | 1,231 |
---
title: Add a Flutter screen to an iOS app
short-title: Add a Flutter screen
description: Learn how to add a single Flutter screen to your existing iOS app.
---
This guide describes how to add a single Flutter screen to an existing iOS app.
## Start a FlutterEngine and FlutterViewController
To launch a Flutter screen from an existing iOS, you start a
[`FlutterEngine`][] and a [`FlutterViewController`][].
{{site.alert.secondary}}
The `FlutterEngine` serves as a host to the Dart VM and your Flutter runtime,
and the `FlutterViewController` attaches to a `FlutterEngine` to pass
input events into Flutter and to display frames rendered by the
`FlutterEngine`.
{{site.alert.end}}
The `FlutterEngine` might have the same lifespan as your
`FlutterViewController` or outlive your `FlutterViewController`.
{{site.alert.tip}}
It's generally recommended to pre-warm a long-lived
`FlutterEngine` for your application because:
* The first frame appears faster when showing the `FlutterViewController`.
* Your Flutter and Dart state will outlive one `FlutterViewController`.
* Your application and your plugins can interact with Flutter and your Dart
logic before showing the UI.
{{site.alert.end}}
See [Loading sequence and performance][]
for more analysis on the latency and memory
trade-offs of pre-warming an engine.
### Create a FlutterEngine
Where you create a `FlutterEngine` depends on your host app.
{% samplecode engine %}
{% sample SwiftUI %}
In this example, we create a `FlutterEngine` object inside a SwiftUI `ObservableObject`.
We then pass this `FlutterEngine` into a `ContentView` using the
`environmentObject()` property.
<?code-excerpt title="MyApp.swift"?>
```swift
import SwiftUI
import Flutter
// The following library connects plugins with iOS platform code to this app.
import FlutterPluginRegistrant
class FlutterDependencies: ObservableObject {
let flutterEngine = FlutterEngine(name: "my flutter engine")
init(){
// Runs the default Dart entrypoint with a default Flutter route.
flutterEngine.run()
// Connects plugins with iOS platform code to this app.
GeneratedPluginRegistrant.register(with: self.flutterEngine);
}
}
@main
struct MyApp: App {
// flutterDependencies will be injected using EnvironmentObject.
@StateObject var flutterDependencies = FlutterDependencies()
var body: some Scene {
WindowGroup {
ContentView().environmentObject(flutterDependencies)
}
}
}
```
{% sample UIKit-Swift %}
As an example, we demonstrate creating a
`FlutterEngine`, exposed as a property, on app startup in
the app delegate.
<?code-excerpt title="AppDelegate.swift"?>
```swift
import UIKit
import Flutter
// The following library connects plugins with iOS platform code to this app.
import FlutterPluginRegistrant
@UIApplicationMain
class AppDelegate: FlutterAppDelegate { // More on the FlutterAppDelegate.
lazy var flutterEngine = FlutterEngine(name: "my flutter engine")
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Runs the default Dart entrypoint with a default Flutter route.
flutterEngine.run();
// Connects plugins with iOS platform code to this app.
GeneratedPluginRegistrant.register(with: self.flutterEngine);
return super.application(application, didFinishLaunchingWithOptions: launchOptions);
}
}
```
{% sample UIKit-ObjC %}
In this example, we create a `FlutterEngine`
object inside a SwiftUI `ObservableObject`.
We then pass this `FlutterEngine` into a
`ContentView` using the `environmentObject()` property.
<?code-excerpt title="AppDelegate.h"?>
```objectivec
@import UIKit;
@import Flutter;
@interface AppDelegate : FlutterAppDelegate // More on the FlutterAppDelegate below.
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@end
```
<?code-excerpt title="AppDelegate.m"?>
```objectivec
// The following library connects plugins with iOS platform code to this app.
#import <FlutterPluginRegistrant/GeneratedPluginRegistrant.h>
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"my flutter engine"];
// Runs the default Dart entrypoint with a default Flutter route.
[self.flutterEngine run];
// Connects plugins with iOS platform code to this app.
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
```
{% endsamplecode %}
### Show a FlutterViewController with your FlutterEngine
{% samplecode vc %}
{% sample SwiftUI %}
The following example shows a generic `ContentView` with a
`Button` hooked to present a [`FlutterViewController`][].
The `FlutterViewController` constructor takes the pre-warmed
`FlutterEngine` as an argument. `FlutterEngine` is passed in
as an `EnvironmentObject` via `flutterDependencies`.
<?code-excerpt title="ContentView.swift"?>
```swift
import SwiftUI
import Flutter
struct ContentView: View {
// Flutter dependencies are passed in an EnvironmentObject.
@EnvironmentObject var flutterDependencies: FlutterDependencies
// Button is created to call the showFlutter function when pressed.
var body: some View {
Button("Show Flutter!") {
showFlutter()
}
}
func showFlutter() {
// Get the RootViewController.
guard
let windowScene = UIApplication.shared.connectedScenes
.first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
let window = windowScene.windows.first(where: \.isKeyWindow),
let rootViewController = window.rootViewController
else { return }
// Create the FlutterViewController.
let flutterViewController = FlutterViewController(
engine: flutterDependencies.flutterEngine,
nibName: nil,
bundle: nil)
flutterViewController.modalPresentationStyle = .overCurrentContext
flutterViewController.isViewOpaque = false
rootViewController.present(flutterViewController, animated: true)
}
}
```
{% sample UIKit-Swift %}
The following example shows a generic `ViewController` with a
`UIButton` hooked to present a [`FlutterViewController`][].
The `FlutterViewController` uses the `FlutterEngine` instance
created in the `AppDelegate`.
<?code-excerpt title="ViewController.swift"?>
```swift
import UIKit
import Flutter
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Make a button to call the showFlutter function when pressed.
let button = UIButton(type:UIButton.ButtonType.custom)
button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside)
button.setTitle("Show Flutter!", for: UIControl.State.normal)
button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
button.backgroundColor = UIColor.blue
self.view.addSubview(button)
}
@objc func showFlutter() {
let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
let flutterViewController =
FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
present(flutterViewController, animated: true, completion: nil)
}
}
```
{% sample UIKit-ObjC %}
The following example shows a generic `ViewController` with a
`UIButton` hooked to present a [`FlutterViewController`][].
The `FlutterViewController` uses the `FlutterEngine` instance
created in the `AppDelegate`.
<?code-excerpt title="ViewController.m"?>
```objectivec
@import Flutter;
#import "AppDelegate.h"
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Make a button to call the showFlutter function when pressed.
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:@selector(showFlutter)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show Flutter!" forState:UIControlStateNormal];
button.backgroundColor = UIColor.blueColor;
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:button];
}
- (void)showFlutter {
FlutterEngine *flutterEngine =
((AppDelegate *)UIApplication.sharedApplication.delegate).flutterEngine;
FlutterViewController *flutterViewController =
[[FlutterViewController alloc] initWithEngine:flutterEngine nibName:nil bundle:nil];
[self presentViewController:flutterViewController animated:YES completion:nil];
}
@end
```
{% endsamplecode %}
Now, you have a Flutter screen embedded in your iOS app.
{{site.alert.note}}
Using the previous example, the default `main()`
entrypoint function of your default Dart library
would run when calling `run` on the
`FlutterEngine` created in the `AppDelegate`.
{{site.alert.end}}
### _Alternatively_ - Create a FlutterViewController with an implicit FlutterEngine
As an alternative to the previous example, you can let the
`FlutterViewController` implicitly create its own `FlutterEngine` without
pre-warming one ahead of time.
This is not usually recommended because creating a
`FlutterEngine` on-demand could introduce a noticeable
latency between when the `FlutterViewController` is
presented and when it renders its first frame. This could, however, be
useful if the Flutter screen is rarely shown, when there are no good
heuristics to determine when the Dart VM should be started, and when Flutter
doesn't need to persist state between view controllers.
To let the `FlutterViewController` present without an existing
`FlutterEngine`, omit the `FlutterEngine` construction, and create the
`FlutterViewController` without an engine reference.
{% samplecode no-engine-vc %}
{% sample SwiftUI %}
```swift
import SwiftUI
import Flutter
struct ContentView: View {
var body: some View {
Button("Show Flutter!") {
openFlutterApp()
}
}
func openFlutterApp() {
// Get the RootViewController.
guard
let windowScene = UIApplication.shared.connectedScenes
.first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
let window = windowScene.windows.first(where: \.isKeyWindow),
let rootViewController = window.rootViewController
else { return }
// Create the FlutterViewController without an existing FlutterEngine.
let flutterViewController = FlutterViewController(
project: nil,
nibName: nil,
bundle: nil)
flutterViewController.modalPresentationStyle = .overCurrentContext
flutterViewController.isViewOpaque = false
rootViewController.present(flutterViewController, animated: true)
}
}
```
{% sample UIKit-Swift %}
<?code-excerpt title="ViewController.swift"?>
```swift
// Existing code omitted.
func showFlutter() {
let flutterViewController = FlutterViewController(project: nil, nibName: nil, bundle: nil)
present(flutterViewController, animated: true, completion: nil)
}
```
{% sample UIKit-ObjC %}
<?code-excerpt title="ViewController.m"?>
```objectivec
// Existing code omitted.
- (void)showFlutter {
FlutterViewController *flutterViewController =
[[FlutterViewController alloc] initWithProject:nil nibName:nil bundle:nil];
[self presentViewController:flutterViewController animated:YES completion:nil];
}
@end
```
{% endsamplecode %}
See [Loading sequence and performance][]
for more explorations on latency and memory usage.
## Using the FlutterAppDelegate
Letting your application's `UIApplicationDelegate` subclass
`FlutterAppDelegate` is recommended but not required.
The `FlutterAppDelegate` performs functions such as:
* Forwarding application callbacks such as [`openURL`][]
to plugins such as [local_auth][].
* Keeping the Flutter connection open
in debug mode when the phone screen locks.
### Creating a FlutterAppDelegate subclass
Creating a subclass of the `FlutterAppDelegate` in UIKit apps was shown
in the [Start a FlutterEngine and FlutterViewController section][].
In a SwiftUI app, you can create a subclass of the
`FlutterAppDelegate` that conforms to the `ObservableObject` protocol as follows:
```swift
import SwiftUI
import Flutter
import FlutterPluginRegistrant
class AppDelegate: FlutterAppDelegate, ObservableObject {
let flutterEngine = FlutterEngine(name: "my flutter engine")
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Runs the default Dart entrypoint with a default Flutter route.
flutterEngine.run();
// Used to connect plugins (only if you have plugins with iOS platform code).
GeneratedPluginRegistrant.register(with: self.flutterEngine);
return true;
}
}
@main
struct MyApp: App {
// Use this property wrapper to tell SwiftUI
// it should use the AppDelegate class for the application delegate
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
```
Then, in your view, the `AppDelegate`is accessible as an `EnvironmentObject`.
```swift
import SwiftUI
import Flutter
struct ContentView: View {
// Access the AppDelegate using an EnvironmentObject.
@EnvironmentObject var appDelegate: AppDelegate
var body: some View {
Button("Show Flutter!") {
openFlutterApp()
}
}
func openFlutterApp() {
// Get the RootViewController.
guard
let windowScene = UIApplication.shared.connectedScenes
.first(where: { $0.activationState == .foregroundActive && $0 is UIWindowScene }) as? UIWindowScene,
let window = windowScene.windows.first(where: \.isKeyWindow),
let rootViewController = window.rootViewController
else { return }
// Create the FlutterViewController.
let flutterViewController = FlutterViewController(
// Access the Flutter Engine via AppDelegate.
engine: appDelegate.flutterEngine,
nibName: nil,
bundle: nil)
flutterViewController.modalPresentationStyle = .overCurrentContext
flutterViewController.isViewOpaque = false
rootViewController.present(flutterViewController, animated: true)
}
}
```
### If you can't directly make FlutterAppDelegate a subclass
If your app delegate can't directly make `FlutterAppDelegate` a subclass,
make your app delegate implement the `FlutterAppLifeCycleProvider`
protocol in order to make sure your plugins receive the necessary callbacks.
Otherwise, plugins that depend on these events might have undefined behavior.
For instance:
{% samplecode app-delegate %}
{% sample Swift %}
<?code-excerpt title="AppDelegate.swift"?>
```swift
import Foundation
import Flutter
class AppDelegate: UIResponder, UIApplicationDelegate, FlutterAppLifeCycleProvider, ObservableObject {
private let lifecycleDelegate = FlutterPluginAppLifeCycleDelegate()
let flutterEngine = FlutterEngine(name: "flutter_nps_engine")
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
flutterEngine.run()
return lifecycleDelegate.application(application, didFinishLaunchingWithOptions: launchOptions ?? [:])
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
lifecycleDelegate.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
lifecycleDelegate.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
lifecycleDelegate.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return lifecycleDelegate.application(app, open: url, options: options)
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
return lifecycleDelegate.application(application, handleOpen: url)
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return lifecycleDelegate.application(application, open: url, sourceApplication: sourceApplication ?? "", annotation: annotation)
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
lifecycleDelegate.application(application, performActionFor: shortcutItem, completionHandler: completionHandler)
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
lifecycleDelegate.application(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
lifecycleDelegate.application(application, performFetchWithCompletionHandler: completionHandler)
}
func add(_ delegate: FlutterApplicationLifeCycleDelegate) {
lifecycleDelegate.add(delegate)
}
}
```
{% sample Objective-C %}
<?code-excerpt title="AppDelegate.h"?>
```objectivec
@import Flutter;
@import UIKit;
@import FlutterPluginRegistrant;
@interface AppDelegate : UIResponder <UIApplicationDelegate, FlutterAppLifeCycleProvider>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,strong) FlutterEngine *flutterEngine;
@end
```
The implementation should delegate mostly to a
`FlutterPluginAppLifeCycleDelegate`:
<?code-excerpt title="AppDelegate.m"?>
```objectivec
@interface AppDelegate ()
@property (nonatomic, strong) FlutterPluginAppLifeCycleDelegate* lifeCycleDelegate;
@end
@implementation AppDelegate
- (instancetype)init {
if (self = [super init]) {
_lifeCycleDelegate = [[FlutterPluginAppLifeCycleDelegate alloc] init];
}
return self;
}
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id>*))launchOptions {
self.flutterEngine = [[FlutterEngine alloc] initWithName:@"io.flutter" project:nil];
[self.flutterEngine runWithEntrypoint:nil];
[GeneratedPluginRegistrant registerWithRegistry:self.flutterEngine];
return [_lifeCycleDelegate application:application didFinishLaunchingWithOptions:launchOptions];
}
// Returns the key window's rootViewController, if it's a FlutterViewController.
// Otherwise, returns nil.
- (FlutterViewController*)rootFlutterViewController {
UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
if ([viewController isKindOfClass:[FlutterViewController class]]) {
return (FlutterViewController*)viewController;
}
return nil;
}
- (void)application:(UIApplication*)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings*)notificationSettings {
[_lifeCycleDelegate application:application
didRegisterUserNotificationSettings:notificationSettings];
}
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
[_lifeCycleDelegate application:application
didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:(NSDictionary*)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
[_lifeCycleDelegate application:application
didReceiveRemoteNotification:userInfo
fetchCompletionHandler:completionHandler];
}
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options {
return [_lifeCycleDelegate application:application openURL:url options:options];
}
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url {
return [_lifeCycleDelegate application:application handleOpenURL:url];
}
- (BOOL)application:(UIApplication*)application
openURL:(NSURL*)url
sourceApplication:(NSString*)sourceApplication
annotation:(id)annotation {
return [_lifeCycleDelegate application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
- (void)application:(UIApplication*)application
performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem
completionHandler:(void (^)(BOOL succeeded))completionHandler {
[_lifeCycleDelegate application:application
performActionForShortcutItem:shortcutItem
completionHandler:completionHandler];
}
- (void)application:(UIApplication*)application
handleEventsForBackgroundURLSession:(nonnull NSString*)identifier
completionHandler:(nonnull void (^)(void))completionHandler {
[_lifeCycleDelegate application:application
handleEventsForBackgroundURLSession:identifier
completionHandler:completionHandler];
}
- (void)application:(UIApplication*)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
[_lifeCycleDelegate application:application performFetchWithCompletionHandler:completionHandler];
}
- (void)addApplicationLifeCycleDelegate:(NSObject<FlutterPlugin>*)delegate {
[_lifeCycleDelegate addDelegate:delegate];
}
@end
```
{% endsamplecode %}
## Launch options
The examples demonstrate running Flutter using the default launch settings.
In order to customize your Flutter runtime,
you can also specify the Dart entrypoint, library, and route.
### Dart entrypoint
Calling `run` on a `FlutterEngine`, by default,
runs the `main()` Dart function
of your `lib/main.dart` file.
You can also run a different entrypoint function by using
[`runWithEntrypoint`][] with an `NSString` specifying
a different Dart function.
{{site.alert.note}}
Dart entrypoint functions other than `main()`
must be annotated with the following in order to
not be [tree-shaken][] away when compiling:
```dart
@pragma('vm:entry-point')
void myOtherEntrypoint() { ... };
```
{{site.alert.end}}
### Dart library
In addition to specifying a Dart function, you can specify an entrypoint
function in a specific file.
For instance the following runs `myOtherEntrypoint()`
in `lib/other_file.dart` instead of `main()` in `lib/main.dart`:
{% samplecode entrypoint-library %}
{% sample Swift %}
```swift
flutterEngine.run(withEntrypoint: "myOtherEntrypoint", libraryURI: "other_file.dart")
```
{% sample Objective-C %}
```objectivec
[flutterEngine runWithEntrypoint:@"myOtherEntrypoint" libraryURI:@"other_file.dart"];
```
{% endsamplecode %}
### Route
Starting in Flutter version 1.22, an initial route can be set for your Flutter
[`WidgetsApp`][] when constructing the FlutterEngine or the
FlutterViewController.
{% samplecode initial-route %}
{% sample Swift %}
```swift
let flutterEngine = FlutterEngine()
// FlutterDefaultDartEntrypoint is the same as nil, which will run main().
engine.run(
withEntrypoint: "main", initialRoute: "/onboarding")
```
{% sample Objective-C %}
```objectivec
FlutterEngine *flutterEngine = [[FlutterEngine alloc] init];
// FlutterDefaultDartEntrypoint is the same as nil, which will run main().
[flutterEngine runWithEntrypoint:FlutterDefaultDartEntrypoint
initialRoute:@"/onboarding"];
```
{% endsamplecode %}
This code sets your `dart:ui`'s [`window.defaultRouteName`][]
to `"/onboarding"` instead of `"/"`.
Alternatively, to construct a FlutterViewController directly without pre-warming
a FlutterEngine:
{% samplecode initial-route-without-pre-warming %}
{% sample Swift %}
```swift
let flutterViewController = FlutterViewController(
project: nil, initialRoute: "/onboarding", nibName: nil, bundle: nil)
```
{% sample Objective-C %}
```objectivec
FlutterViewController* flutterViewController =
[[FlutterViewController alloc] initWithProject:nil
initialRoute:@"/onboarding"
nibName:nil
bundle:nil];
```
{% endsamplecode %}
{{site.alert.tip}}
In order to imperatively change your current Flutter
route from the platform side after the `FlutterEngine`
is already running, use [`pushRoute()`][]
or [`popRoute()`] on the `FlutterViewController`.
To pop the iOS route from the Flutter side,
call [`SystemNavigator.pop()`][].
{{site.alert.end}}
See [Navigation and routing][] for more about Flutter's routes.
### Other
The previous example only illustrates a few ways to customize
how a Flutter instance is initiated. Using [platform channels][],
you're free to push data or prepare your Flutter environment
in any way you'd like, before presenting the Flutter UI using a
`FlutterViewController`.
[`FlutterEngine`]: {{site.api}}/ios-embedder/interface_flutter_engine.html
[`FlutterViewController`]: {{site.api}}/ios-embedder/interface_flutter_view_controller.html
[Loading sequence and performance]: /add-to-app/performance
[local_auth]: {{site.pub}}/packages/local_auth
[Navigation and routing]: /ui/navigation
[Navigator]: {{site.api}}/flutter/widgets/Navigator-class.html
[`NavigatorState`]: {{site.api}}/flutter/widgets/NavigatorState-class.html
[`openURL`]: {{site.apple-dev}}/documentation/uikit/uiapplicationdelegate/1623112-application
[platform channels]: /platform-integration/platform-channels
[`popRoute()`]: {{site.api}}/ios-embedder/interface_flutter_view_controller.html#ac89c8010fbf7a39f7aaab64f68c013d2
[`pushRoute()`]: {{site.api}}/ios-embedder/interface_flutter_view_controller.html#ac7cffbf03f9c8c0b28d1f0dafddece4e
[`runApp`]: {{site.api}}/flutter/widgets/runApp.html
[`runWithEntrypoint`]: {{site.api}}/ios-embedder/interface_flutter_engine.html#a019d6b3037eff6cfd584fb2eb8e9035e
[`SystemNavigator.pop()`]: {{site.api}}/flutter/services/SystemNavigator/pop.html
[tree-shaken]: https://en.wikipedia.org/wiki/Tree_shaking
[`WidgetsApp`]: {{site.api}}/flutter/widgets/WidgetsApp-class.html
[`window.defaultRouteName`]: {{site.api}}/flutter/dart-ui/SingletonFlutterWindow/defaultRouteName.html
[Start a FlutterEngine and FlutterViewController section]:/add-to-app/ios/add-flutter-screen/#start-a-flutterengine-and-flutterviewcontroller
| website/src/add-to-app/ios/add-flutter-screen.md/0 | {
"file_path": "website/src/add-to-app/ios/add-flutter-screen.md",
"repo_id": "website",
"token_count": 8480
} | 1,232 |
<?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="content" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="406px" height="737.85px" viewBox="0 0 406 737.85" enable-background="new 0 0 406 737.85" xml:space="preserve">
<g>
<g opacity="0.54" enable-background="new ">
<path d="M35.68,641.37h52.6v10.3h-41.9v31.1h37.8v10.2h-37.8v39.4h-10.7V641.37z"/>
<path d="M100.98,641.37h10.8v90.9h-10.8V641.37z"/>
<path d="M133.38,727.47c-4.1-4.6-6.2-11-6.2-19.2v-40.8h10.8v39.1c0,6.2,1.4,10.7,4.2,13.6c2.8,2.9,6.6,4.3,11.3,4.3
c3.6,0,6.9-1,9.7-2.9s5-4.5,6.6-7.6s2.3-6.4,2.3-9.9v-36.6h10.8v64.8h-10.3v-9.4h-0.5c-1.8,3.2-4.6,5.9-8.5,8.1
c-3.9,2.2-8,3.3-12.4,3.3C143.48,734.27,137.48,732.07,133.38,727.47z"/>
<path d="M217.18,733.07c-2.2-0.9-4.1-2-5.7-3.5c-1.7-1.6-3-3.5-3.8-5.7s-1.3-4.8-1.3-7.9v-38.7h-11.3v-9.8h11.3v-18.3h10.8v18.3
h15.7v9.8h-15.7v36.1c0,3.6,0.7,6.3,2,8c1.6,1.9,3.9,2.9,7,2.9c2.5,0,4.8-0.7,7.1-2.2v10.5c-1.3,0.6-2.6,1-3.9,1.3
c-1.3,0.3-3,0.4-5,0.4C221.88,734.27,219.48,733.87,217.18,733.07z"/>
<path d="M263.08,733.07c-2.2-0.9-4.1-2-5.7-3.5c-1.7-1.6-3-3.5-3.8-5.7s-1.3-4.8-1.3-7.9v-38.7h-11.3v-9.8h11.3v-18.3h10.8v18.3
h15.7v9.8h-15.7v36.1c0,3.6,0.7,6.3,2,8c1.6,1.9,3.9,2.9,7,2.9c2.5,0,4.8-0.7,7.1-2.2v10.5c-1.3,0.6-2.6,1-3.9,1.3
c-1.3,0.3-3,0.4-5,0.4C267.78,734.27,265.28,733.87,263.08,733.07z"/>
<path d="M301.38,729.87c-4.9-3-8.7-7-11.5-12.3c-2.8-5.2-4.1-11.1-4.1-17.6c0-6.3,1.3-12,3.9-17.3c2.6-5.2,6.2-9.4,11-12.6
c4.7-3.1,10.2-4.7,16.5-4.7s11.9,1.4,16.5,4.3c4.7,2.8,8.2,6.8,10.7,11.7c2.5,5,3.7,10.7,3.7,17.1c0,1.3-0.1,2.4-0.4,3.3h-51.2
c0.3,4.9,1.4,9.1,3.6,12.4c2.1,3.4,4.8,5.9,8.1,7.6c3.3,1.7,6.7,2.5,10.2,2.5c8.3,0,14.7-3.9,19.2-11.7l9.1,4.4
c-2.8,5.2-6.6,9.4-11.4,12.4c-4.8,3-10.6,4.6-17.3,4.6C311.78,734.27,306.28,732.87,301.38,729.87z M336.68,693.07
c-0.2-2.7-0.9-5.4-2.3-8.1c-1.4-2.7-3.5-5-6.4-6.9s-6.6-2.8-11-2.8c-5.1,0-9.4,1.6-12.9,4.9c-3.5,3.3-5.8,7.6-6.9,12.9
L336.68,693.07L336.68,693.07z"/>
<path d="M360.68,667.47h10.3v10.4h0.5c1.3-3.6,3.7-6.5,7.4-8.9c3.6-2.4,7.4-3.6,11.4-3.6c3,0,5.5,0.5,7.6,1.4v11.6
c-2.7-1.4-5.8-2-9.1-2c-3.1,0-6,0.9-8.6,2.7s-4.7,4.2-6.3,7.2s-2.3,6.3-2.3,9.7v36.3h-10.8v-64.8H360.68z"/>
</g>
<g>
<g>
<g>
<defs>
<path id="SVGID_1_" d="M404.03,233.33L270.02,367.34l134.01,134.04l0,0H250.87l-57.45-57.45l0,0l-76.59-76.59l134.04-134.01
H404.03L404.03,233.33L404.03,233.33z M250.87,3.57L1.97,252.48l76.59,76.59L404.03,3.57H250.87z"/>
</defs>
<clipPath id="SVGID_2_">
<use xlink:href="#SVGID_1_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_2_)">
<g>
<polygon fill="#39CEFD" points="404.03,233.33 404.03,233.33 404.03,233.33 250.87,233.33 116.86,367.37 193.43,443.94
"/>
</g>
</g>
</g>
<g>
<defs>
<path id="SVGID_3_" d="M404.03,233.33L270.02,367.34l134.01,134.04l0,0H250.87l-57.45-57.45l0,0l-76.59-76.59l134.04-134.01
H404.03L404.03,233.33L404.03,233.33z M250.87,3.57L1.97,252.48l76.59,76.59L404.03,3.57H250.87z"/>
</defs>
<clipPath id="SVGID_4_">
<use xlink:href="#SVGID_3_" overflow="visible"/>
</clipPath>
<polygon clip-path="url(#SVGID_4_)" fill="#39CEFD" points="78.56,329.07 1.97,252.48 250.87,3.57 404.03,3.57 "/>
</g>
<g>
<defs>
<path id="SVGID_5_" d="M404.03,233.33L270.02,367.34l134.01,134.04l0,0H250.87l-57.45-57.45l0,0l-76.59-76.59l134.04-134.01
H404.03L404.03,233.33L404.03,233.33z M250.87,3.57L1.97,252.48l76.59,76.59L404.03,3.57H250.87z"/>
</defs>
<clipPath id="SVGID_6_">
<use xlink:href="#SVGID_5_" overflow="visible"/>
</clipPath>
<polygon clip-path="url(#SVGID_6_)" fill="#03569B" points="193.43,443.94 250.87,501.38 404.03,501.38 404.03,501.38
270.02,367.37 "/>
</g>
<g>
<defs>
<path id="SVGID_7_" d="M404.03,233.33L270.02,367.34l134.01,134.04l0,0H250.87l-57.45-57.45l0,0l-76.59-76.59l134.04-134.01
H404.03L404.03,233.33L404.03,233.33z M250.87,3.57L1.97,252.48l76.59,76.59L404.03,3.57H250.87z"/>
</defs>
<clipPath id="SVGID_8_">
<use xlink:href="#SVGID_7_" overflow="visible"/>
</clipPath>
<linearGradient id="SVGID_9_" gradientUnits="userSpaceOnUse" x1="7709.7266" y1="-3087.0684" x2="7937.896" y2="-2858.8984" gradientTransform="matrix(0.25 0 0 -0.25 -1711.6658 -313.0314)">
<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="193.43,443.94 307.02,404.62 270.02,367.37 "/>
</g>
<g>
<defs>
<path id="SVGID_10_" d="M404.03,233.33L270.02,367.34l134.01,134.04l0,0H250.87l-57.45-57.45l0,0l-76.59-76.59l134.04-134.01
H404.03L404.03,233.33L404.03,233.33z M250.87,3.57L1.97,252.48l76.59,76.59L404.03,3.57H250.87z"/>
</defs>
<clipPath id="SVGID_11_">
<use xlink:href="#SVGID_10_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_11_)">
<rect x="139.28" y="313.2" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -203.1048 244.3713)" fill="#16B9FD" width="108.3" height="108.3"/>
</g>
</g>
</g>
<radialGradient id="SVGID_12_" cx="6899.7866" cy="-1402.1913" r="2436.1667" gradientTransform="matrix(0.25 0 0 -0.25 -1711.6658 -313.0314)" 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="M404.03,233.33L270.02,367.34l134.01,134.04l0,0H250.87l-57.45-57.45l0,0l-76.59-76.59
l134.04-134.01H404.03L404.03,233.33L404.03,233.33z M250.87,3.57L1.97,252.48l76.59,76.59L404.03,3.57H250.87z"/>
</g>
</g>
</svg>
| website/src/assets/images/branding/flutter/logo+text/vertical/default.svg/0 | {
"file_path": "website/src/assets/images/branding/flutter/logo+text/vertical/default.svg",
"repo_id": "website",
"token_count": 3909
} | 1,233 |
---
title: Using Flutter in China
description: How to use, access, and learn about Flutter in China.
toc: true
os-list: [Windows, macOS, Linux, ChromeOS]
---
{% assign flutter-sdk = 'flutter_opsys_v3.13.0-stable.' %}
{% capture sdk-path -%}flutter_infra_release/releases/stable/opsys/{{flutter-sdk}}{%- endcapture %}
{% include docs/china-notice-cn.md %}
To speed the download and installation of Flutter in China,
consider using a [mirror site][] or _mirror_.
{{site.alert.important}}
Use mirror sites _only_ if you _trust_ the provider.
The Flutter team can't verify their reliability or security.
{{site.alert.end}}
[mirror site]: https://en.wikipedia.org/wiki/Mirror_site
## Use a Flutter mirror site
The [China Flutter User Group][] (CFUG) maintains a Simplified Chinese
Flutter website [https://flutter.cn](https://flutter.cn) and a mirror.
Other mirrors can be found at the [end of this guide](#known-trusted-community-run-mirror-sites).
### Configure your machine to use a mirror site
To install or use Flutter in China, use a trustworthy Flutter mirror.
This requires setting two environment variables on your machine.
_All examples that follow presume that you are using the CFUG mirror._
To set your machine to use a mirror site:
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="china-os-tabs" role="tablist">
{% for os in page.os-list %}
{% assign id = os | downcase -%}
<li class="nav-item">
<a class="nav-link {%- if id == 'windows' %} active {% endif %}" id="{{id}}-tab" href="#{{id}}" role="tab" aria-controls="{{id}} {{id}}-dl {{id}}-pub" aria-selected="true">{{os}}</a>
</li>
{% endfor -%}
</ul>
{% comment %} Tab panes {% endcomment -%}
<div class="tab-content">
{% for os in page.os-list %}
{% include_relative _os-settings.md ref-os=os sdk=flutter-sdk %}
{% endfor -%}
</div>
### Download Flutter archives based on a mirror site
To download Flutter from the [SDK archive][] from a mirror,
replace `storage.googleapis.com` with the URL of your trusted mirror.
Use your mirror site in the browser or in other applications
like IDM or Thunder.
This should improve download speed.
[SDK archive]: /release/archive
The following example shows how to change the URL for Flutter's download site
from Google's archive to CFUG's mirror.
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="china-os-dl-tabs" role="tablist">
{% for os in page.os-list %}
{% assign id = os | downcase -%}
<li class="nav-item">
<a class="nav-link {%- if id == 'windows' %} active {% endif %}" id="{{id}}-dl-tab" href="#{{id}}-dl" role="tab" aria-controls="{{id}} {{id}}-dl {{id}}-pub" aria-selected="true">{{os}}</a>
</li>
{% endfor -%}
</ul>
{% comment %} Tab panes {% endcomment -%}
<div class="tab-content">
{% for os in page.os-list %}
{% include_relative _download-urls.md ref-os=os filepath=sdk-path %}
{% endfor -%}
</div>
{{site.alert.note}}
Not every mirror supports downloading artifacts using their direct URL.
{{site.alert.end}}
## Configure your machine to publish your package
To publish your packages to `pub.dev`,
you need to be able to access both Google Auth and the `pub.dev` site.
{% comment %}
From <https://github.com/flutter/website/pull/9338#discussion_r1328077020>
{% endcomment %}
To enable access to `pub.dev`:
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="china-os-pub-tabs" role="tablist">
{% for os in page.os-list %}
{% assign id = os | downcase -%}
<li class="nav-item">
<a class="nav-link {%- if id == 'windows' %} active {% endif %}" id="{{id}}-pub-tab" href="#{{id}}-pub" role="tab" aria-controls="{{id}} {{id}}-pub" aria-selected="true">{{os}}</a>
</li>
{% endfor -%}
</ul>
{% comment %} Tab panes {% endcomment -%}
<div class="tab-content">
{% include_relative _pub-settings.md os="Windows" filepath=path %}
{% include_relative _pub-settings.md os="macOS" filepath=path %}
{% include_relative _pub-settings.md os="Linux" filepath=path %}
{% include_relative _pub-settings.md os="ChromeOS" filepath=path %}
</div>
To learn more about publishing packages, check out the
[Dart documentation on publishing packages][].
[Dart documentation on publishing packages]: {{site.dart-site}}/tools/pub/publishing
## Known, trusted community-run mirror sites
The Flutter team can't guarantee long-term availability of any mirrors.
You can use other mirrors if they become available.
{% for mirror in site.data.mirrors %}
<hr>
### {{mirror.group}}
[{{mirror.group}}][] maintains the `{{mirror.mirror}}` mirror.
It includes the Flutter SDK and pub packages.
#### Configure your machine to use this mirror
To set your machine to use this mirror, use these commands.
On macOS, Linux, or ChromeOS:
```terminal
export PUB_HOSTED_URL={{mirror.urls.pubhosted}};
export FLUTTER_STORAGE_BASE_URL={{mirror.urls.flutterstorage}}
```
On Windows:
```terminal
$env:PUB_HOSTED_URL="{{mirror.urls.pubhosted}}";
$env:FLUTTER_STORAGE_BASE_URL="{{mirror.urls.flutterstorage}}"
```
#### Get support for this mirror
If you're running into issues that only occur when
using the `{{mirror.mirror}}` mirror, report the issue to their
[issue tracker]({{mirror.urls.issues}}).
{% endfor %}
{% for mirror in site.data.mirrors %}
[{{mirror.group}}]: {{mirror.urls.group}}
{% endfor %}
## Offer to host a new mirror site
If you're interested in setting up your own mirror,
contact [[email protected]](mailto:[email protected])
for assistance.
| website/src/community/china/index.md/0 | {
"file_path": "website/src/community/china/index.md",
"repo_id": "website",
"token_count": 1901
} | 1,234 |
---
title: Create an expandable FAB
description: How to implement a FAB that expands to multiple buttons when tapped.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/effects/expandable_fab"?>
A Floating Action Button (FAB) is a round button that
floats near the bottom right of a content area.
This button represents the primary action for the
corresponding content, but sometimes, there is no primary action.
Instead, there are a few critical actions that the user might take.
In this case, you could create an expandable FAB like the one shown
in the following figure. When pressed, this expandable FAB spawns
multiple, other action buttons. Each button corresponds to one of
those critical actions.
The following animation shows the app's behavior:
{:.site-mobile-screenshot}
## Create an ExpandableFab widget
Start by creating a new stateful widget called `ExpandableFab`.
This widget displays the primary FAB and coordinates the expansion
and collapse of the other action buttons. The widget takes
in parameters for whether or not the `ExpandedFab` begins in
the expanded position, what the maximum distance of each action button is,
and a list of children. You'll use the list later to provide
the other action buttons.
<?code-excerpt "lib/excerpt1.dart (ExpandableFab)"?>
```dart
@immutable
class ExpandableFab extends StatefulWidget {
const ExpandableFab({
super.key,
this.initialOpen,
required this.distance,
required this.children,
});
final bool? initialOpen;
final double distance;
final List<Widget> children;
@override
State<ExpandableFab> createState() => _ExpandableFabState();
}
class _ExpandableFabState extends State<ExpandableFab> {
@override
Widget build(BuildContext context) {
return const SizedBox();
}
}
```
## FAB cross-fade
The `ExpandableFab` displays a blue edit button when collapsed
and a white close button when expanded. When expanding and collapsing,
these two buttons scale and fade between one another.
Implement the expand and collapse cross-fade between the two different FABs.
<?code-excerpt "lib/excerpt2.dart (ExpandableFabState)"?>
```dart
class _ExpandableFabState extends State<ExpandableFab> {
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
}
void _toggle() {
setState(() {
_open = !_open;
});
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [
_buildTapToCloseFab(),
_buildTapToOpenFab(),
],
),
);
}
Widget _buildTapToCloseFab() {
return SizedBox(
width: 56,
height: 56,
child: Center(
child: Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
elevation: 4,
child: InkWell(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.close,
color: Theme.of(context).primaryColor,
),
),
),
),
),
);
}
Widget _buildTapToOpenFab() {
return IgnorePointer(
ignoring: _open,
child: AnimatedContainer(
transformAlignment: Alignment.center,
transform: Matrix4.diagonal3Values(
_open ? 0.7 : 1.0,
_open ? 0.7 : 1.0,
1.0,
),
duration: const Duration(milliseconds: 250),
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
child: AnimatedOpacity(
opacity: _open ? 0.0 : 1.0,
curve: const Interval(0.25, 1.0, curve: Curves.easeInOut),
duration: const Duration(milliseconds: 250),
child: FloatingActionButton(
onPressed: _toggle,
child: const Icon(Icons.create),
),
),
),
);
}
}
```
The open button sits on top of the close button within a `Stack`,
allowing for the visual appearance of a cross-fade as the top button
appears and disappears.
To achieve the cross-fade animation, the open button uses an
`AnimatedContainer` with a scale transform and an `AnimatedOpacity`.
The open button scales down and fades out when the `ExpandableFab`
goes from collapsed to expanded. Then, the open button scales up
and fades in when the `ExpandableFab` goes from expanded to collapsed.
You'll notice that the open button is wrapped with an
`IgnorePointer` widget. This is because the open button always exists,
even when it's transparent. Without the `IgnorePointer`,
the open button always receives the tap event,
even when the close button is visible.
## Create an ActionButton widget
Each of the buttons that expand from the `ExpandableFab`
have the same design. They're blue circles with white icons.
More precisely, the button background color is the `ColorScheme.secondary`
color, and the icon color is `ColorScheme.onSecondary`.
Define a new stateless widget called `ActionButton` to display
these round buttons.
<?code-excerpt "lib/main.dart (ActionButton)"?>
```dart
@immutable
class ActionButton extends StatelessWidget {
const ActionButton({
super.key,
this.onPressed,
required this.icon,
});
final VoidCallback? onPressed;
final Widget icon;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
color: theme.colorScheme.secondary,
elevation: 4,
child: IconButton(
onPressed: onPressed,
icon: icon,
color: theme.colorScheme.onSecondary,
),
);
}
}
```
Pass a few instances of this new `ActionButton` widget into your
`ExpandableFab`.
<?code-excerpt "lib/main.dart (FloatingActionButton)"?>
```dart
floatingActionButton: ExpandableFab(
distance: 112,
children: [
ActionButton(
onPressed: () => _showAction(context, 0),
icon: const Icon(Icons.format_size),
),
ActionButton(
onPressed: () => _showAction(context, 1),
icon: const Icon(Icons.insert_photo),
),
ActionButton(
onPressed: () => _showAction(context, 2),
icon: const Icon(Icons.videocam),
),
],
),
```
## Expand and collapse the action buttons
The child `ActionButton`s should fly out from under the open
FAB when expanded. Then, the child `ActionButton`s should
fly back under the open FAB when collapsed.
This motion requires explicit (x,y) positioning of each
`ActionButton` and an `Animation` to choreograph changes to
those (x,y) positions over time.
Introduce an `AnimationController` and an `Animation` to
control the rate at which the various `ActionButton`s expand and collapse.
<?code-excerpt "lib/excerpt3.dart (ExpandableFabState3)" replace="/\/\/ code-excerpt-closing-bracket/}/g"?>
```dart
class _ExpandableFabState extends State<ExpandableFab>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _expandAnimation;
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
_controller = AnimationController(
value: _open ? 1.0 : 0.0,
duration: const Duration(milliseconds: 250),
vsync: this,
);
_expandAnimation = CurvedAnimation(
curve: Curves.fastOutSlowIn,
reverseCurve: Curves.easeOutQuad,
parent: _controller,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggle() {
setState(() {
_open = !_open;
if (_open) {
_controller.forward();
} else {
_controller.reverse();
}
});
}
}
```
Next, introduce a new stateless widget called `_ExpandingActionButton`,
and configure this widget to animate and position an individual `ActionButton`. The `ActionButton` is provided as a generic `Widget` called `child`.
<?code-excerpt "lib/excerpt3.dart (ExpandingActionButton)"?>
```dart
@immutable
class _ExpandingActionButton extends StatelessWidget {
const _ExpandingActionButton({
required this.directionInDegrees,
required this.maxDistance,
required this.progress,
required this.child,
});
final double directionInDegrees;
final double maxDistance;
final Animation<double> progress;
final Widget child;
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: progress,
builder: (context, child) {
final offset = Offset.fromDirection(
directionInDegrees * (math.pi / 180.0),
progress.value * maxDistance,
);
return Positioned(
right: 4.0 + offset.dx,
bottom: 4.0 + offset.dy,
child: Transform.rotate(
angle: (1.0 - progress.value) * math.pi / 2,
child: child!,
),
);
},
child: FadeTransition(
opacity: progress,
child: child,
),
);
}
}
```
The most important part of `_ExpandingActionButton` is the
`Positioned` widget, which positions the `child` at a specific (x,y)
coordinate within the surrounding `Stack`.
The `AnimatedBuilder` causes the `Positioned` widget to rebuild
every time the animation changes. The `FadeTransition` widget
orchestrates the appearance and disappearance of each
`ActionButton` as they expand and collapse, respectively.
{{site.alert.note}}
The use of a `Positioned` widget within `_ExpandingActionButton`
implies that `_ExpandingActionButton` can only be used as a direct
child of a `Stack`. This is due to the explicit relationship
between `Positioned` and `Stack`.
{{site.alert.end}}
Finally, use the new `_ExpandingActionButton` widget
within the `ExpandableFab` to complete the exercise.
<?code-excerpt "lib/excerpt4.dart (ExpandableFabState4)" replace="/\/\/ code-excerpt-closing-bracket/}/g"?>
```dart
class _ExpandableFabState extends State<ExpandableFab>
with SingleTickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [
_buildTapToCloseFab(),
..._buildExpandingActionButtons(),
_buildTapToOpenFab(),
],
),
);
}
List<Widget> _buildExpandingActionButtons() {
final children = <Widget>[];
final count = widget.children.length;
final step = 90.0 / (count - 1);
for (var i = 0, angleInDegrees = 0.0;
i < count;
i++, angleInDegrees += step) {
children.add(
_ExpandingActionButton(
directionInDegrees: angleInDegrees,
maxDistance: widget.distance,
progress: _expandAnimation,
child: widget.children[i],
),
);
}
return children;
}
}
```
Congratulations! You now have an expandable FAB.
## Interactive example
Run the app:
* Click the FAB in the lower-right corner,
represented with an Edit icon.
It fans out to 3 buttons and is itself replaced by
a close button, represented by an **X**.
* Click the close button to see the expanded
buttons fly back to the original FAB and
the **X** is replaced by the Edit icon.
* Expand the FAB again, and click on any
of the 3 satellite buttons to see a dialog
representing that button's action.
<!-- 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 'dart:math' as math;
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleExpandableFab(),
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class ExampleExpandableFab extends StatelessWidget {
static const _actionTitles = ['Create Post', 'Upload Photo', 'Upload Video'];
const ExampleExpandableFab({super.key});
void _showAction(BuildContext context, int index) {
showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
content: Text(_actionTitles[index]),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('CLOSE'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Expandable Fab'),
),
body: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: 25,
itemBuilder: (context, index) {
return FakeItem(isBig: index.isOdd);
},
),
floatingActionButton: ExpandableFab(
distance: 112,
children: [
ActionButton(
onPressed: () => _showAction(context, 0),
icon: const Icon(Icons.format_size),
),
ActionButton(
onPressed: () => _showAction(context, 1),
icon: const Icon(Icons.insert_photo),
),
ActionButton(
onPressed: () => _showAction(context, 2),
icon: const Icon(Icons.videocam),
),
],
),
);
}
}
@immutable
class ExpandableFab extends StatefulWidget {
const ExpandableFab({
super.key,
this.initialOpen,
required this.distance,
required this.children,
});
final bool? initialOpen;
final double distance;
final List<Widget> children;
@override
State<ExpandableFab> createState() => _ExpandableFabState();
}
class _ExpandableFabState extends State<ExpandableFab>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _expandAnimation;
bool _open = false;
@override
void initState() {
super.initState();
_open = widget.initialOpen ?? false;
_controller = AnimationController(
value: _open ? 1.0 : 0.0,
duration: const Duration(milliseconds: 250),
vsync: this,
);
_expandAnimation = CurvedAnimation(
curve: Curves.fastOutSlowIn,
reverseCurve: Curves.easeOutQuad,
parent: _controller,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggle() {
setState(() {
_open = !_open;
if (_open) {
_controller.forward();
} else {
_controller.reverse();
}
});
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: Stack(
alignment: Alignment.bottomRight,
clipBehavior: Clip.none,
children: [
_buildTapToCloseFab(),
..._buildExpandingActionButtons(),
_buildTapToOpenFab(),
],
),
);
}
Widget _buildTapToCloseFab() {
return SizedBox(
width: 56,
height: 56,
child: Center(
child: Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
elevation: 4,
child: InkWell(
onTap: _toggle,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.close,
color: Theme.of(context).primaryColor,
),
),
),
),
),
);
}
List<Widget> _buildExpandingActionButtons() {
final children = <Widget>[];
final count = widget.children.length;
final step = 90.0 / (count - 1);
for (var i = 0, angleInDegrees = 0.0;
i < count;
i++, angleInDegrees += step) {
children.add(
_ExpandingActionButton(
directionInDegrees: angleInDegrees,
maxDistance: widget.distance,
progress: _expandAnimation,
child: widget.children[i],
),
);
}
return children;
}
Widget _buildTapToOpenFab() {
return IgnorePointer(
ignoring: _open,
child: AnimatedContainer(
transformAlignment: Alignment.center,
transform: Matrix4.diagonal3Values(
_open ? 0.7 : 1.0,
_open ? 0.7 : 1.0,
1.0,
),
duration: const Duration(milliseconds: 250),
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
child: AnimatedOpacity(
opacity: _open ? 0.0 : 1.0,
curve: const Interval(0.25, 1.0, curve: Curves.easeInOut),
duration: const Duration(milliseconds: 250),
child: FloatingActionButton(
onPressed: _toggle,
child: const Icon(Icons.create),
),
),
),
);
}
}
@immutable
class _ExpandingActionButton extends StatelessWidget {
const _ExpandingActionButton({
required this.directionInDegrees,
required this.maxDistance,
required this.progress,
required this.child,
});
final double directionInDegrees;
final double maxDistance;
final Animation<double> progress;
final Widget child;
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: progress,
builder: (context, child) {
final offset = Offset.fromDirection(
directionInDegrees * (math.pi / 180.0),
progress.value * maxDistance,
);
return Positioned(
right: 4.0 + offset.dx,
bottom: 4.0 + offset.dy,
child: Transform.rotate(
angle: (1.0 - progress.value) * math.pi / 2,
child: child!,
),
);
},
child: FadeTransition(
opacity: progress,
child: child,
),
);
}
}
@immutable
class ActionButton extends StatelessWidget {
const ActionButton({
super.key,
this.onPressed,
required this.icon,
});
final VoidCallback? onPressed;
final Widget icon;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
shape: const CircleBorder(),
clipBehavior: Clip.antiAlias,
color: theme.colorScheme.secondary,
elevation: 4,
child: IconButton(
onPressed: onPressed,
icon: icon,
color: theme.colorScheme.onSecondary,
),
);
}
}
@immutable
class FakeItem extends StatelessWidget {
const FakeItem({
super.key,
required this.isBig,
});
final bool isBig;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 24),
height: isBig ? 128 : 36,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(8)),
color: Colors.grey.shade300,
),
);
}
}
```
| website/src/cookbook/effects/expandable-fab.md/0 | {
"file_path": "website/src/cookbook/effects/expandable-fab.md",
"repo_id": "website",
"token_count": 7450
} | 1,235 |
---
title: Add multiplayer support using Firestore
description: >
How to use use Firebase Cloud Firestore to implement multiplayer
in your game.
---
<?code-excerpt path-base="cookbook/games/firestore_multiplayer"?>
Multiplayer games need a way to synchronize game states between players.
Broadly speaking, two types of multiplayer games exist:
1. **High tick rate**.
These games need to synchronize game states many times per second
with low latency.
These would include action games, sports games, fighting games.
2. **Low tick rate**.
These games only need to synchronize game states occasionally
with latency having less impact.
These would include card games, strategy games, puzzle games.
This resembles the differentiation between real-time versus turn-based
games, though the analogy falls short.
For example, real-time strategy games run—as the name suggests—in
real-time, but that doesn't correlate to a high tick rate.
These games can simulate much of what happens
in between player interactions on local machines.
Therefore, they don't need to synchronize game states that often.
{:.site-illustration}
If you can choose low tick rates as a developer, you should.
Low tick lowers latency requirements and server costs.
Sometimes, a game requires high tick rates of synchronization.
For those cases, solutions such as Firestore *don't make a good fit*.
Pick a dedicated multiplayer server solution such as [Nakama][].
Nakama has a [Dart package][].
If you expect that your game requires a low tick rate of synchronization,
continue reading.
This recipe demonstrates how to use the
[`cloud_firestore` package][]
to implement multiplayer capabilities in your game.
This recipe doesn't require a server.
It uses two or more clients sharing game state using Cloud Firestore.
[`cloud_firestore` package]: {{site.pub-pkg}}/cloud_firestore
[Dart package]: {{site.pub-pkg}}/nakama
[Nakama]: https://heroiclabs.com/nakama/
## 1. Prepare your game for multiplayer
Write your game code to allow changing the game state
in response to both local events and remote events.
A local event could be a player action or some game logic.
A remote event could be a world update coming from the server.
{:.site-mobile-screenshot .site-illustration}
To simplify this cookbook recipe, start with
the [`card`][] template that you'll find
in the [`flutter/games` repository][].
Run the following command to clone that repository:
```terminal
git clone https://github.com/flutter/games.git
```
{% comment %}
If/when we have a "sample_extractor" tool, or any other easier way
to get the code, mention that here.
{% endcomment %}
Open the project in `templates/card`.
{{site.alert.note}}
You can ignore this step and follow the recipe with your own game
project. Adapt the code at appropriate places.
{{site.alert.end}}
[`card`]: {{site.github}}/flutter/games/tree/main/templates/card#readme
[`flutter/games` repository]: {{site.github}}/flutter/games
## 2. Install Firestore
[Cloud Firestore][] is a horizontally scaling,
NoSQL document database in the cloud.
It includes built-in live synchronization.
This is perfect for our needs.
It keeps the game state updated in the cloud database,
so every player sees the same state.
If you want a quick, 15-minute primer on Cloud Firestore,
check out the following video:
<iframe width="560" height="315" src="{{site.yt.embed}}/v_hR4K4auoQ" title="What is a NoSQL Database? Learn about Cloud Firestore" {{site.yt.set}}></iframe>
To add Firestore to your Flutter project,
follow the first two steps of the
[Get started with Cloud Firestore][] guide:
* [Create a Cloud Firestore database][]
* [Set up your development environment][]
The desired outcomes include:
* A Firestore database ready in the cloud, in **Test mode**
* A generated `firebase_options.dart` file
* The appropriate plugins added to your `pubspec.yaml`
You *don't* need to write any Dart code in this step.
As soon as you understand the step of writing
Dart code in that guide, return to this recipe.
{% comment %}
Revisit to see if we can inline the steps here:
<https://firebase.google.com/docs/flutter/setup>
... followed by the first 2 steps here:
<https://firebase.google.com/docs/firestore/quickstart>
{% endcomment %}
[Cloud Firestore]: https://cloud.google.com/firestore/
[Create a Cloud Firestore database]: {{site.firebase}}/docs/firestore/quickstart#create
[Get started with Cloud Firestore]: {{site.firebase}}/docs/firestore/quickstart
[Set up your development environment]: {{site.firebase}}/docs/firestore/quickstart#set_up_your_development_environment
## 3. Initialize Firestore
1. Open `lib/main.dart` and import the plugins,
as well as the `firebase_options.dart` file
that was generated by `flutterfire configure` in the previous step.
<?code-excerpt "lib/main.dart (imports)"?>
```dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
```
2. Add the following code just above the call to `runApp()`
in `lib/main.dart`:
<?code-excerpt "lib/main.dart (initializeApp)"?>
```dart
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
```
This ensures that Firebase is initialized on game startup.
3. Add the Firestore instance to the app.
That way, any widget can access this instance.
Widgets can also react to the instance missing, if needed.
To do this with the `card` template, you can use
the `provider` package
(which is already installed as a dependency).
Replace the boilerplate `runApp(MyApp())` with the following:
<?code-excerpt "lib/main.dart (runApp)"?>
```dart
runApp(
Provider.value(
value: FirebaseFirestore.instance,
child: MyApp(),
),
);
```
Put the provider above `MyApp`, not inside it.
This enables you to test the app without Firebase.
{{site.alert.note}}
In case you are *not* working with the `card` template,
you must either [install the `provider` package][]
or use your own method of accessing the `FirebaseFirestore`
instance from various parts of your codebase.
{{site.alert.end}}
[install the `provider` package]: {{site.pub-pkg}}/provider/install
## 4. Create a Firestore controller class
Though you can talk to Firestore directly,
you should write a dedicated controller class
to make the code more readable and maintainable.
How you implement the controller depends on your game
and on the exact design of your multiplayer experience.
For the case of the `card` template,
you could synchronize the contents of the two circular playing areas.
It's not enough for a full multiplayer experience,
but it's a good start.
{:.site-mobile-screenshot .site-illustration}
To create a controller, copy,
then paste the following code into a new file called
`lib/multiplayer/firestore_controller.dart`.
<?code-excerpt "lib/multiplayer/firestore_controller.dart"?>
```dart
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import '../game_internals/board_state.dart';
import '../game_internals/playing_area.dart';
import '../game_internals/playing_card.dart';
class FirestoreController {
static final _log = Logger('FirestoreController');
final FirebaseFirestore instance;
final BoardState boardState;
/// For now, there is only one match. But in order to be ready
/// for match-making, put it in a Firestore collection called matches.
late final _matchRef = instance.collection('matches').doc('match_1');
late final _areaOneRef = _matchRef
.collection('areas')
.doc('area_one')
.withConverter<List<PlayingCard>>(
fromFirestore: _cardsFromFirestore, toFirestore: _cardsToFirestore);
late final _areaTwoRef = _matchRef
.collection('areas')
.doc('area_two')
.withConverter<List<PlayingCard>>(
fromFirestore: _cardsFromFirestore, toFirestore: _cardsToFirestore);
StreamSubscription? _areaOneFirestoreSubscription;
StreamSubscription? _areaTwoFirestoreSubscription;
StreamSubscription? _areaOneLocalSubscription;
StreamSubscription? _areaTwoLocalSubscription;
FirestoreController({required this.instance, required this.boardState}) {
// Subscribe to the remote changes (from Firestore).
_areaOneFirestoreSubscription = _areaOneRef.snapshots().listen((snapshot) {
_updateLocalFromFirestore(boardState.areaOne, snapshot);
});
_areaTwoFirestoreSubscription = _areaTwoRef.snapshots().listen((snapshot) {
_updateLocalFromFirestore(boardState.areaTwo, snapshot);
});
// Subscribe to the local changes in game state.
_areaOneLocalSubscription = boardState.areaOne.playerChanges.listen((_) {
_updateFirestoreFromLocalAreaOne();
});
_areaTwoLocalSubscription = boardState.areaTwo.playerChanges.listen((_) {
_updateFirestoreFromLocalAreaTwo();
});
_log.fine('Initialized');
}
void dispose() {
_areaOneFirestoreSubscription?.cancel();
_areaTwoFirestoreSubscription?.cancel();
_areaOneLocalSubscription?.cancel();
_areaTwoLocalSubscription?.cancel();
_log.fine('Disposed');
}
/// Takes the raw JSON snapshot coming from Firestore and attempts to
/// convert it into a list of [PlayingCard]s.
List<PlayingCard> _cardsFromFirestore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options,
) {
final data = snapshot.data()?['cards'] as List?;
if (data == null) {
_log.info('No data found on Firestore, returning empty list');
return [];
}
final list = List.castFrom<Object?, Map<String, Object?>>(data);
try {
return list.map((raw) => PlayingCard.fromJson(raw)).toList();
} catch (e) {
throw FirebaseControllerException(
'Failed to parse data from Firestore: $e');
}
}
/// Takes a list of [PlayingCard]s and converts it into a JSON object
/// that can be saved into Firestore.
Map<String, Object?> _cardsToFirestore(
List<PlayingCard> cards,
SetOptions? options,
) {
return {'cards': cards.map((c) => c.toJson()).toList()};
}
/// Updates Firestore with the local state of [area].
Future<void> _updateFirestoreFromLocal(
PlayingArea area, DocumentReference<List<PlayingCard>> ref) async {
try {
_log.fine('Updating Firestore with local data (${area.cards}) ...');
await ref.set(area.cards);
_log.fine('... done updating.');
} catch (e) {
throw FirebaseControllerException(
'Failed to update Firestore with local data (${area.cards}): $e');
}
}
/// Sends the local state of `boardState.areaOne` to Firestore.
void _updateFirestoreFromLocalAreaOne() {
_updateFirestoreFromLocal(boardState.areaOne, _areaOneRef);
}
/// Sends the local state of `boardState.areaTwo` to Firestore.
void _updateFirestoreFromLocalAreaTwo() {
_updateFirestoreFromLocal(boardState.areaTwo, _areaTwoRef);
}
/// Updates the local state of [area] with the data from Firestore.
void _updateLocalFromFirestore(
PlayingArea area, DocumentSnapshot<List<PlayingCard>> snapshot) {
_log.fine('Received new data from Firestore (${snapshot.data()})');
final cards = snapshot.data() ?? [];
if (listEquals(cards, area.cards)) {
_log.fine('No change');
} else {
_log.fine('Updating local data with Firestore data ($cards)');
area.replaceWith(cards);
}
}
}
class FirebaseControllerException implements Exception {
final String message;
FirebaseControllerException(this.message);
@override
String toString() => 'FirebaseControllerException: $message';
}
```
Notice the following features of this code:
* The controller's constructor takes a `BoardState`.
This enables the controller to manipulate the local state of the game.
* The controller subscribes to both local changes to update Firestore
and to remote changes to update the local state and UI.
* The fields `_areaOneRef` and `_areaTwoRef` are
Firebase document references.
They describe where the data for each area resides,
and how to convert between the local Dart objects (`List<PlayingCard>`)
and remote JSON objects (`Map<String, dynamic>`).
The Firestore API lets us subscribe to these references
with `.snapshots()`, and write to them with `.set()`.
## 5. Use the Firestore controller
1. Open the file responsible for starting the play session:
`lib/play_session/play_session_screen.dart` in the case of the
`card` template.
You instantiate the Firestore controller from this file.
2. Import Firebase and the controller:
<?code-excerpt "lib/play_session/play_session_screen.dart (imports)"?>
```dart
import 'package:cloud_firestore/cloud_firestore.dart';
import '../multiplayer/firestore_controller.dart';
```
3. Add a nullable field to the `_PlaySessionScreenState` class
to contain a controller instance:
<?code-excerpt "lib/play_session/play_session_screen.dart (controller)"?>
```dart
FirestoreController? _firestoreController;
```
4. In the `initState()` method of the same class,
add code that tries to read the FirebaseFirestore instance
and, if successful, constructs the controller.
You added the `FirebaseFirestore` instance to `main.dart`
in the *Initialize Firestore* step.
<?code-excerpt "lib/play_session/play_session_screen.dart (initState)"?>
```dart
final firestore = context.read<FirebaseFirestore?>();
if (firestore == null) {
_log.warning("Firestore instance wasn't provided. "
'Running without _firestoreController.');
} else {
_firestoreController = FirestoreController(
instance: firestore,
boardState: _boardState,
);
}
```
5. Dispose of the controller using the `dispose()` method
of the same class.
<?code-excerpt "lib/play_session/play_session_screen.dart (dispose)"?>
```dart
_firestoreController?.dispose();
```
## 6. Test the game
1. Run the game on two separate devices
or in 2 different windows on the same device.
2. Watch how adding a card to an area on one device
makes it appear on the other one.
{% comment %}
TBA: GIF of multiplayer working
{% endcomment %}
3. Open the [Firebase web console][]
and navigate to your project's Firestore Database.
4. Watch how it updates the data in real time.
You can even edit the data in the console
and see all running clients update.

[Firebase web console]: https://console.firebase.google.com/
### Troubleshooting
The most common issues you might encounter when testing
Firebase integration include the following:
* **The game crashes when trying to reach Firebase.**
* Firebase integration hasn't been properly set up.
Revisit *Step 2* and make sure to run `flutterfire configure`
as part of that step.
* **The game doesn't communicate with Firebase on macOS.**
* By default, macOS apps don't have internet access.
Enable [internet entitlement][] first.
[internet entitlement]: /data-and-backend/networking#macos
## 7. Next steps
At this point, the game has near-instant and
dependable synchronization of state across clients.
It lacks actual game rules:
what cards can be played when, and with what results.
This depends on the game itself and is left to you to try.
{:.site-illustration}
At this point, the shared state of the match only includes
the two playing areas and the cards within them.
You can save other data into `_matchRef`, too,
like who the players are and whose turn it is.
If you're unsure where to start,
follow [a Firestore codelab or two][]
to familiarize yourself with the API.
At first, a single match should suffice
for testing your multiplayer game with colleagues and friends.
As you approach the release date,
think about authentication and match-making.
Thankfully, Firebase provides a
[built-in way to authenticate users][]
and the Firestore database structure can handle multiple matches.
Instead of a single `match_1`,
you can populate the matches collection with as many records as needed.

An online match can start in a "waiting" state,
with only the first player present.
Other players can see the "waiting" matches in some kind of lobby.
Once enough players join a match, it becomes "active".
Once again, the exact implementation depends on
the kind of online experience you want.
The basics remain the same:
a large collection of documents,
each representing one active or potential match.
[a Firestore codelab or two]: {{site.codelabs}}/?product=flutter&text=firestore
[built-in way to authenticate users]: {{site.firebase}}/docs/auth/flutter/start
| website/src/cookbook/games/firestore-multiplayer.md/0 | {
"file_path": "website/src/cookbook/games/firestore-multiplayer.md",
"repo_id": "website",
"token_count": 5408
} | 1,236 |
---
title: Lists
description: A catalog of recipes for handling lists in your Flutter app.
---
{% include docs/cookbook-group-index.md %}
| website/src/cookbook/lists/index.md/0 | {
"file_path": "website/src/cookbook/lists/index.md",
"repo_id": "website",
"token_count": 41
} | 1,237 |
---
title: Parse JSON in the background
description: How to perform a task in the background.
---
<?code-excerpt path-base="cookbook/networking/background_parsing/"?>
By default, Dart apps do all of their work on a single thread.
In many cases, this model simplifies coding and is fast enough
that it does not result in poor app performance or stuttering animations,
often called "jank."
However, you might need to perform an expensive computation,
such as parsing a very large JSON document.
If this work takes more than 16 milliseconds,
your users experience jank.
To avoid jank, you need to perform expensive computations
like this in the background.
On Android, this means scheduling work on a different thread.
In Flutter, you can use a separate [Isolate][].
This recipe uses the following steps:
1. Add the `http` package.
2. Make a network request using the `http` package.
3. Convert the response into a list of photos.
4. Move this work to a separate isolate.
## 1. Add the `http` package
First, add the [`http`][] package to your project.
The `http` package makes it easier to perform network
requests, such as fetching data from a JSON endpoint.
To add the `http` package as a dependency,
run `flutter pub add`:
```terminal
$ flutter pub add http
```
## 2. Make a network request
This example covers how to fetch a large JSON document
that contains a list of 5000 photo objects from the
[JSONPlaceholder REST API][],
using the [`http.get()`][] method.
<?code-excerpt "lib/main_step2.dart (fetchPhotos)"?>
```dart
Future<http.Response> fetchPhotos(http.Client client) async {
return client.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
}
```
{{site.alert.note}}
You're providing an `http.Client` to the function in this example.
This makes the function easier to test and use in different environments.
{{site.alert.end}}
## 3. Parse and convert the JSON into a list of photos
Next, following the guidance from the
[Fetch data from the internet][] recipe,
convert the `http.Response` into a list of Dart objects.
This makes the data easier to work with.
### Create a `Photo` class
First, create a `Photo` class that contains data about a photo.
Include a `fromJson()` factory method to make it easy to create a
`Photo` starting with a JSON object.
<?code-excerpt "lib/main_step3.dart (Photo)"?>
```dart
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
const Photo({
required this.albumId,
required this.id,
required this.title,
required this.url,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
```
### Convert the response into a list of photos
Now, use the following instructions to update the
`fetchPhotos()` function so that it returns a
`Future<List<Photo>>`:
1. Create a `parsePhotos()` function that converts the response
body into a `List<Photo>`.
2. Use the `parsePhotos()` function in the `fetchPhotos()` function.
<?code-excerpt "lib/main_step3.dart (parsePhotos)"?>
```dart
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed =
(jsonDecode(responseBody) as List).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
// Synchronously run parsePhotos in the main isolate.
return parsePhotos(response.body);
}
```
## 4. Move this work to a separate isolate
If you run the `fetchPhotos()` function on a slower device,
you might notice the app freezes for a brief moment as it parses and
converts the JSON. This is jank, and you want to get rid of it.
You can remove the jank by moving the parsing and conversion
to a background isolate using the [`compute()`][]
function provided by Flutter. The `compute()` function runs expensive
functions in a background isolate and returns the result. In this case,
run the `parsePhotos()` function in the background.
<?code-excerpt "lib/main.dart (fetchPhotos)"?>
```dart
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
```
## Notes on working with isolates
Isolates communicate by passing messages back and forth. These messages can
be primitive values, such as `null`, `num`, `bool`, `double`, or `String`, or
simple objects such as the `List<Photo>` in this example.
You might experience errors if you try to pass more complex objects,
such as a `Future` or `http.Response` between isolates.
As an alternate solution, check out the [`worker_manager`][] or
[`workmanager`][] packages for background processing.
[`worker_manager`]: {{site.pub}}/packages/worker_manager
[`workmanager`]: {{site.pub}}/packages/workmanager
## Complete example
<?code-excerpt "lib/main.dart"?>
```dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parsePhotos, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed =
(jsonDecode(responseBody) as List).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
const Photo({
required this.albumId,
required this.id,
required this.title,
required this.url,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Isolate Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: FutureBuilder<List<Photo>>(
future: fetchPhotos(http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Center(
child: Text('An error has occurred!'),
);
} else if (snapshot.hasData) {
return PhotosList(photos: snapshot.data!);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
class PhotosList extends StatelessWidget {
const PhotosList({super.key, required this.photos});
final List<Photo> photos;
@override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: photos.length,
itemBuilder: (context, index) {
return Image.network(photos[index].thumbnailUrl);
},
);
}
}
```
{:.site-mobile-screenshot}
[`compute()`]: {{site.api}}/flutter/foundation/compute.html
[Fetch data from the internet]: /cookbook/networking/fetch-data
[`http`]: {{site.pub-pkg}}/http
[`http.get()`]: {{site.pub-api}}/http/latest/http/get.html
[Isolate]: {{site.api}}/flutter/dart-isolate/Isolate-class.html
[JSONPlaceholder REST API]: https://jsonplaceholder.typicode.com
| website/src/cookbook/networking/background-parsing.md/0 | {
"file_path": "website/src/cookbook/networking/background-parsing.md",
"repo_id": "website",
"token_count": 2860
} | 1,238 |
---
title: Integration
description: >
A catalog of recipes for adding integration testing to your Flutter app.
---
{% include docs/cookbook-group-index.md %}
| website/src/cookbook/testing/integration/index.md/0 | {
"file_path": "website/src/cookbook/testing/integration/index.md",
"repo_id": "website",
"token_count": 45
} | 1,239 |
---
layout: toc
title: Persistence
description: Content covering persistence in Flutter apps.
---
| website/src/data-and-backend/persistence/index.md/0 | {
"file_path": "website/src/data-and-backend/persistence/index.md",
"repo_id": "website",
"token_count": 25
} | 1,240 |
---
title: Obfuscate Dart code
description: How to remove function and class names from your Dart binary.
---
<?code-excerpt path-base="deployment/obfuscate"?>
## What is code obfuscation?
[Code obfuscation][] is the process of modifying an
app's binary to make it harder for humans to understand.
Obfuscation hides function and class names in your
compiled Dart code, replacing each symbol with
another symbol, making it difficult for an attacker
to reverse engineer your proprietary app.
**Flutter's code obfuscation works
only on a [release build][].**
[Code obfuscation]: https://en.wikipedia.org/wiki/Obfuscation_(software)
[release build]: /testing/build-modes#release
## Limitations
Note that obfuscating your code does _not_
encrypt resources nor does it protect against
reverse engineering.
It only renames symbols with more obscure names.
{{site.alert.info}}
It is a **poor security practice** to
store secrets in an app.
{{site.alert.end}}
## Supported targets
The following build targets
support the obfuscation process
described on this page:
* `aar`
* `apk`
* `appbundle`
* `ios`
* `ios-framework`
* `ipa`
* `linux`
* `macos`
* `macos-framework`
* `windows`
{{site.alert.info}}
Web apps don't support obfuscation.
A web app can be [minified][], which provides a similar result.
When you build a release version of a Flutter web app,
the web compiler minifies the app. To learn more,
see [Build and release a web app][].
{{site.alert.end}}
[Build and release a web app]: /deployment/web
[minified]: https://en.wikipedia.org/wiki/Minification_(programming)
## Obfuscate your app
To obfuscate your app, use the `flutter build` command
in release mode
with the `--obfuscate` and `--split-debug-info` options.
The `--split-debug-info` option specifies the directory
where Flutter outputs debug files.
In the case of obfuscation, it outputs a symbol map.
For example:
```terminal
$ flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory>
```
Once you've obfuscated your binary, **save
the symbols file**. You need this if you later
want to de-obfuscate a stack trace.
{{site.alert.tip}}
The `--split-debug-info` option can also be used without `--obfuscate`
to extract Dart program symbols, reducing code size.
To learn more about app size, see [Measuring your app's size][].
{{site.alert.end}}
[Measuring your app's size]: /perf/app-size
For detailed information on these flags, run
the help command for your specific target, for example:
```terminal
$ flutter build apk -h
```
If these flags are not listed in the output,
run `flutter --version` to check your version of Flutter.
## Read an obfuscated stack trace
To debug a stack trace created by an obfuscated app,
use the following steps to make it human readable:
1. Find the matching symbols file.
For example, a crash from an Android arm64
device would need `app.android-arm64.symbols`.
1. Provide both the stack trace (stored in a file)
and the symbols file to the `flutter symbolize` command.
For example:
```terminal
$ flutter symbolize -i <stack trace file> -d out/android/app.android-arm64.symbols
```
For more information on the `symbolize` command,
run `flutter symbolize -h`.
## Read an obfuscated name
To make the name that an app obfuscated human readable,
use the following steps:
1. To save the name obfuscation map at app build time,
use `--extra-gen-snapshot-options=--save-obfuscation-map=/<your-path>`.
For example:
```terminal
$ flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory> --extra-gen-snapshot-options=--save-obfuscation-map=/<your-path>
```
1. To recover the name, use the generated obfuscation map.
The obfuscation map is a flat JSON array with pairs of
original names and obfuscated names. For example,
`["MaterialApp", "ex", "Scaffold", "ey"]`, where `ex`
is the obfuscated name of `MaterialApp`.
## Caveat
Be aware of the following when coding an app that will
eventually be an obfuscated binary.
* Code that relies on matching specific class, function,
or library names will fail.
For example, the following call to `expect()` won't
work in an obfuscated binary:
<?code-excerpt "lib/main.dart (Expect)"?>
```dart
expect(foo.runtimeType.toString(), equals('Foo'));
```
* Enum names are not obfuscated currently.
| website/src/deployment/obfuscate.md/0 | {
"file_path": "website/src/deployment/obfuscate.md",
"repo_id": "website",
"token_count": 1322
} | 1,241 |
---
title: Flutter for Xamarin.Forms developers
description: Learn how to apply Xamarin.Forms developer knowledge when building Flutter apps.
---
<?code-excerpt path-base="get-started/flutter-for/xamarin_devs"?>
This document is meant for Xamarin.Forms developers
looking to apply their existing knowledge
to build mobile apps with Flutter.
If you understand the fundamentals of the Xamarin.Forms framework,
then you can use this document as a jump start to Flutter development.
Your Android and iOS knowledge and skill set
are valuable when building with Flutter,
because Flutter relies on the native operating system configurations,
similar to how you would configure your native Xamarin.Forms projects.
The Flutter Frameworks is also similar to how you create a single UI,
that is used on multiple platforms.
This document can be used as a cookbook by jumping around
and finding questions that are most relevant to your needs.
## Project setup
### How does the app start?
For each platform in Xamarin.Forms,
you call the `LoadApplication` method,
which creates a new application and starts your app.
```csharp
LoadApplication(new App());
```
In Flutter, the default main entry point is
`main` where you load your Flutter app.
<?code-excerpt "lib/main.dart (Main)"?>
```dart
void main() {
runApp(const MyApp());
}
```
In Xamarin.Forms, you assign a `Page` to the
`MainPage` property in the `Application` class.
```csharp
public class App : Application
{
public App()
{
MainPage = new ContentPage
{
Content = new Label
{
Text = "Hello World",
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center
}
};
}
}
```
In Flutter, "everything is a widget", even the application itself.
The following example shows `MyApp`, a simple application `Widget`.
<?code-excerpt "lib/main.dart (MyApp)"?>
```dart
class MyApp extends StatelessWidget {
/// This widget is the root of your application.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Center(
child: Text(
'Hello World!',
textDirection: TextDirection.ltr,
),
);
}
}
```
### How do you create a page?
Xamarin.Forms has many types of pages;
`ContentPage` is the most common.
In Flutter, you specify an application widget that holds your root page.
You can use a [`MaterialApp`][] widget, which supports [Material Design][],
or you can use a [`CupertinoApp`][] widget, which supports an iOS-style app,
or you can use the lower level [`WidgetsApp`][],
which you can customize in any way you want.
[`CupertinoApp`]: {{site.api}}/flutter/cupertino/CupertinoApp-class.html
[`MaterialApp`]: {{site.api}}/flutter/material/MaterialApp-class.html
[`WidgetsApp`]: {{site.api}}/flutter/widgets/WidgetsApp-class.html
The following code defines the home page, a stateful widget.
In Flutter, all widgets are immutable,
but two types of widgets are supported: _Stateful_ and _Stateless_.
Examples of a stateless widget are titles, icons, or images.
The following example uses `MaterialApp`,
which holds its root page in the `home` property.
<?code-excerpt "lib/page.dart (MyApp)"?>
```dart
class MyApp extends StatelessWidget {
/// This widget is the root of your application.
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
```
From here, your actual first page is another `Widget`,
in which you create your state.
A _Stateful_ widget, such as `MyHomePage` below, consists of two parts.
The first part, which is itself immutable, creates a `State` object
that holds the state of the object. The `State` object persists over
the life of the widget.
<?code-excerpt "lib/page.dart (MyHomePage)"?>
```dart
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
```
The `State` object implements the `build()` method for the stateful widget.
When the state of the widget tree changes, call `setState()`,
which triggers a build of that portion of the UI.
Make sure to call `setState()` only when necessary,
and only on the part of the widget tree that has changed,
or it can result in poor UI performance.
<?code-excerpt "lib/page.dart (MyHomePageState)"?>
```dart
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Take the value from the MyHomePage object that was created by
// the App.build method, and use it to set the appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
```
In Flutter, the UI (also known as widget tree), is immutable,
meaning you can't change its state once it's built.
You change fields in your `State` class, then call `setState()`
to rebuild the entire widget tree again.
This way of generating UI is different from Xamarin.Forms,
but there are many benefits to this approach.
## Views
### What is the equivalent of a Page or Element in Flutter?
{{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}}
`ContentPage`, `TabbedPage`, `FlyoutPage` are all types of pages
you might use in a Xamarin.Forms application.
These pages would then hold `Element`s to display the various controls.
In Xamarin.Forms an `Entry` or `Button` are examples of an `Element`.
In Flutter, almost everything is a widget.
A `Page`, called a `Route` in Flutter, is a widget.
Buttons, progress bars, and animation controllers are all widgets.
When building a route, you create a widget tree.
Flutter includes the [Material Components][] library.
These are widgets that implement the [Material Design guidelines][].
Material Design is a flexible design system
[optimized for all platforms][], including iOS.
But Flutter is flexible and expressive enough
to implement any design language.
For example, on iOS, you can use the [Cupertino widgets][]
to produce an interface that looks like [Apple's iOS design language][].
### How do I update widgets?
In Xamarin.Forms, each `Page` or `Element` is a stateful class,
that has properties and methods.
You update your `Element` by updating a property,
and this is propagated down to the native control.
In Flutter, `Widget`s are immutable and you can't directly update them
by changing a property, instead you have to work with the widget's state.
This is where the concept of Stateful vs Stateless widgets comes from.
A `StatelessWidget` is just what it sounds like—
a widget with no state information.
`StatelessWidgets` are useful when the part of the user interface
you are describing doesn't depend on anything
other than the configuration information in the object.
For example, in Xamarin.Forms, this is similar
to placing an `Image` with your logo.
The logo is not going to change during runtime,
so use a `StatelessWidget` in Flutter.
If you want to dynamically change the UI based on data received
after making an HTTP call or a user interaction,
then you have to work with `StatefulWidget`
and tell the Flutter framework that
the widget's `State` has been updated,
so it can update that widget.
The important thing to note here is at the core
both stateless and stateful widgets behave the same.
They rebuild every frame, the difference is
the `StatefulWidget` has a `State` object
that stores state data across frames and restores it.
If you are in doubt, then always remember this rule: if a widget changes
(because of user interactions, for example) it's stateful.
However, if a widget reacts to change, the containing parent widget can
still be stateless if it doesn't itself react to change.
The following example shows how to use a `StatelessWidget`.
A common `StatelessWidget` is the `Text` widget.
If you look at the implementation of the `Text` widget
you'll find it subclasses `StatelessWidget`.
<?code-excerpt "lib/views.dart (Text)" replace="/return //g"?>
```dart
const Text(
'I like Flutter!',
style: TextStyle(fontWeight: FontWeight.bold),
);
```
As you can see, the `Text` widget has no state information associated with it,
it renders what is passed in its constructors and nothing more.
But, what if you want to make "I Like Flutter" change dynamically,
for example, when clicking a `FloatingActionButton`?
To achieve this, wrap the `Text` widget in a `StatefulWidget`
and update it when the user clicks the button,
as shown in the following example:
<?code-excerpt "lib/views_stateful.dart"?>
```dart
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
/// Default placeholder text
String textToShow = 'I Like Flutter';
void _updateText() {
setState(() {
// Update the text
textToShow = 'Flutter is Awesome!';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: Center(child: Text(textToShow)),
floatingActionButton: FloatingActionButton(
onPressed: _updateText,
tooltip: 'Update Text',
child: const Icon(Icons.update),
),
);
}
}
```
### How do I lay out my widgets? What is the equivalent of an XAML file?
In Xamarin.Forms, most developers write layouts in XAML,
though sometimes in C#.
In Flutter, you write your layouts with a widget tree in code.
The following example shows how to display a simple widget with padding:
<?code-excerpt "lib/padding.dart (Padding)"?>
```dart
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.only(left: 20, right: 30),
),
onPressed: () {},
child: const Text('Hello'),
),
),
);
}
```
You can view the layouts that Flutter has to offer in the
[widget catalog][].
### How do I add or remove an Element from my layout?
In Xamarin.Forms, you had to remove or add an `Element` in code.
This involved either setting the `Content` property or calling
`Add()` or `Remove()` if it was a list.
In Flutter, because widgets are immutable there is no direct equivalent.
Instead, you can pass a function to the parent that returns a widget,
and control that child's creation with a boolean flag.
The following example shows how to toggle between two widgets
when the user clicks the `FloatingActionButton`:
<?code-excerpt "lib/views.dart (AddRemoveElement)"?>
```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),
),
);
}
}
```
### How do I animate a widget?
In Xamarin.Forms, you create simple animations using ViewExtensions that
include methods such as `FadeTo` and `TranslateTo`.
You would use these methods on a view
to perform the required animations.
```xml
<Image Source="{Binding MyImage}" x:Name="myImage" />
```
Then in code behind, or a behavior, this would fade in the image,
over a 1-second period.
```csharp
myImage.FadeTo(0, 1000);
```
In Flutter, you animate widgets using the animation library
by wrapping widgets inside an animated widget.
Use an `AnimationController`, which is an `Animation<double>`
that can pause, seek, stop and reverse the animation.
It requires a `Ticker` that signals when vsync happens,
and produces a linear interpolation between 0 and 1
on each frame while it's running.
You then create one or 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';
void main() {
runApp(const FadeAppTest());
}
class FadeAppTest extends StatelessWidget {
/// This widget is the root of your application.
const FadeAppTest({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Fade Demo',
home: MyFadeTest(title: 'Fade Demo'),
);
}
}
class MyFadeTest extends StatefulWidget {
const MyFadeTest({super.key, required this.title});
final String title;
@override
State<MyFadeTest> createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
late final AnimationController controller;
late final CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
curve = CurvedAnimation(
parent: controller,
curve: Curves.easeIn,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: FadeTransition(
opacity: curve,
child: const FlutterLogo(size: 100),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
controller.forward();
},
tooltip: 'Fade',
child: const Icon(Icons.brush),
),
);
}
}
```
For more information, see [Animation & Motion widgets][],
the [Animations tutorial][], and the [Animations overview][].
### How do I draw/paint on the screen?
Xamarin.Forms never had a built-in way to draw directly on the screen.
Many would use SkiaSharp, if they needed a custom image drawn.
In Flutter, you have direct access to the Skia Canvas
and can easily draw on screen.
Flutter has two classes that help you draw to the canvas: `CustomPaint`
and `CustomPainter`, the latter of which implements your algorithm to draw to
the canvas.
To learn how to implement a signature painter in Flutter,
see Collin's answer on [Custom Paint][].
[Custom Paint]: {{site.so}}/questions/46241071/create-signature-area-for-mobile-app-in-dart-flutter
<?code-excerpt "lib/draw.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
SignatureState createState() => SignatureState();
}
class SignatureState extends State<Signature> {
List<Offset?> _points = <Offset?>[];
void _onPanUpdate(DragUpdateDetails details) {
setState(() {
final RenderBox referenceBox = context.findRenderObject() as RenderBox;
final Offset localPosition = referenceBox.globalToLocal(
details.globalPosition,
);
_points = List.from(_points)..add(localPosition);
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: _onPanUpdate,
onPanEnd: (details) => _points.add(null),
child: CustomPaint(
painter: SignaturePainter(_points),
size: Size.infinite,
),
);
}
}
class SignaturePainter extends CustomPainter {
const SignaturePainter(this.points);
final List<Offset?> points;
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()
..color = Colors.black
..strokeCap = StrokeCap.round
..strokeWidth = 5;
for (int i = 0; i < points.length - 1; i++) {
if (points[i] != null && points[i + 1] != null) {
canvas.drawLine(points[i]!, points[i + 1]!, paint);
}
}
}
@override
bool shouldRepaint(SignaturePainter oldDelegate) =>
oldDelegate.points != points;
}
```
### Where is the widget's opacity?
On Xamarin.Forms, all `VisualElement`s have an Opacity.
In Flutter, you need to wrap a widget in an
[`Opacity` widget][] to accomplish this.
### How do I build custom widgets?
In Xamarin.Forms, you typically subclass `VisualElement`,
or use a pre-existing `VisualElement`, to override and
implement methods that achieve the desired behavior.
In Flutter, build a custom widget by [composing][]
smaller widgets (instead of extending them).
It is somewhat similar to implementing a custom control
based off a `Grid` with numerous `VisualElement`s added in,
while extending with custom logic.
For example, how do you build a `CustomButton`
that takes a label in the constructor?
Create a CustomButton that composes a `ElevatedButton`
with a label, rather than by extending `ElevatedButton`:
<?code-excerpt "lib/custom_button.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_button.dart (UseCustomButton)"?>
```dart
@override
Widget build(BuildContext context) {
return const Center(
child: CustomButton('Hello'),
);
}
```
## Navigation
### How do I navigate between pages?
In Xamarin.Forms, the `NavigationPage` class
provides a hierarchical navigation experience
where the user is able to navigate through pages,
forwards and backwards.
Flutter has a similar implementation,
using a `Navigator` and `Routes`.
A `Route` is an abstraction for a `Page` of an app,
and a `Navigator` is a [widget][] that manages routes.
A route roughly maps to a `Page`.
The navigator works in a similar way to the Xamarin.Forms `NavigationPage`,
in that it can `push()` and `pop()` routes depending on
whether you want to navigate to, or back from, a view.
To navigate between pages, you have a couple options:
* Specify a `Map` of route names. (`MaterialApp`)
* Directly navigate to a route. (`WidgetsApp`)
The following example builds a `Map`.
<?code-excerpt "lib/navigation.dart (Main)"?>
```dart
void main() {
runApp(
MaterialApp(
home: const MyAppHome(), // becomes the route named '/'
routes: <String, WidgetBuilder>{
'/a': (context) => const MyPage(title: 'page A'),
'/b': (context) => const MyPage(title: 'page B'),
'/c': (context) => const MyPage(title: 'page C'),
},
),
);
}
```
Navigate to a route by pushing its name to the `Navigator`.
<?code-excerpt "lib/navigation.dart (PushNamed)"?>
```dart
Navigator.of(context).pushNamed('/b');
```
The `Navigator` is a stack that manages your app's routes.
Pushing a route to the stack moves to that route.
Popping a route from the stack, returns to the previous route.
This is done by awaiting on the `Future` returned by `push()`.
`async`/`await` is very similar to the .NET implementation
and is explained in more detail in [Async UI][].
For example, to start a `location` route
that lets the user select their location,
you might do the following:
<?code-excerpt "lib/navigation.dart (await)"?>
```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/navigation.dart (PopLocation)"?>
```dart
Navigator.of(context).pop({'lat': 43.821757, 'long': -79.226392});
```
### How do I navigate to another app?
In Xamarin.Forms, to send the user to another application,
you use a specific URI scheme, using `Device.OpenUrl("mailto://")`.
To implement this functionality in Flutter,
create a native platform integration, or use an [existing plugin][],
such as[`url_launcher`][], available with many other packages on [pub.dev][].
## Async UI
### What is the equivalent of Device.BeginOnMainThread() in Flutter?
Dart has a single-threaded execution model,
with support for `Isolate`s (a way to run Dart codes on another thread),
an event loop, and asynchronous programming.
Unless you spawn an `Isolate`,
your Dart code runs in the main UI thread
and is driven by an event loop.
Dart's single-threaded model doesn't mean you need to run everything
as a blocking operation that causes the UI to freeze.
Much like Xamarin.Forms, you need to keep the UI thread free.
You would use `async`/`await` to perform tasks,
where you must wait for the response.
In Flutter, use the asynchronous facilities that the Dart language provides,
also named `async`/`await`, to perform asynchronous work.
This is very similar to C# and should be very easy to use
for any Xamarin.Forms developer.
For example, you can run network code without causing the UI to hang by
using `async`/`await` and letting Dart do the heavy lifting:
<?code-excerpt "lib/data.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 awaited network call is done,
update the UI by calling `setState()`,
which triggers a rebuild of the widget subtree and updates the data.
The following example loads data asynchronously
and displays it in a `ListView`:
<?code-excerpt "lib/data.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 Android.
### How do you move work to a background thread?
Since Flutter is single threaded and runs an event loop,
you don't have to worry about thread management
or spawning background threads.
This is very similar to Xamarin.Forms.
If you're doing I/O-bound work, such as disk access or a network call,
then you can safely use `async`/`await` and you're all set.
If, on the other hand, you need to do computationally intensive work
that keeps the CPU busy,
you want to move it to an `Isolate` to avoid blocking the event loop,
like you would keep _any_ sort of work out of the main thread.
This is similar to when you move things to a different
thread via `Task.Run()` in Xamarin.Forms.
For I/O-bound work, declare the function as an `async` function,
and `await` on long-running tasks inside the function:
<?code-excerpt "lib/data.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 would typically do network or database calls,
which are both I/O operations.
However, there are times when you might be processing
a large amount of data and your UI hangs.
In Flutter, use `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 is a difference between `Task.Run()`.
This means you can't access variables from the main thread,
or update your UI by calling `setState()`.
The following example shows, in a simple isolate,
how to share data back to the main thread to update the UI.
<?code-excerpt "lib/isolates.dart (SimpleIsolate)"?>
```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() {
if (showLoadingDialog) {
return getProgressDialog();
}
return getListView();
}
Widget getProgressDialog() {
return const Center(child: CircularProgressIndicator());
}
ListView getListView() {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return getRow(index);
},
);
}
Widget getRow(int index) {
return Padding(
padding: const EdgeInsets.all(10),
child: Text('Row ${data[index]['title']}'),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: getBody(),
);
}
}
```
### How do I make network requests?
In Xamarin.Forms you would use `HttpClient`.
Making a network call in Flutter is easy
when you use the popular [`http` package][].
This abstracts away a lot of the networking
that you might normally implement yourself,
making it simple to make network calls.
To use the `http` package, add it to your dependencies in `pubspec.yaml`:
```yaml
dependencies:
http: ^1.1.0
```
To make a network request,
call `await` on the `async` function `http.get()`:
<?code-excerpt "lib/data.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);
});
}
```
### How do I show the progress for a long-running task?
In Xamarin.Forms you would typically create a loading indicator,
either directly in XAML or through a 3rd party plugin such as AcrDialogs.
In Flutter, use a `ProgressIndicator` widget.
Show the progress programmatically by controlling
when it's rendered through a boolean flag.
Tell Flutter to update its state before your long-running task starts,
and hide it after it ends.
In the example below, the build function is separated into three different
functions. If `showLoadingDialog` is `true`
(when `widgets.length == 0`), then render the `ProgressIndicator`.
Otherwise, render the `ListView` with the data returned from a network call.
<?code-excerpt "lib/loading.dart"?>
```dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Map<String, dynamic>> data = <Map<String, dynamic>>[];
@override
void initState() {
super.initState();
loadData();
}
bool get showLoadingDialog => data.isEmpty;
Future<void> loadData() async {
final Uri dataURL = Uri.parse(
'https://jsonplaceholder.typicode.com/posts',
);
final http.Response response = await http.get(dataURL);
setState(() {
data = jsonDecode(response.body);
});
}
Widget getBody() {
if (showLoadingDialog) {
return getProgressDialog();
}
return getListView();
}
Widget getProgressDialog() {
return const Center(child: CircularProgressIndicator());
}
ListView getListView() {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return getRow(index);
},
);
}
Widget getRow(int index) {
return Padding(
padding: const EdgeInsets.all(10),
child: Text('Row ${data[index]['title']}'),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: getBody(),
);
}
}
```
## Project structure & resources
### Where do I store my image files?
Xamarin.Forms has no platform independent way of storing images,
you had to place images in the iOS `xcasset` folder,
or on Android in the various `drawable` folders.
While Android and iOS treat resources and assets as distinct items,
Flutter apps have only assets.
All resources that would live in the
`Resources/drawable-*` folders on Android,
are placed in an assets' folder for Flutter.
Flutter follows a simple density-based format like iOS.
Assets might be `1.0x`, `2.0x`, `3.0x`, or any other multiplier.
Flutter doesn't have `dp`s but there are logical pixels,
which are basically the same as device-independent pixels.
Flutter's [`devicePixelRatio`][] expresses the ratio
of physical pixels in a single logical pixel.
The equivalent to Android's density buckets are:
| Android density qualifier | Flutter pixel ratio |
|---------------------------|---------------------|
| `ldpi` | `0.75x` |
| `mdpi` | `1.0x` |
| `hdpi` | `1.5x` |
| `xhdpi` | `2.0x` |
| `xxhdpi` | `3.0x` |
| `xxxhdpi` | `4.0x` |
Assets are located in any arbitrary folder—
Flutter has no predefined folder structure.
You declare the assets (with location)
in the `pubspec.yaml` file, and Flutter picks them up.
To add a new image asset called `my_icon.png` to our Flutter project,
for example, and deciding that it should live in a folder we
arbitrarily called `images`, you would put the base image (1.0x)
in the `images` folder, and all the other variants in sub-folders
called with the appropriate ratio multiplier:
```
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, you'll need to declare these images in your `pubspec.yaml` file:
```yaml
assets:
- images/my_icon.jpeg
```
You can directly access your images in an `Image.asset` widget:
<?code-excerpt "lib/images.dart (ImageAsset)"?>
```dart
@override
Widget build(BuildContext context) {
return Image.asset('images/my_icon.png');
}
```
or using `AssetImage`:
<?code-excerpt "lib/images.dart (AssetImage)"?>
```dart
@override
Widget build(BuildContext context) {
return const Image(
image: AssetImage('images/my_image.png'),
);
}
```
More detailed information can be found in [Adding assets and images][].
### Where do I store strings? How do I handle localization?
Unlike .NET which has `resx` files,
Flutter doesn't currently have a dedicated system for handling strings.
At the moment, the best practice is to declare your copy text
in a class as static fields and access them from there. For example:
<?code-excerpt "lib/strings.dart (StringsClass)"?>
```dart
class Strings {
static const String welcomeMessage = 'Welcome To Flutter';
}
```
You can access your strings as such:
<?code-excerpt "lib/strings.dart (AccessString)" replace="/return 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/strings.dart (Localization)"?>
```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.
### Where is my project file?
In Xamarin.Forms you will have a `csproj` file.
The closest equivalent in Flutter is pubspec.yaml,
which contains package dependencies and various project details.
Similar to .NET Standard,
files within the same directory are considered part of the project.
### What is the equivalent of Nuget? How do I add dependencies?
In the .NET ecosystem, native Xamarin projects and Xamarin.Forms projects
had access to Nuget and the built-in package management system.
Flutter apps contain a native Android app, native iOS app and Flutter app.
In Android, you add dependencies by adding to your Gradle build script.
In iOS, you add dependencies by adding to your `Podfile`.
Flutter uses Dart's own build system, and the Pub package manager.
The tools delegate the building of the native Android and iOS wrapper apps
to the respective build systems.
In general, use `pubspec.yaml` to declare
external dependencies to use in Flutter.
A good place to find Flutter packages is on [pub.dev][].
## Application lifecycle
### How do I listen to application lifecycle events?
In Xamarin.Forms, you have an `Application`
that contains `OnStart`, `OnResume` and `OnSleep`.
In Flutter, you can instead listen to similar lifecycle events
by hooking into the `WidgetsBinding` observer and listening to
the `didChangeAppLifecycleState()` change event.
The observable lifecycle events are:
`inactive`
: The application is in an inactive state and is not receiving user input.
This event is iOS only.
`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.
This event is Android only.
For more details on the meaning of these states,
see the [`AppLifecycleStatus` documentation][].
[`AppLifecycleStatus` documentation]: {{site.api}}/flutter/dart-ui/AppLifecycleState.html
## Layouts
### What is the equivalent of a StackLayout?
In Xamarin.Forms you can create a `StackLayout`
with an `Orientation` of horizontal or vertical.
Flutter has a similar approach,
however you would use the `Row` or `Column` widgets.
If you notice the two code samples are identical
except the `Row` and `Column` widget.
The children are the same and this feature
can be exploited to develop rich layouts
that can change overtime with the same children.
<?code-excerpt "lib/layouts.dart (Row)"?>
```dart
@override
Widget build(BuildContext context) {
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Row One'),
Text('Row Two'),
Text('Row Three'),
Text('Row Four'),
],
);
}
```
<?code-excerpt "lib/layouts.dart (Column)"?>
```dart
@override
Widget build(BuildContext context) {
return const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Column One'),
Text('Column Two'),
Text('Column Three'),
Text('Column Four'),
],
);
```
### What is the equivalent of a Grid?
The closest equivalent of a `Grid` would be a `GridView`.
This is much more powerful than what you are used to in Xamarin.Forms.
A `GridView` provides automatic scrolling when the
content exceeds its viewable space.
<?code-excerpt "lib/layouts.dart (Grid)"?>
```dart
@override
Widget build(BuildContext context) {
return GridView.count(
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this would produce 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the list.
children: List<Widget>.generate(
100,
(index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headlineMedium,
),
);
},
),
);
}
```
You might have used a `Grid` in Xamarin.Forms
to implement widgets that overlay other widgets.
In Flutter, you accomplish this with the `Stack` widget.
This sample creates two icons that overlap each other.
<?code-excerpt "lib/layouts.dart (Stack)"?>
```dart
@override
Widget build(BuildContext context) {
return const Stack(
children: <Widget>[
Icon(
Icons.add_box,
size: 24,
color: Colors.black,
),
Positioned(
left: 10,
child: Icon(
Icons.add_circle,
size: 24,
color: Colors.black,
),
),
],
);
}
```
### What is the equivalent of a ScrollView?
In Xamarin.Forms, a `ScrollView` wraps around a `VisualElement`,
and if the content is larger than the device screen, it scrolls.
In Flutter, the closest match is the `SingleChildScrollView` widget.
You simply fill the Widget with the content that you want to be scrollable.
<?code-excerpt "lib/layouts.dart (ScrollView)"?>
```dart
@override
Widget build(BuildContext context) {
return const SingleChildScrollView(
child: Text('Long Content'),
);
}
```
If you have many items you want to wrap in a scroll,
even of different `Widget` types, you might want to use a `ListView`.
This might seem like overkill, but in Flutter this is
far more optimized and less intensive than a Xamarin.Forms `ListView`,
which is backing on to platform specific controls.
<?code-excerpt "lib/layouts.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'),
],
);
}
```
### How do I handle landscape transitions in Flutter?
Landscape transitions can be handled automatically by setting the
`configChanges` property in the AndroidManifest.xml:
```xml
<activity android:configChanges="orientation|screenSize" />
```
## Gesture detection and touch event handling
### How do I add GestureRecognizers to a widget in Flutter?
In Xamarin.Forms, `Element`s might contain a click event you can attach to.
Many elements also contain a `Command` that is tied to this event.
Alternatively you would use the `TapGestureRecognizer`.
In Flutter there are two very similar ways:
1. If the widget supports event detection, pass a function to it and
handle it in the function. For example, the ElevatedButton has an
`onPressed` parameter:
<?code-excerpt "lib/gestures.dart (ElevatedButton)"?>
```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/gestures.dart (GestureDetector)"?>
```dart
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onTap: () {
developer.log('tap');
},
child: const FlutterLogo(size: 200),
),
),
);
}
}
```
### How do I handle other gestures on widgets?
In Xamarin.Forms you would add a `GestureRecognizer` to the `View`.
You would normally be limited to `TapGestureRecognizer`,
`PinchGestureRecognizer`, `PanGestureRecognizer`, `SwipeGestureRecognizer`,
`DragGestureRecognizer` and `DropGestureRecognizer` unless you built your own.
In Flutter, using the GestureDetector,
you can listen to a wide range of Gestures such as:
* Tap
`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 tap
`onDoubleTap`
: The user tapped the screen at the same location twice
in quick succession.
* Long press
`onLongPress`
: A pointer has remained in contact with the screen
at the same location for a long period of time.
* Vertical drag
`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 drag
`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 and was moving at a specific velocity
when it stopped contacting the screen.
The following example shows a `GestureDetector`
that rotates the Flutter logo on a double tap:
<?code-excerpt "lib/gestures.dart (RotatingFlutterDetector)"?>
```dart
class RotatingFlutterDetector extends StatefulWidget {
const RotatingFlutterDetector({super.key});
@override
State<RotatingFlutterDetector> createState() =>
_RotatingFlutterDetectorState();
}
class _RotatingFlutterDetectorState extends State<RotatingFlutterDetector>
with SingleTickerProviderStateMixin {
late final AnimationController controller;
late final CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 2000),
vsync: this,
);
curve = CurvedAnimation(parent: controller, curve: Curves.easeIn);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onDoubleTap: () {
if (controller.isCompleted) {
controller.reverse();
} else {
controller.forward();
}
},
child: RotationTransition(
turns: curve,
child: const FlutterLogo(size: 200),
),
),
),
);
}
}
```
## Listviews and adapters
### What is the equivalent to a ListView in Flutter?
The equivalent to a `ListView` in Flutter is … a `ListView`!
In a Xamarin.Forms `ListView`, you create a `ViewCell`
and possibly a `DataTemplateSelector`and pass it into the `ListView`,
which renders each row with what your
`DataTemplateSelector` or `ViewCell` returns.
However, you often have to make sure you turn on Cell Recycling
otherwise you will run into memory issues and slow scrolling speeds.
Due to Flutter's immutable widget pattern,
you pass a list of widgets to your `ListView`,
and Flutter takes care of making sure that scrolling is fast and smooth.
<?code-excerpt "lib/listview.dart"?>
```dart
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatelessWidget {
const SampleAppPage({super.key});
List<Widget> _getListData() {
return List<Widget>.generate(
100,
(index) => Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $index'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: ListView(children: _getListData()),
);
}
}
```
### How do I know which list item has been clicked?
In Xamarin.Forms, the ListView has an `ItemTapped` method
to find out which item was clicked.
There are many other techniques you might have used
such as checking when `SelectedItem` or `EventToCommand`
behaviors change.
In Flutter, use the touch handling provided by the passed-in widgets.
<?code-excerpt "lib/listview_item_clicked.dart"?>
```dart
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Widget> _getListData() {
return List<Widget>.generate(
100,
(index) => GestureDetector(
onTap: () {
developer.log('Row $index tapped');
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $index'),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: ListView(children: _getListData()),
);
}
}
```
### How do I update a ListView dynamically?
In Xamarin.Forms, if you bound the
`ItemsSource` property to an `ObservableCollection`,
you would just update the list in your ViewModel.
Alternatively, you could assign a new `List` to the `ItemSource` property.
In Flutter, things work a little differently.
If you update the list of widgets inside a `setState()` method,
you would quickly see that your data did not change visually.
This is because when `setState()` is called,
the Flutter rendering engine looks at the widget tree
to see if anything has changed.
When it gets to your `ListView`, it performs a `==` check,
and determines that the two `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/dynamic_listview.dart"?>
```dart
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Widget> widgets = <Widget>[];
@override
void initState() {
super.initState();
for (int i = 0; i < 100; i++) {
widgets.add(getRow(i));
}
}
Widget getRow(int index) {
return GestureDetector(
onTap: () {
setState(() {
widgets = List<Widget>.from(widgets);
widgets.add(getRow(widgets.length));
developer.log('Row $index');
});
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $index'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: ListView(children: widgets),
);
}
}
```
The recommended, efficient, and effective way to build a list
uses a `ListView.Builder`.
This method is great when you have a dynamic list
or a list with very large amounts of data.
This is essentially the equivalent of RecyclerView on Android,
which automatically recycles list elements for you:
<?code-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 {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Widget> widgets = [];
@override
void initState() {
super.initState();
for (int i = 0; i < 100; i++) {
widgets.add(getRow(i));
}
}
Widget getRow(int index) {
return GestureDetector(
onTap: () {
setState(() {
widgets.add(getRow(widgets.length));
developer.log('Row $index');
});
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $index'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: ListView.builder(
itemCount: widgets.length,
itemBuilder: (context, index) {
return getRow(index);
},
),
);
}
}
```
Instead of creating a `ListView`, create a `ListView.builder`
that takes two key parameters: the initial length of the list,
and an item builder function.
The item builder function is similar to the `getView` function
in an Android adapter; it takes a position,
and returns the row you want rendered at that position.
Finally, but most importantly, notice that the `onTap()` function
doesn't recreate the list anymore, but instead adds to it.
For more information, see
[Your first Flutter app][first_codelab] codelab.
## Working with text
### How do I set custom fonts on my text widgets?
In Xamarin.Forms, you would have to add a custom font in each native project.
Then, in your `Element` you would assign this font name
to the `FontFamily` attribute using `filename#fontname`
and just `fontname` for iOS.
In Flutter, place the font file in a folder and reference it
in the `pubspec.yaml` file, similar to how you import images.
```yaml
fonts:
- family: MyCustomFont
fonts:
- asset: fonts/MyCustomFont.ttf
- style: italic
```
Then assign the font to your `Text` widget:
<?code-excerpt "lib/strings.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'),
),
),
);
}
```
### How do I style my text widgets?
Along with fonts, you can customize other styling elements on a `Text` widget.
The style parameter of a `Text` widget takes a `TextStyle` object,
where you can customize many parameters, such as:
* `color`
* `decoration`
* `decorationColor`
* `decorationStyle`
* `fontFamily`
* `fontSize`
* `fontStyle`
* `fontWeight`
* `hashCode`
* `height`
* `inherit`
* `letterSpacing`
* `textBaseline`
* `wordSpacing`
## Form input
### How do I retrieve user input?
Xamarin.Forms `element`s allow you to directly query the `element`
to determine the state of its properties,
or whether it's bound to a property in a `ViewModel`.
Retrieving information in Flutter is handled by specialized widgets
and is different from how you are used to.
If you have a `TextField`or a `TextFormField`,
you can supply a [`TextEditingController`][]
to retrieve user input:
<?code-excerpt "lib/form.dart"?>
```dart
import 'package:flutter/material.dart';
class MyForm extends StatefulWidget {
const MyForm({super.key});
@override
State<MyForm> createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
/// Create a text controller and use it to retrieve the current value
/// of the TextField.
final TextEditingController myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when disposing of the widget.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Retrieve Text Input')),
body: Padding(
padding: const EdgeInsets.all(16),
child: TextField(controller: myController),
),
floatingActionButton: FloatingActionButton(
// When the user presses the button, show an alert dialog with the
// text that the user has typed into our text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text that the user has entered using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: const Icon(Icons.text_fields),
),
);
}
}
```
You can find more information and the full code listing in
[Retrieve the value of a text field][],
from the [Flutter cookbook][].
### What is the equivalent of a Placeholder on an Entry?
In Xamarin.Forms, some `Elements` support a `Placeholder` property
that you can assign a value to. For example:
```xml
<Entry Placeholder="This is a hint">
```
In Flutter, you can easily show a "hint" or a placeholder text
for your input by adding an `InputDecoration` object
to the `decoration` constructor parameter for the text widget.
<?code-excerpt "lib/input_decoration.dart (HintText)" replace="/child: //g"?>
```dart
TextField(
decoration: InputDecoration(hintText: 'This is a hint'),
),
```
### How do I show validation errors?
With Xamarin.Forms, if you wished to provide a visual hint of a
validation error, you would need to create new properties and
`VisualElement`s surrounding the `Element`s that had validation errors.
In Flutter, you pass through an InputDecoration object to the
decoration constructor for the text widget.
However, you don't want to start off by showing an error.
Instead, when the user has entered invalid data,
update the state, and pass a new `InputDecoration` object.
<?code-excerpt "lib/validation.dart"?>
```dart
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
String? _errorText;
String? _getErrorText() {
return _errorText;
}
bool isEmail(String em) {
const String emailRegexp =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|'
r'(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|'
r'(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
final RegExp regExp = RegExp(emailRegexp);
return regExp.hasMatch(em);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: Center(
child: TextField(
onSubmitted: (text) {
setState(() {
if (!isEmail(text)) {
_errorText = 'Error: This is not an email';
} else {
_errorText = null;
}
});
},
decoration: InputDecoration(
hintText: 'This is a hint',
errorText: _getErrorText(),
),
),
),
);
}
}
```
## Flutter plugins
## Interacting with hardware, third party services, and the platform
### How do I interact with the platform, and with platform native code?
Flutter doesn't run code directly on the underlying platform;
rather, the Dart code that makes up a Flutter app is run natively
on the device, "sidestepping" the SDK provided by the platform.
That means, for example, when you perform a network request in Dart,
it runs directly in the Dart context.
You don't use the Android or iOS APIs
you normally take advantage of when writing native apps.
Your Flutter app is still hosted in a native app's
`ViewController` or `Activity` as a view,
but you don't have direct access to this, or the native framework.
This doesn't mean Flutter apps can't interact with those native APIs,
or with any native code you have. Flutter provides [platform channels][]
that communicate and exchange data with the
`ViewController` or `Activity` that hosts your Flutter view.
Platform channels are essentially an asynchronous messaging mechanism
that bridges the Dart code with the host `ViewController`
or `Activity` and the iOS or Android framework it runs on.
You can use platform channels to execute a method on the native side,
or to retrieve some data from the device's sensors, for example.
In addition to directly using platform channels,
you can use a variety of pre-made [plugins][]
that encapsulate the native and Dart code for a specific goal.
For example, you can use a plugin to access
the camera roll and the device camera directly from Flutter,
without having to write your own integration.
Plugins are found on [pub.dev][],
Dart and Flutter's open source package repository.
Some packages might support native integrations on iOS,
or Android, or both.
If you can't find a plugin on pub.dev that fits your needs,
you can [write your own][], and [publish it on pub.dev][].
### How do I access the GPS sensor?
Use the [`geolocator`][] community plugin.
### How do I access the camera?
The [`camera`][] plugin is popular for accessing the camera.
### How do I log in with Facebook?
To log in with Facebook, use the
[`flutter_facebook_login`][] community plugin.
### How do I use Firebase features?
Most Firebase functions are covered by [first party plugins][].
These plugins are first-party integrations, maintained by the Flutter team:
* [`google_mobile_ads`][] for Google Mobile Ads for Flutter
* [`firebase_analytics`][] for Firebase Analytics
* [`firebase_auth`][] for Firebase Auth
* [`firebase_database`][] for Firebase RTDB
* [`firebase_storage`][] for Firebase Cloud Storage
* [`firebase_messaging`][] for Firebase Messaging (FCM)
* [`flutter_firebase_ui`][] for quick Firebase Auth integrations
(Facebook, Google, Twitter and email)
* [`cloud_firestore`][] for Firebase Cloud Firestore
You can also find some third-party Firebase plugins on pub.dev
that cover areas not directly covered by the first-party plugins.
### How do I build my own custom native integrations?
If there is platform-specific functionality that Flutter
or its community plugins are missing,
you can build your own following the
[developing packages and plugins][] page.
Flutter's plugin architecture, in a nutshell,
is much like using an Event bus in Android:
you fire off a message and let the receiver process and emit a result
back to you. In this case, the receiver is code running on the native side
on Android or iOS.
## Themes (Styles)
### How do I theme my app?
Flutter comes with a beautiful, built-in implementation of Material Design,
which handles much of the styling and theming needs
that you would typically do.
Xamarin.Forms does have a global `ResourceDictionary`
where you can share styles across your app.
Alternatively, there is Theme support currently in preview.
In Flutter, you declare themes in the top level widget.
To take full advantage of Material Components in your app,
you can declare a top level widget `MaterialApp`
as the entry point to your application.
`MaterialApp` is a convenience widget
that wraps a number of widgets that are commonly required
for applications implementing Material Design.
It builds upon a `WidgetsApp` by adding Material-specific functionality.
You can also use a `WidgetsApp` as your app widget,
which provides some of the same functionality,
but is not as rich as `MaterialApp`.
To customize the colors and styles of any child components,
pass a `ThemeData` object to the `MaterialApp` widget.
For example, in the following code,
the color scheme from seed is set to deepPurple and text selection color is red.
<?code-excerpt "lib/theme.dart (Theme)"?>
```dart
class SampleApp extends StatelessWidget {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sample App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
textSelectionTheme:
const TextSelectionThemeData(selectionColor: Colors.red),
),
home: const SampleAppPage(),
);
}
}
```
## Databases and local storage
### How do I access shared preferences or UserDefaults?
Xamarin.Forms developers will likely be familiar with the
`Xam.Plugins.Settings` plugin.
In Flutter, access equivalent functionality using the
[`shared_preferences`][] plugin. This plugin wraps the
functionality of both `UserDefaults` and the Android
equivalent, `SharedPreferences`.
### How do I access SQLite in Flutter?
In Xamarin.Forms most applications would use the `sqlite-net-pcl`
plugin to access SQLite databases.
In Flutter, on macOS, Android, and iOS,
access this functionality using the
[`sqflite`][] plugin.
## Debugging
### What tools can I use to debug my app in Flutter?
Use the [DevTools][] suite for debugging Flutter or Dart apps.
DevTools includes support for profiling, examining the heap,
inspecting the widget tree, logging diagnostics, debugging,
observing executed lines of code,
debugging memory leaks and memory fragmentation.
For more information, see the [DevTools][] documentation.
## Notifications
### How do I set up push notifications?
In Android, you use Firebase Cloud Messaging to set up
push notifications for your app.
In Flutter, access this functionality using the
[`firebase_messaging`][] plugin.
For more information on using the Firebase Cloud Messaging API, see the
[`firebase_messaging`][] plugin documentation.
[Adding assets and images]: /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/
[arb]: {{site.github}}/google/app-resource-bundle
[Async UI]: #async-ui
[`cloud_firestore`]: {{site.pub}}/packages/cloud_firestore
[composing]: /resources/architectural-overview#composition
[Cupertino widgets]: /ui/widgets/cupertino
[`devicePixelRatio`]: {{site.api}}/flutter/dart-ui/FlutterView/devicePixelRatio.html
[developing packages and plugins]: /packages-and-plugins/developing-packages
[DevTools]: /tools/devtools/overview
[existing plugin]: {{site.pub}}/flutter
[`google_mobile_ads`]: {{site.pub}}/packages/google_mobile_ads
[`firebase_analytics`]: {{site.pub}}/packages/firebase_analytics
[`firebase_auth`]: {{site.pub}}/packages/firebase_auth
[`firebase_database`]: {{site.pub}}/packages/firebase_database
[`firebase_messaging`]: {{site.pub}}/packages/firebase_messaging
[`firebase_storage`]: {{site.pub}}/packages/firebase_storage
[first party plugins]: {{site.pub}}/flutter/packages?q=firebase
[Flutter cookbook]: /cookbook
[`flutter_facebook_login`]: {{site.pub}}/packages/flutter_facebook_login
[`flutter_firebase_ui`]: {{site.pub}}/packages/flutter_firebase_ui
[`geolocator`]: {{site.pub}}/packages/geolocator
[`camera`]: {{site.pub-pkg}}/camera
[`http` package]: {{site.pub}}/packages/http
[internationalization guide]: /ui/accessibility-and-internationalization/internationalization
[`intl`]: {{site.pub}}/packages/intl
[`intl_translation`]: {{site.pub}}/packages/intl_translation
[Introduction to declarative UI]: /get-started/flutter-for/declarative
[`Localizations`]: {{site.api}}/flutter/widgets/Localizations-class.html
[Material Components]: /ui/widgets/material
[Material Design]: {{site.material}}/styles
[Material Design guidelines]: {{site.material}}/styles
[`Opacity` widget]: {{site.api}}/flutter/widgets/Opacity-class.html
[optimized for all platforms]: {{site.material2}}/design/platform-guidance/cross-platform-adaptation.html#cross-platform-guidelines
[platform channels]: /platform-integration/platform-channels
[plugins]: /packages-and-plugins/using-packages
[pub.dev]: {{site.pub}}
[publish it on pub.dev]: /packages-and-plugins/developing-packages#publish
[Retrieve the value of a text field]: /cookbook/forms/retrieve-input
[`shared_preferences`]: {{site.pub}}/packages/shared_preferences
[`sqflite`]: {{site.pub}}/packages/sqflite
[`TextEditingController`]: {{site.api}}/flutter/widgets/TextEditingController-class.html
[`url_launcher`]: {{site.pub}}/packages/url_launcher
[widget]: /resources/architectural-overview#widgets
[widget catalog]: /ui/widgets/layout
[`Window.locale`]: {{site.api}}/flutter/dart-ui/Window/locale.html
[first_codelab]: {{site.codelabs}}/codelabs/flutter-codelab-first
[write your own]: /packages-and-plugins/developing-packages
| website/src/get-started/flutter-for/xamarin-forms-devs.md/0 | {
"file_path": "website/src/get-started/flutter-for/xamarin-forms-devs.md",
"repo_id": "website",
"token_count": 24617
} | 1,242 |
## Get the Flutter SDK
{% include docs/china-notice.md %}
{% include_relative_help-link.md location='win-get-sdk' %}
1. Download the following installation bundle to get the latest
{{site.sdk.channel}} release of the Flutter SDK:
[(loading...)](#){:.download-latest-link-{{os}}.btn.btn-primary}
For other release channels, and older builds,
check out the [SDK archive][].
1. Extract the zip file and place the contained `flutter`
in the desired installation location for the Flutter SDK
(for example, `%USERPROFILE%\flutter`, `C:\dev\flutter`).
{{site.alert.warning}}
Do not install Flutter to a path that contains special
characters or spaces.
{{site.alert.end}}
{{site.alert.warning}}
Do not install Flutter in a directory like
`C:\Program Files\` that requires elevated privileges.
{{site.alert.end}}
You are now ready to run Flutter commands in the Flutter Console.
### Update your path
{% include_relative_help-link.md location='win-path' section='#unable-to-find-the-flutter-command' %}
If you wish to run Flutter commands in the regular Windows console,
take these steps to add Flutter to the `PATH` environment variable:
* From the Start search bar, enter 'env'
and select **Edit environment variables for your account**.
* Under **User variables** check if there is an entry called **Path**:
* If the entry exists, append the full path to `flutter\bin` using
`;` as a separator from existing values.
* If the entry doesn't exist,
create a new user variable named `Path` with
the full path to `flutter\bin` as its value.
You have to close and reopen any existing console windows
for these changes to take effect.
{% include docs/dart-tool-win.md %}
### Run `flutter doctor`
{% include_relative_help-link.md location='win-doctor' %}
From a console window that has the Flutter directory in the
path (see above), run the following command to see if there
are any platform dependencies you need to complete the setup:
```batchfile
C:\src\flutter>flutter doctor
```
This command checks your environment and displays a report of the status
of your Flutter installation. Check the output carefully for other
software you might need to install or further tasks to perform
(shown in **bold** text).
For example:
<pre>
[-] Android toolchain - develop for Android devices
• Android SDK at C:\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. Once you have installed any missing
dependencies, you can run the `flutter doctor` command again to
verify that you've set everything up correctly.
{{site.alert.note}}
If `flutter doctor` returns that either the Flutter plugin
or Dart plugin of Android Studio are not installed, move
on to [Set up an editor][] to resolve this issue.
{{site.alert.end}}
{% include_relative_analytics.md %}
[SDK archive]: /release/archive
[Set up an editor]: /get-started/editor?tab=androidstudio
| website/src/get-started/install/_deprecated/_get-sdk-win.md/0 | {
"file_path": "website/src/get-started/install/_deprecated/_get-sdk-win.md",
"repo_id": "website",
"token_count": 919
} | 1,243 |
---
title: Start building Flutter native desktop apps on macOS
description: Configure your system to develop Flutter desktop apps on macOS.
short-title: Make macOS desktop apps
target: desktop
config: macOSDesktop
devos: macOS
next:
title: Create a test app
path: /get-started/test-drive
---
{% include docs/install/reqs/macos/base.md
os=page.devos
target=page.target
-%}
{% include docs/install/flutter-sdk.md
os=page.devos
target=page.target
terminal='Terminal'
-%}
{% include docs/install/compiler/xcode.md
os=page.devos
target=page.target
attempt='first'
-%}
{% include docs/install/flutter-doctor.md
devos=page.devos
target=page.target
config=page.config
-%}
{% include docs/install/next-steps.md
devos=page.devos
target=page.target
config=page.config
-%}
| website/src/get-started/install/macos/desktop.md/0 | {
"file_path": "website/src/get-started/install/macos/desktop.md",
"repo_id": "website",
"token_count": 305
} | 1,244 |
---
title: Developing packages & plugins
short-title: Developing
description: How to write packages and plugins for Flutter.
---
## Package introduction
Packages enable the creation of modular code that can be shared easily.
A minimal package consists of the following:
**`pubspec.yaml`**
: A metadata file that declares the package name,
version, author, and so on.
**`lib`**
: The `lib` directory contains the public code in
the package, minimally a single `<package-name>.dart` file.
{{site.alert.note}}
For a list of dos and don'ts when writing an effective plugin,
see the Medium article by Mehmet Fidanboylu,
[Writing a good plugin][].
{{site.alert.end}}
### Package types {#types}
Packages can contain more than one kind of content:
**Dart packages**
: General packages written in Dart,
for example the [`path`][] package.
Some of these might contain Flutter specific
functionality and thus have a dependency on the
Flutter framework, restricting their use to Flutter only,
for example the [`fluro`][] package.
**Plugin packages**
: A specialized Dart package that contains an API written in
Dart code combined with one or more platform-specific
implementations.
Plugin packages can be written for Android
(using Kotlin or Java), iOS (using Swift or Objective-C),
web, macOS, Windows, or Linux, or any combination
thereof.
A concrete example is the [`url_launcher`][] plugin package.
To see how to use the `url_launcher` package, and how it
was extended to implement support for web,
see the Medium article by Harry Terkelsen,
[How to Write a Flutter Web Plugin, Part 1][].
**FFI Plugin packages**
: A specialized Dart package that contains an API written in
Dart code combined with one or more platform-specific
implementations that use Dart FFI([Android][Android], [iOS][iOS], [macOS][macOS]).
## Developing Dart packages {#dart}
The following instructions explain how to write a Flutter
package.
### Step 1: Create the package
To create a starter Flutter package,
use the `--template=package` flag with `flutter create`:
```terminal
$ flutter create --template=package hello
```
This creates a package project in the `hello`
folder with the following content:
**LICENSE**
: A (mostly) empty license text file.
**test/hello_test.dart**
: The [unit tests][] for the package.
**hello.iml**
: A configuration file used by the IntelliJ IDEs.
**.gitignore**
: A hidden file that tells Git which files or
folders to ignore in a project.
**.metadata**
: A hidden file used by IDEs to track the properties
of the Flutter project.
**pubspec.yaml**
: A yaml file containing metadata that specifies
the package's dependencies. Used by the pub tool.
**README.md**
: A starter markdown file that briefly describes
the package's purpose.
**lib/hello.dart**
: A starter app containing Dart code for the package.
**.idea/modules.xml**, **.idea/workspace.xml**
: A hidden folder containing configuration files
for the IntelliJ IDEs.
**CHANGELOG.md**
: A (mostly) empty markdown file for tracking
version changes to the package.
### Step 2: Implement the package
For pure Dart packages, simply add the functionality
inside the main `lib/<package name>.dart` file,
or in several files in the `lib` directory.
To test the package, add [unit tests][]
in a `test` directory.
For additional details on how to organize the
package contents,
see the [Dart library package][] documentation.
## Developing plugin packages {#plugin}
If you want to develop a package that calls into
platform-specific APIs,
you need to develop a plugin package.
The API is connected to the platform-specific
implementation(s) using a [platform channel][].
### Federated plugins
Federated plugins are a way of splitting support for
different platforms into separate packages.
So, a federated plugin can use one package for iOS,
another for Android, another for web,
and yet another for a car (as an example of an IoT device).
Among other benefits, this approach allows a domain expert
to extend an existing plugin to work for the platform they know best.
A federated plugin requires the following packages:
**app-facing package**
: The package that plugin users depend on to use the plugin.
This package specifies the API used by the Flutter app.
**platform package(s)**
: One or more packages that contain the platform-specific
implementation code. The app-facing package calls into
these packages—they aren't included into an app,
unless they contain platform-specific functionality
accessible to the end user.
**platform interface package**
: The package that glues the app-facing package
to the platform package(s). This package declares an
interface that any platform package must implement to
support the app-facing package. Having a single package
that defines this interface ensures that all platform
packages implement the same functionality in a uniform way.
#### Endorsed federated plugin
Ideally, when adding a platform implementation to
a federated plugin, you will coordinate with the package
author to include your implementation.
In this way, the original author _endorses_ your
implementation.
For example, say you write a `foobar_windows`
implementation for the (imaginary) `foobar` plugin.
In an endorsed plugin, the original `foobar` author
adds your Windows implementation as a dependency
in the pubspec for the app-facing package.
Then, when a developer includes the `foobar` plugin
in their Flutter app, the Windows implementation,
as well as the other endorsed implementations,
are automatically available to the app.
#### Non-endorsed federated plugin
If you can't, for whatever reason, get your implementation
added by the original plugin author, then your plugin
is _not_ endorsed. A developer can still use your
implementation, but must manually add the plugin
to the app's pubspec file. So, the developer
must include both the `foobar` dependency _and_
the `foobar_windows` dependency in order to achieve
full functionality.
For more information on federated plugins,
why they are useful, and how they are
implemented, see the Medium article by Harry Terkelsen,
[How To Write a Flutter Web Plugin, Part 2][].
### Specifying a plugin's supported platforms {#plugin-platforms}
Plugins can specify the platforms they support by
adding keys to the `platforms` map in the
`pubspec.yaml` file. For example,
the following pubspec file shows the
`flutter:` map for the `hello` plugin,
which supports only iOS and Android:
```yaml
flutter:
plugin:
platforms:
android:
package: com.example.hello
pluginClass: HelloPlugin
ios:
pluginClass: HelloPlugin
```
When adding plugin implementations for more platforms,
the `platforms` map should be updated accordingly.
For example, here's the map in the pubspec file
for the `hello` plugin,
when updated to add support for macOS and web:
```yaml
flutter:
plugin:
platforms:
android:
package: com.example.hello
pluginClass: HelloPlugin
ios:
pluginClass: HelloPlugin
macos:
pluginClass: HelloPlugin
web:
pluginClass: HelloPlugin
fileName: hello_web.dart
```
#### Federated platform packages
A platform package uses the same format,
but includes an `implements` entry indicating
which app-facing package it implements. For example,
a `hello_windows` plugin containing the Windows
implementation for `hello`
would have the following `flutter:` map:
```yaml
flutter:
plugin:
implements: hello
platforms:
windows:
pluginClass: HelloPlugin
```
#### Endorsed implementations
An app facing package can endorse a platform package by adding a
dependency on it, and including it as a `default_package` in the
`platforms:` map. If the `hello` plugin above endorsed `hello_windows`,
it would look as follows:
```yaml
flutter:
plugin:
platforms:
android:
package: com.example.hello
pluginClass: HelloPlugin
ios:
pluginClass: HelloPlugin
windows:
default_package: hello_windows
dependencies:
hello_windows: ^1.0.0
```
Note that as shown here, an app-facing package can have
some platforms implemented within the package,
and others in endorsed federated implementations.
#### Shared iOS and macOS implementations
Many frameworks support both iOS and macOS with identical
or mostly identical APIs, making it possible to implement
some plugins for both iOS and macOS with the same codebase.
Normally each platform's implementation is in its own
folder, but the `sharedDarwinSource` option allows iOS
and macOS to use the same folder instead:
```yaml
flutter:
plugin:
platforms:
ios:
pluginClass: HelloPlugin
sharedDarwinSource: true
macos:
pluginClass: HelloPlugin
sharedDarwinSource: true
environment:
sdk: ^3.0.0
# Flutter versions prior to 3.7 did not support the
# sharedDarwinSource option.
flutter: ">=3.7.0"
```
When `sharedDarwinSource` is enabled, instead of
an `ios` directory for iOS and a `macos` directory
for macOS, both platforms use a shared `darwin`
directory for all code and resources. When enabling
this option, you need to move any existing files
from `ios` and `macos` to the shared directory. You
also need to update the podspec file to set the
dependencies and deployment targets for both platforms,
for example:
```ruby
s.ios.dependency 'Flutter'
s.osx.dependency 'FlutterMacOS'
s.ios.deployment_target = '11.0'
s.osx.deployment_target = '10.14'
```
### Step 1: Create the package
To create a plugin package, use the `--template=plugin`
flag with `flutter create`.
Use the `--platforms=` option followed by a
comma-separated list to specify the platforms
that the plugin supports. Available platforms are:
`android`, `ios`, `web`, `linux`, `macos`, and `windows`.
If no platforms are specified, the
resulting project doesn't support any platforms.
Use the `--org` option to specify your organization,
using reverse domain name notation. This value is used
in various package and bundle identifiers in the
generated plugin code.
Use the `-a` option to specify the language for android
or the `-i` option to specify the language for ios.
Please choose **one** of the following:
```terminal
$ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -a kotlin hello
```
```terminal
$ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -a java hello
```
```terminal
$ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -i objc hello
```
```terminal
$ flutter create --org com.example --template=plugin --platforms=android,ios,linux,macos,windows -i swift hello
```
This creates a plugin project in the `hello` folder
with the following specialized content:
**`lib/hello.dart`**
: The Dart API for the plugin.
**`android/src/main/java/com/example/hello/HelloPlugin.kt`**
: The Android platform-specific implementation of the plugin API
in Kotlin.
**`ios/Classes/HelloPlugin.m`**
: The iOS-platform specific implementation of the plugin API
in Objective-C.
**`example/`**
: A Flutter app that depends on the plugin,
and illustrates how to use it.
By default, the plugin project uses Swift for iOS code and
Kotlin for Android code. If you prefer Objective-C or Java,
you can specify the iOS language using `-i` and the
Android language using `-a`. For example:
```terminal
$ flutter create --template=plugin --platforms=android,ios -i objc hello
```
```terminal
$ flutter create --template=plugin --platforms=android,ios -a java hello
```
### Step 2: Implement the package {#edit-plugin-package}
As a plugin package contains code for several platforms
written in several programming languages,
some specific steps are needed to ensure a smooth experience.
#### Step 2a: Define the package API (.dart)
The API of the plugin package is defined in Dart code.
Open the main `hello/` folder in your favorite [Flutter editor][].
Locate the file `lib/hello.dart`.
#### Step 2b: Add Android platform code (.kt/.java)
We recommend you edit the Android code using Android Studio.
Then use the following steps:
1. Launch Android Studio.
1. Select **Open an existing Android Studio Project**
in the **Welcome to Android Studio** dialog,
or select **File > Open** from the menu,
and select the `hello/example/android/build.gradle` file.
1. In the **Gradle Sync** dialog, select **OK**.
1. In the **Android Gradle Plugin Update** dialog,
select **Don't remind me again for this project**.
The Android platform code of your plugin is located in
`hello/java/com.example.hello/HelloPlugin`.
You can run the example app from Android Studio by
pressing the run (▶) button.
#### Step 2c: Add iOS platform code (.swift/.h+.m)
We recommend you edit the iOS code using Xcode.
Before editing the iOS platform code in Xcode,
first make sure that the code has been built at least once
(in other words, run the example app from your IDE/editor,
or in a terminal execute
`cd hello/example; flutter build ios --no-codesign`).
Then use the following steps:
1. Launch Xcode.
1. Select **File > Open**, and select the
`hello/example/ios/Runner.xcworkspace` file.
The iOS platform code for your plugin is located in
`Pods/Development Pods/hello/../../example/ios/.symlinks/plugins/hello/ios/Classes`
in the Project Navigator. (If you are using `sharedDarwinSource`,
the path will end with `hello/darwin/Classes` instead.)
You can run the example app by pressing the run (▶) button.
##### Add CocoaPod dependencies
Use the following instructions to add `HelloPod` with the version `0.0.1`:
1. Specify dependency at the end of `ios/hello.podspec`:
```ruby
s.dependency 'HelloPod', '0.0.1'
```
For private pods, refer to [Private CocoaPods](https://guides.cocoapods.org/making/private-cocoapods.html) to ensure repo access:
```ruby
s.source = {
# For pods hosted on GitHub
:git => "https://github.com/path/to/HelloPod.git",
# Alternatively, for pods hosted locally
# :path => "file:///path/to/private/repo",
:tag => s.version.to_s
}`
```
2. Installing the plugin
- Add the plugin in the project’s `pubspec.yaml` dependencies.
- Run `flutter pub get`.
- In the project’s `ios/` directory, run `pod install`.
The pod should appear in the installation summary.
#### Step 2d: Add Linux platform code (.h+.cc)
We recommend you edit the Linux code using an IDE with
C++ integration. The instructions below are for
Visual Studio Code with the "C/C++" and "CMake" extensions
installed, but can be adjusted for other IDEs.
Before editing the Linux platform code in an IDE,
first make sure that the code has been built at least once
(in other words, run the example app from your Flutter
IDE/editor, or in a terminal execute
`cd hello/example; flutter build linux`).
Then use the following steps:
1. Launch Visual Studio Code.
1. Open the `hello/example/linux/` directory.
1. Choose **Yes** in the prompt asking:
`Would you like to configure project "linux"?`.
This will allow C++ autocomplete to work.
The Linux platform code for your plugin is located in
`flutter/ephemeral/.plugin_symlinks/hello/linux/`.
You can run the example app using `flutter run`.
**Note:** Creating a runnable Flutter application
on Linux requires steps that are part of the `flutter`
tool, so even if your editor provides CMake
integration building and running that way won't
work correctly.
#### Step 2e: Add macOS platform code (.swift)
We recommend you edit the macOS code using Xcode.
Before editing the macOS platform code in Xcode,
first make sure that the code has been built at least once
(in other words, run the example app from your IDE/editor,
or in a terminal execute
`cd hello/example; flutter build macos`).
Then use the following steps:
1. Launch Xcode.
1. Select **File > Open**, and select the
`hello/example/macos/Runner.xcworkspace` file.
The macOS platform code for your plugin is located in
`Pods/Development Pods/hello/../../example/macos/Flutter/ephemeral/.symlinks/plugins/hello/macos/Classes`
in the Project Navigator. (If you are using `sharedDarwinSource`,
the path will end with `hello/darwin/Classes` instead.)
You can run the example app by pressing the run (▶) button.
#### Step 2f: Add Windows platform code (.h+.cpp)
We recommend you edit the Windows code using Visual Studio.
Before editing the Windows platform code in Visual Studio,
first make sure that the code has been built at least once
(in other words, run the example app from your IDE/editor,
or in a terminal execute
`cd hello/example; flutter build windows`).
Then use the following steps:
1. Launch Visual Studio.
1. Select **Open a project or solution**, and select the
`hello/example/build/windows/hello_example.sln` file.
The Windows platform code for your plugin is located in
`hello_plugin/Source Files` and `hello_plugin/Header Files` in
the Solution Explorer.
You can run the example app by right-clicking `hello_example` in
the Solution Explorer and selecting **Set as Startup Project**,
then pressing the run (▶) button. **Important:** After
making changes to plugin code, you must select
**Build > Build Solution** before running again, otherwise
an outdated copy of the built plugin will be run instead
of the latest version containing your changes.
#### Step 2g: Connect the API and the platform code
Finally, you need to connect the API written in Dart code with
the platform-specific implementations.
This is done using a [platform channel][],
or through the interfaces defined in a platform
interface package.
### Add support for platforms in an existing plugin project
To add support for specific platforms to an
existing plugin project, run `flutter create` with
the `--template=plugin` flag again in the project directory.
For example, to add web support in an existing plugin, run:
```terminal
$ flutter create --template=plugin --platforms=web .
```
If this command displays a message about updating the
`pubspec.yaml` file, follow the provided instructions.
### Dart platform implementations
In many cases, non-web platform implementations only use the
platform-specific implementation language, as shown above. However,
platform implementations can also use platform-specific Dart as well.
{{site.alert.note}}
The examples below only apply to non-web platforms. Web
plugin implementations are always written in Dart, and use
`pluginClass` and `fileName` for their Dart implementations
as shown above.
{{site.alert.end}}
#### Dart-only platform implementations
In some cases, some platforms can be
implemented entirely in Dart (for example, using FFI).
For a Dart-only platform implementation on a platform other than web,
replace the `pluginClass` in pubspec.yaml with a `dartPluginClass`.
Here is the `hello_windows` example above modified for a
Dart-only implementation:
```yaml
flutter:
plugin:
implements: hello
platforms:
windows:
dartPluginClass: HelloPluginWindows
```
In this version you would have no C++ Windows code, and would instead
subclass the `hello` plugin's Dart platform interface class with a
`HelloPluginWindows` class that includes a static
`registerWith()` method. This method is called during startup,
and can be used to register the Dart implementation:
```dart
class HelloPluginWindows extends HelloPluginPlatform {
/// Registers this class as the default instance of [HelloPluginPlatform].
static void registerWith() {
HelloPluginPlatform.instance = HelloPluginWindows();
}
```
#### Hybrid platform implementations
Platform implementations can also use both Dart and a platform-specific
language. For example, a plugin could use a different platform channel
for each platform so that the channels can be customized per platform.
A hybrid implementation uses both of the registration systems
described above. Here is the `hello_windows` example above modified for a
hybrid implementation:
```yaml
flutter:
plugin:
implements: hello
platforms:
windows:
dartPluginClass: HelloPluginWindows
pluginClass: HelloPlugin
```
The Dart `HelloPluginWindows` class would use the `registerWith()`
shown above for Dart-only implementations, while the C++ `HelloPlugin`
class would be the same as in a C++-only implementation.
### Testing your plugin
We encourage you test your plugin with automated tests
to ensure that functionality doesn't regress
as you make changes to your code.
To learn more about testing your plugins,
check out [Testing plugins][].
If you are writing tests for your Flutter app
and plugins are causing crashes,
check out [Flutter in plugin tests][].
[Flutter in plugin tests]: /testing/plugins-in-tests
[Testing plugins]: /testing/testing-plugins
## Developing FFI plugin packages {#plugin-ffi}
If you want to develop a package that calls into native APIs using
Dart's FFI, you need to develop an FFI plugin package.
Both FFI plugin packages and (non-FFI) plugin packages support
bundling native code, but FFI plugin packages do not support
method channels and do include method channel registration code.
If you want to implement a plugin that uses both method channels
and FFI, use a (non-FFI) plugin. You can chose per platform to
use an FFI or (non-FFI) plugin.
FFI plugin packages were introduced in Flutter 3.0, if you're
targeting older Flutter versions, you can use a (non-FFI) plugin.
### Step 1: Create the package
To create a starter FFI plugin package,
use the `--template=plugin_ffi` flag with `flutter create`:
```terminal
$ flutter create --template=plugin_ffi hello
```
This creates an FFI plugin project in the `hello`
folder with the following specialized content:
**lib**: The Dart code that defines the API of the plugin,
and which calls into the native code using `dart:ffi`.
**src**: The native source code, and a `CMakeLists.txt`
file for building that source code into a dynamic library.
**platform folders** (`android`, `ios`, `windows`, etc.): The
build files for building and bundling the native code
library with the platform application.
### Step 2: Building and bundling native code
The `pubspec.yaml` specifies FFI plugins as follows:
```yaml
plugin:
platforms:
some_platform:
ffiPlugin: true
```
This configuration invokes the native build
for the various target platforms and bundles
the binaries in Flutter applications using these FFI plugins.
This can be combined with `dartPluginClass`,
such as when FFI is used for the
implementation of one platform in a federated plugin:
```yaml
plugin:
implements: some_other_plugin
platforms:
some_platform:
dartPluginClass: SomeClass
ffiPlugin: true
```
A plugin can have both FFI and method channels:
```yaml
plugin:
platforms:
some_platform:
pluginClass: SomeName
ffiPlugin: true
```
The native build systems that are invoked by FFI
(and method channels) plugins are:
* For Android: Gradle, which invokes the Android NDK for native builds.
* See the documentation in `android/build.gradle`.
* For iOS and macOS: Xcode, via CocoaPods.
* See the documentation in `ios/hello.podspec`.
* See the documentation in `macos/hello.podspec`.
* For Linux and Windows: CMake.
* See the documentation in `linux/CMakeLists.txt`.
* See the documentation in `windows/CMakeLists.txt`.
### Step 3: Binding to native code
To use the native code, bindings in Dart are needed.
To avoid writing these by hand,
they are generated from the header file
(`src/hello.h`) by [`package:ffigen`][].
Reference the [ffigen docs][] for information
on how to install this package.
Regenerate the bindings by running the following:
```terminal
$ dart run ffigen --config ffigen.yaml
```
### Step 4: Invoking native code
Very short-running native functions can be directly
invoked from any isolate.
For an example, see `sum` in `lib/hello.dart`.
Longer-running functions should be invoked on a
[helper isolate][] to avoid dropping frames in
Flutter applications.
For an example, see `sumAsync` in `lib/hello.dart`.
## Adding documentation
It is recommended practice to add the following documentation
to all packages:
1. A `README.md` file that introduces the package
1. A `CHANGELOG.md` file that documents changes in each version
1. A [`LICENSE`] file containing the terms under which the package
is licensed
1. API documentation for all public APIs (see below for details)
### API documentation
When you publish a package,
API documentation is automatically generated and
published to pub.dev/documentation.
For example, see the docs for [`device_info`][].
If you wish to generate API documentation locally on
your development machine, use the following commands:
<ol markdown="1">
<li markdown="1">Change directory to the location of your package:
```terminal
cd ~/dev/mypackage
```
</li>
<li markdown="1">Tell the documentation tool where the
Flutter SDK is located (change the following commands to reflect
where you placed it):
```terminal
export FLUTTER_ROOT=~/dev/flutter # on macOS or Linux
set FLUTTER_ROOT=~/dev/flutter # on Windows
```
</li>
<li markdown="1">Run the `dart doc` tool
(included as part of the Flutter SDK), as follows:
```terminal
$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart doc # on macOS or Linux
%FLUTTER_ROOT%\bin\cache\dart-sdk\bin\dart doc # on Windows
```
</li>
</ol>
For tips on how to write API documentation, see
[Effective Dart Documentation][].
### Adding licenses to the LICENSE file
Individual licenses inside each LICENSE file
should be separated by 80 hyphens
on their own on a line.
If a LICENSE file contains more than one
component license, then each component
license must start with the names of the
packages to which the component license applies,
with each package name on its own line,
and the list of package names separated from
the actual license text by a blank line.
(The packages need not match the names of
the pub package. For example, a package might itself contain
code from multiple third-party sources,
and might need to include a license for each one.)
The following example shows a well-organized license file:
```none
package_1
<some license text>
--------------------------------------------------------------------------------
package_2
<some license text>
```
Here is another example of a well-organized license file:
```none
package_1
<some license text>
--------------------------------------------------------------------------------
package_1
package_2
<some license text>
```
Here is an example of a poorly-organized license file:
```none
<some license text>
--------------------------------------------------------------------------------
<some license text>
```
Another example of a poorly-organized license file:
```
package_1
<some license text>
--------------------------------------------------------------------------------
<some license text>
```
## Publishing your package {#publish}
{{site.alert.tip}}
Have you noticed that some of the packages and plugins
on pub.dev are designated as [Flutter Favorites][]?
These are the packages published by verified developers
and are identified as the packages and plugins you
should first consider using when writing your app.
To learn more,
see the [Flutter Favorites program][].
{{site.alert.end}}
Once you have implemented a package, you can publish it on
[pub.dev][], so that other developers can easily use it.
Prior to publishing, make sure to review the `pubspec.yaml`,
`README.md`, and `CHANGELOG.md` files to make sure their
content is complete and correct. Also, to improve the
quality and usability of your package (and to make it
more likely to achieve the status of a Flutter Favorite),
consider including the following items:
* Diverse code usage examples
* Screenshots, animated gifs, or videos
* A link to the corresponding code repository
Next, run the publish command in `dry-run` mode
to see if everything passes analysis:
```terminal
$ flutter pub publish --dry-run
```
The next step is publishing to pub.dev,
but be sure that you are ready because
[publishing is forever][]:
```terminal
$ flutter pub publish
```
For more details on publishing, see the
[publishing docs][] on dart.dev.
## Handling package interdependencies {#dependencies}
If you are developing a package `hello` that depends on
the Dart API exposed by another package, you need to add
that package to the `dependencies` section of your
`pubspec.yaml` file. The code below makes the Dart API
of the `url_launcher` plugin available to `hello`:
```yaml
dependencies:
url_launcher: ^5.0.0
```
You can now `import 'package:url_launcher/url_launcher.dart'`
and `launch(someUrl)` in the Dart code of `hello`.
This is no different from how you include packages in
Flutter apps or any other Dart project.
But if `hello` happens to be a _plugin_ package
whose platform-specific code needs access
to the platform-specific APIs exposed by `url_launcher`,
you also need to add suitable dependency declarations
to your platform-specific build files, as shown below.
### Android
The following example sets a dependency for
`url_launcher` in `hello/android/build.gradle`:
```groovy
android {
// lines skipped
dependencies {
compileOnly rootProject.findProject(":url_launcher")
}
}
```
You can now `import io.flutter.plugins.urllauncher.UrlLauncherPlugin`
and access the `UrlLauncherPlugin`
class in the source code at `hello/android/src`.
For more information on `build.gradle` files, see the
[Gradle Documentation][] on build scripts.
### iOS
The following example sets a dependency for
`url_launcher` in `hello/ios/hello.podspec`:
```ruby
Pod::Spec.new do |s|
# lines skipped
s.dependency 'url_launcher'
```
You can now `#import "UrlLauncherPlugin.h"` and
access the `UrlLauncherPlugin` class in the source code
at `hello/ios/Classes`.
For additional details on `.podspec` files, see the
[CocoaPods Documentation][] on them.
### Web
All web dependencies are handled by the `pubspec.yaml`
file like any other Dart package.
{% comment %}
<!-- Remove until we have better text. -->
### MacOS
PENDING
{% endcomment %}
[CocoaPods Documentation]: https://guides.cocoapods.org/syntax/podspec.html
[Dart library package]: {{site.dart-site}}/guides/libraries/create-library-packages
[`device_info`]: {{site.pub-api}}/device_info/latest
[Effective Dart Documentation]: {{site.dart-site}}/guides/language/effective-dart/documentation
[federated plugins]: #federated-plugins
[ffigen docs]: {{site.pub-pkg}}/ffigen/install
[Android]: /platform-integration/android/c-interop
[iOS]: /platform-integration/ios/c-interop
[macOS]: /platform-integration/macos/c-interop
[`fluro`]: {{site.pub}}/packages/fluro
[Flutter editor]: /get-started/editor
[Flutter Favorites]: {{site.pub}}/flutter/favorites
[Flutter Favorites program]: /packages-and-plugins/favorites
[Gradle Documentation]: https://docs.gradle.org/current/userguide/tutorial_using_tasks.html
[helper isolate]: {{site.dart-site}}/guides/language/concurrency#background-workers
[How to Write a Flutter Web Plugin, Part 1]: {{site.flutter-medium}}/how-to-write-a-flutter-web-plugin-5e26c689ea1
[How To Write a Flutter Web Plugin, Part 2]: {{site.flutter-medium}}/how-to-write-a-flutter-web-plugin-part-2-afdddb69ece6
[issue #33302]: {{site.repo.flutter}}/issues/33302
[`LICENSE`]: #adding-licenses-to-the-license-file
[`path`]: {{site.pub}}/packages/path
[`package:ffigen`]: {{site.pub}}/packages/ffigen
[platform channel]: /platform-integration/platform-channels
[pub.dev]: {{site.pub}}
[publishing docs]: {{site.dart-site}}/tools/pub/publishing
[publishing is forever]: {{site.dart-site}}/tools/pub/publishing#publishing-is-forever
[supported-platforms]: #plugin-platforms
[test your plugin]: #testing-your-plugin
[unit tests]: /testing/overview#unit-tests
[`url_launcher`]: {{site.pub}}/packages/url_launcher
[Writing a good plugin]: {{site.flutter-medium}}/writing-a-good-flutter-plugin-1a561b986c9c
| website/src/packages-and-plugins/developing-packages.md/0 | {
"file_path": "website/src/packages-and-plugins/developing-packages.md",
"repo_id": "website",
"token_count": 9230
} | 1,245 |
---
title: Debugging performance for web apps
description: Learn how to use Chrome DevTools to debug web performance issues.
---
{{site.alert.note}}
Profiling Flutter web apps requires Flutter version 3.14 or later.
{{site.alert.end}}
The Flutter framework emits timeline events as it works to build frames,
draw scenes, and track other activity such as garbage collections.
These events are exposed in the
[Chrome DevTools performance panel][] for debugging.
You can also emit your own timeline events using the `dart:developer`
[Timeline][] and [TimelineTask][] APIs for further performance analysis.
[Chrome DevTools performance panel]: https://developer.chrome.com/docs/devtools/performance
[Timeline]: {{site.api}}/flutter/dart-developer/Timeline-class.html
[TimelineTask]: {{site.api}}/flutter/dart-developer/TimelineTask-class.html

## Optional flags to enhance tracing
To configure which timeline events are tracked, set any of the following top-level properties to `true`
in your app's `main` method.
- [debugProfileBuildsEnabled][]: Adds `Timeline` events for every `Widget` built.
- [debugProfileBuildsEnabledUserWidgets][]: Adds `Timeline` events for every user-created `Widget` built.
- [debugProfileLayoutsEnabled][]: Adds `Timeline` events for every `RenderObject` layout.
- [debugProfilePaintsEnabled][]: Adds `Timeline` events for every `RenderObject` painted.
[debugProfileBuildsEnabled]: {{site.api}}/flutter/widgets/debugProfileBuildsEnabled.html
[debugProfileBuildsEnabledUserWidgets]: {{site.api}}/flutter/widgets/debugProfileBuildsEnabledUserWidgets.html
[debugProfileLayoutsEnabled]: {{site.api}}/flutter/rendering/debugProfileLayoutsEnabled.html
[debugProfilePaintsEnabled]: {{site.api}}/flutter/rendering/debugProfilePaintsEnabled.html
## Instructions
1. _[Optional]_ Set any desired tracing flags to true from your app's main method.
2. Run your Flutter web app in [profile mode][].
3. Open up the [Chrome DevTools Performance panel][] for your application,
and [start recording][] to capture timeline events.
[start recording]: https://developer.chrome.com/docs/devtools/performance/#record
[profile mode]: /testing/build-modes#profile
[Chrome DevTools performance panel]: https://developer.chrome.com/docs/devtools/performance
| website/src/perf/web-performance.md/0 | {
"file_path": "website/src/perf/web-performance.md",
"repo_id": "website",
"token_count": 665
} | 1,246 |
---
title: Desktop support for Flutter
description: General information about Flutter support for desktop apps.
---
Flutter provides support for compiling
a native Windows, macOS, or Linux desktop app.
Flutter's desktop support also extends to plugins—you
can install existing plugins that support the Windows,
macOS, or Linux platforms, or you can create your own.
{{site.alert.note}}
This page covers developing apps for all desktop
platforms. Once you've read this, you can dive into
specific platform information at the following links:
* [Building Windows apps with Flutter][]
* [Building macOS apps with Flutter][]
* [Building Linux apps with Flutter][]
{{site.alert.end}}
[Building Windows apps with Flutter]: /platform-integration/windows/building
[Building macOS apps with Flutter]: /platform-integration/macos/building
[Building Linux apps with Flutter]: /platform-integration/linux/building
## Create a new project
You can use the following steps
to create a new project with desktop support.
### Set up desktop devtools
Consult the guide for your target desktop environment:
* [Install Linux desktop devtools][Linux-devtools]
* [Install macOS desktop devtools][macOS-devtools]
* [Install Windows desktop devtools][Windows-devtools]
[Linux-devtools]: /get-started/install/linux/desktop
[macOS-devtools]: /get-started/install/macos/desktop
[Windows-devtools]: /get-started/install/windows/desktop
If `flutter doctor` finds problems or missing components
for a platform that you don't want to develop for,
you can ignore those warnings. Or you can disable the
platform altogether using the `flutter config` command,
for example:
```terminal
$ flutter config --no-enable-ios
```
Other available flags:
* `--no-enable-windows-desktop`
* `--no-enable-linux-desktop`
* `--no-enable-macos-desktop`
* `--no-enable-web`
* `--no-enable-android`
* `--no-enable-ios`
After enabling desktop support,
restart your IDE so that it can detect the new device.
### Create and run
Creating a new project with desktop support is no different
than [creating a new Flutter project][] for other platforms.
Once you've configured your environment for desktop
support, you can create and run a desktop application
either in the IDE or from the command line.
[creating a new Flutter project]: /get-started/test-drive
#### Using an IDE
After you've configured your environment to support
desktop, make sure you restart the IDE if it was
already running.
Create a new application in your IDE and it automatically
creates iOS, Android, web, and desktop versions of your app.
From the device pulldown, select **windows (desktop)**,
**macOS (desktop)**, or **linux (desktop)**
and run your application to see it launch on the desktop.
#### From the command line
To create a new application that includes desktop support
(in addition to mobile and web support), run the following commands,
substituting `my_app` with the name of your project:
```terminal
$ flutter create my_app
$ cd my_app
```
To launch your application from the command line,
enter one of the following commands from the top
of the package:
```terminal
C:\> flutter run -d windows
$ flutter run -d macos
$ flutter run -d linux
```
{{site.alert.note}}
If you do not supply the `-d` flag, `flutter run` lists
the available targets to choose from.
{{site.alert.end}}
## Build a release app
To generate a release build,
run one of the following commands:
```terminal
PS C:\> flutter build windows
$ flutter build macos
$ flutter build linux
```
## Add desktop support to an existing Flutter app
To add desktop support to an existing Flutter project,
run the following command in a terminal from the
root project directory:
```terminal
$ flutter create --platforms=windows,macos,linux .
```
This adds the necessary desktop files and directories
to your existing Flutter project.
To add only specific desktop platforms,
change the `platforms` list to include only
the platform(s) you want to add.
## Plugin support
Flutter on the desktop supports using and creating plugins.
To use a plugin that supports desktop,
follow the steps for plugins in [using packages][].
Flutter automatically adds the necessary native code
to your project, as with any other platform.
### Writing a plugin
When you start building your own plugins,
you'll want to keep federation in mind.
Federation is the ability to define several
different packages, each targeted at a
different set of platforms, brought together
into a single plugin for ease of use by developers.
For example, the Windows implementation of the
`url_launcher` is really `url_launcher_windows`,
but a Flutter developer can simply add the
`url_launcher` package to their `pubspec.yaml`
as a dependency and the build process pulls in
the correct implementation based on the target platform.
Federation is handy because different teams with
different expertise can build plugin implementations
for different platforms.
You can add a new platform implementation to any
endorsed federated plugin on pub.dev,
so long as you coordinate this effort with the
original plugin author.
For more information, including information
about endorsed plugins, see the following resources:
* [Developing packages and plugins][], particularly the
[Federated plugins][] section.
* [How to write a Flutter web plugin, part 2][],
covers the structure of federated plugins and
contains information applicable to desktop
plugins.
* [Modern Flutter Plugin Development][] covers
recent enhancements to Flutter's plugin support.
[using packages]: /packages-and-plugins/using-packages
[Developing packages and plugins]: /packages-and-plugins/developing-packages
[Federated plugins]: /packages-and-plugins/developing-packages#federated-plugins
[How to write a Flutter web plugin, part 2]: {{site.flutter-medium}}/how-to-write-a-flutter-web-plugin-part-2-afdddb69ece6
[Modern Flutter Plugin Development]: {{site.flutter-medium}}/modern-flutter-plugin-development-4c3ee015cf5a
## Samples and codelabs
[Write a Flutter desktop application][]
: A codelab that walks you through building
a desktop application that integrates the GitHub
GraphQL API with your Flutter app.
You can run the following samples as desktop apps,
as well as download and inspect the source code to
learn more about Flutter desktop support.
Wonderous app [running app][wonderous-app], [repo][wonderous-repo]
: A showcase app that uses Flutter to create a highly expressive user interface.
Wonderous focuses on delivering an accessible and high-quality user experience
while including engaging interactions and novel animations.
To run Wonderous as a desktop app, clone the project and
follow the instructions provided in the [README][wonderous-readme].
Flokk [announcement blogpost][gskinner-flokk-blogpost], [repo][gskinner-flokk-repo]
: A Google contacts manager that integrates with GitHub and Twitter.
It syncs with your Google account, imports your contacts,
and allows you to manage them.
[Photo Search app][]
: A sample application built as a desktop application that
uses desktop-supported plugins.
[wonderous-app]: {{site.wonderous}}/web
[wonderous-repo]: {{site.repo.wonderous}}
[wonderous-readme]: {{site.repo.wonderous}}#wonderous
[Photo Search app]: {{site.repo.samples}}/tree/main/desktop_photo_search
[gskinner-flokk-repo]: {{site.github}}/gskinnerTeam/flokk
[gskinner-flokk-blogpost]: https://blog.gskinner.com/archives/2020/09/flokk-how-we-built-a-desktop-app-using-flutter.html
[Write a Flutter desktop application]: {{site.codelabs}}/codelabs/flutter-github-client
| website/src/platform-integration/desktop.md/0 | {
"file_path": "website/src/platform-integration/desktop.md",
"repo_id": "website",
"token_count": 2048
} | 1,247 |
---
layout: toc
title: Linux
description: Content covering integration with Linux in Flutter apps.
---
| website/src/platform-integration/linux/index.md/0 | {
"file_path": "website/src/platform-integration/linux/index.md",
"repo_id": "website",
"token_count": 26
} | 1,248 |
---
title: Customizing web app initialization
description: Customize how Flutter apps are initialized on the web
---
You can customize how a Flutter app is initialized on the web
using the `_flutter.loader` JavaScript API provided by `flutter.js`.
This API can be used to display a loading indicator in CSS,
prevent the app from loading based on a condition,
or wait until the user presses a button before showing the app.
The initialization process is split into the following stages:
**Loading the entrypoint script**
: Fetches the `main.dart.js` script and initializes the service worker.
**Initializing the Flutter engine**
: Initializes Flutter's web engine by downloading required resources
such as assets, fonts, and CanvasKit.
**Running the app**
: Prepares the DOM for your Flutter app and runs it.
This page shows how to customize the behavior
at each stage of the initialization process.
## Getting started
By default, the `index.html` file
generated by the `flutter create` command
contains a script tag
that calls `loadEntrypoint` from the `flutter.js` file:
```html
<html>
<head>
<!-- ... -->
<script src="flutter.js" defer></script>
</head>
<body>
<script>
window.addEventListener('load', function (ev) {
// Download main.dart.js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: async function(engineInitializer) {
// Initialize the Flutter engine
let appRunner = await engineInitializer.initializeEngine();
// Run the app
await appRunner.runApp();
}
});
});
</script>
</body>
</html>
```
{{site.alert.note}}
In Flutter 2.10 or earlier,
this script doesn't support customization.
To upgrade your `index.html` file to the latest version,
see [Upgrading an older project](#upgrading-an-older-project).
{{site.alert.end}}
The `loadEntrypoint` function calls the `onEntrypointLoaded` callback
once the Service Worker is initialized, and the `main.dart.js` entrypoint
has been downloaded and run by the browser. Flutter also calls
`onEntrypointLoaded` on every hot restart during development.
The `onEntrypointLoaded` callback receives an **engine initializer** object as
its only parameter. Use the engine initializer to set the run-time
configuration, and start the Flutter Web engine.
The `initializeEngine()` function returns a [`Promise`][js-promise]
that resolves with an **app runner** object. The app runner has a
single method, `runApp()`, that runs the Flutter app.
[js-promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
## Customizing web app initialization
In this section,
learn how to customize each stage of your app's initialization.
### Loading the entrypoint
The `loadEntrypoint` method accepts these parameters:
<div class="table-wrapper" markdown="1">
| Name | Description | JS Type |
|-|-|-|
|`entrypointUrl`| The URL of your Flutter app's entrypoint. Defaults to `"main.dart.js"`. |`String`|
|`onEntrypointLoaded`| The function called when the engine is ready to be initialized. Receives an `engineInitializer` object as its only parameter. |`Function`|
|`serviceWorker`| The configuration for the `flutter_service_worker.js` loader. (If not set, the service worker won't be used.) |`Object`|
{:.table}
</div>
The `serviceWorker` JavaScript object accepts the following properties:
<div class="table-wrapper" markdown="1">
| Name | Description | JS Type |
|-|-|-|
|`serviceWorkerUrl`| The URL of the Service Worker JS file. The `serviceWorkerVersion` is appended to the URL. Defaults to `"flutter_service_worker.js?v="` |`String`|
|`serviceWorkerVersion`| Pass *the `serviceWorkerVersion` variable* set by the build process in your **`index.html`** file. |`String`|
|`timeoutMillis`| The timeout value for the service worker load. Defaults to `4000`. |`Number`|
{:.table}
</div>
### Initializing the engine
As of _Flutter 3.7.0_, you can use the `initializeEngine` method to
configure several run-time options of the Flutter web engine through a
plain JavaScript object.
You can add any of the following optional parameters:
<div class="table-wrapper" markdown="1">
| Name | Description | Dart Type |
|-|-|-|
|`assetBase`| The base URL of the `assets` directory of the app. Add this when Flutter loads from a different domain or subdirectory than the actual web app. You might need this when you embed Flutter web into another app, or when you deploy its assets to a CDN. |`String`|
|`canvasKitBaseUrl`| The base URL from where `canvaskit.wasm` is downloaded. |`String`|
|`canvasKitVariant`| The CanvasKit variant to download. Your options cover:<br><br>1. `auto`: Downloads the optimal variant for the browser. The option defaults to this value.<br>2. `full`: Downloads the full variant of CanvasKit that works in all browsers.<br>3. `chromium`: Downloads a smaller variant of CanvasKit that uses Chromium compatible APIs. **_Warning_**: Don't use the `chromium` option unless you plan on only using Chromium-based browsers. |`String`|
|`canvasKitForceCpuOnly`| When `true`, forces CPU-only rendering in CanvasKit (the engine won't use WebGL). |`bool`|
|`canvasKitMaximumSurfaces`| The maximum number of overlay surfaces that the CanvasKit renderer can use. |`double`|
|`debugShowSemanticNodes`| If `true`, Flutter visibly renders the semantics tree onscreen (for debugging). |`bool`|
|`hostElement`| HTML Element into which Flutter renders the app. When not set, Flutter web takes over the whole page. |`HtmlElement`|
|`renderer`| Specifies the [web renderer][web-renderers] for the current Flutter application, either `"canvaskit"` or `"html"`. |`String`|
{:.table}
</div>
[jsflutterconfig-source]: {{site.repo.engine}}/blob/main/lib/web_ui/lib/src/engine/configuration.dart#L247-L259
[web-renderers]: /platform-integration/web/renderers
{{site.alert.note}}
Some of the parameters described above might have been overridden
in previous releases by using properties in the `window` object.
That approach is still supported, but displays a **deprecation
notice** in the JS console, as of **Flutter 3.7.0**.
{{site.alert.end}}
#### Engine configuration example
The `initializeEngine` method lets you pass any of the configuration
parameters described above to your Flutter app.
Consider the following example.
Your Flutter app should target an HTML element with `id="flutter_app"` and
use the `canvaskit` renderer. The resulting JavaScript code would resemble
the following:
```js
onEntrypointLoaded: async function(engineInitializer) {
let appRunner = await engineInitializer.initializeEngine({
hostElement: document.querySelector("#flutter_app"),
renderer: "canvaskit"
});
appRunner.runApp();
}
```
For a more detailed explanation of each parameter, take a look at the
**"Runtime parameters"** documentation section of the [`configuration.dart`][config-dart]
file of the web engine.
[config-dart]: {{site.repo.engine}}/blob/main/lib/web_ui/lib/src/engine/configuration.dart#L174
#### Skipping this step
Instead of calling `initializeEngine()` on the engine initializer (and then
`runApp()` on the application runner), you can call `autoStart()` to
initialize the engine with its default configuration, and then start the app
immediately after the initialization is complete:
```js
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: async function(engineInitializer) {
await engineInitializer.autoStart();
}
});
```
## Example: Display a progress indicator
To give the user of your application feedback
during the initialization process,
use the hooks provided for each stage to update the DOM:
```html
<html>
<head>
<!-- ... -->
<script src="flutter.js" defer></script>
</head>
<body>
<div id="loading"></div>
<script>
window.addEventListener('load', function(ev) {
var loading = document.querySelector('#loading');
loading.textContent = "Loading entrypoint...";
_flutter.loader.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
onEntrypointLoaded: async function(engineInitializer) {
loading.textContent = "Initializing engine...";
let appRunner = await engineInitializer.initializeEngine();
loading.textContent = "Running app...";
await appRunner.runApp();
}
});
});
</script>
</body>
</html>
```
For a more practical example using CSS animations,
see the [initialization code][gallery-init] for the Flutter Gallery.
[gallery-init]: {{site.repo.gallery-archive}}/blob/main/web/index.html
## Upgrading an older project
If your project was created in Flutter 2.10 or earlier,
you can create a new `index.html` file
with the latest initialization template by running
`flutter create` as follows.
First, remove the files from your `/web` directory.
Then, from your project directory, run the following:
```
$ flutter create . --platforms=web
```
| website/src/platform-integration/web/initialization.md/0 | {
"file_path": "website/src/platform-integration/web/initialization.md",
"repo_id": "website",
"token_count": 2872
} | 1,249 |
---
title: Add Windows devtools for Flutter
description: Configure your system to develop Flutter for Windows.
short-title: Add Windows desktop DevTools
target-list: [Android, Web]
---
To choose the guide to add Visual Studio to your Flutter configuration,
click the [Getting Started path][] you followed.
<div class="card-deck mb-8">
{% for target in page.target-list %}
{% assign targetlink='/platform-integration/windows/install-windows/install-windows-from-' | append: target | downcase %}
<a class="card card-app-type card-windows"
id="install-{{target | downcase}}"
href="{{targetlink}}">
<div class="card-body">
<header class="card-title text-center m-0">
<span class="d-block h1">
{% assign icon = target | downcase -%}
{% case icon %}
{% when 'android' -%}
<span class="material-symbols">phone_android</span>
{% when 'web' -%}
<span class="material-symbols">web</span>
{% endcase -%}
<span class="material-symbols">add</span>
<span class="material-symbols">desktop_windows</span>
</span>
<span class="text-muted text-nowrap">
Make Windows desktop and {{ target }} apps
</span>
</header>
</div>
</a>
{% endfor %}
</div>
[Getting Started path]: /get-started/install
| website/src/platform-integration/windows/install-windows/index.md/0 | {
"file_path": "website/src/platform-integration/windows/install-windows/index.md",
"repo_id": "website",
"token_count": 532
} | 1,250 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.