text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// 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 'package:flutter/material.dart';
class TextStyles {
const TextStyles({Key? key});
static TextStyle bodyStyle() {
return const TextStyle(
fontFamily: 'Roboto',
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.w400,
height: 1.5,
);
}
static TextStyle headlineStyle() {
return const TextStyle(
fontFamily: 'Roboto',
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.w700,
height: 1.5,
);
}
}
class ButtonStyles {
static ButtonStyle style() {
return ButtonStyle(
fixedSize: MaterialStateProperty.resolveWith<Size>((states) {
return const Size(100, 36);
}),
shape: MaterialStateProperty.resolveWith<OutlinedBorder>((states) {
return const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(18)));
}),
overlayColor: null,
backgroundColor: MaterialStateProperty.resolveWith<Color?>((states) {
if (states.contains(MaterialState.hovered)) {
return Colors.black; // Hovered bg (for desktop with mouse)
}
return Colors.grey[600]; // Default bg
}),
);
}
}
| samples/experimental/varfont_shader_puzzle/lib/styles.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/styles.dart",
"repo_id": "samples",
"token_count": 532
} | 1,225 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/experimental/varfont_shader_puzzle/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,226 |
// 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 'auth.dart';
class MockAuthService implements Auth {
@override
Future<bool> get isSignedIn async => false;
@override
Future<User> signIn() async {
return MockUser();
}
@override
Future signOut() async {
return null;
}
}
class MockUser implements User {
@override
String get uid => "123";
}
| samples/experimental/web_dashboard/lib/src/auth/mock.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/auth/mock.dart",
"repo_id": "samples",
"token_count": 167
} | 1,227 |
// 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 'dart:convert';
import 'dart:io';
import 'package:grinder/grinder.dart';
import 'package:path/path.dart' as path;
void main(List<String> args) => grind(args);
@Task()
void runSkia() {
run('flutter',
arguments:
'run -d web --web-port=5000 --release --dart-define=FLUTTER_WEB_USE_SKIA=true lib/main.dart '
.split(' '));
}
@Task()
void runWeb() {
run('flutter',
arguments: 'run -d web --web-port=5000 lib/main.dart '.split(' '));
}
@Task()
void runFirebase() {
run('flutter',
arguments:
'run -d web --web-port=5000 lib/main_firebase.dart '.split(' '));
}
@Task()
void runFirebaseSkia() {
run('flutter',
arguments:
'run -d web --web-port=5000 --release --dart-define=FLUTTER_WEB_USE_SKIA=true lib/main_firebase.dart'
.split(' '));
}
@Task()
void test() {
TestRunner().testAsync();
}
@DefaultTask()
@Depends(test, copyright)
void build() {
Pub.build();
}
@Task()
void clean() => defaultClean();
@Task()
void generate() {
Pub.run('build_runner', arguments: ['build']);
}
const _copyright =
'''// 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.''';
@Task()
Future copyright() async {
var files = <File>[];
await for (var file in _filesWithoutCopyright()) {
files.add(file);
}
if (files.isNotEmpty) {
log('Found Dart files without a copyright header:');
for (var file in files) {
log(file.toString());
}
fail('run "grind fix-copyright" to add copyright headers');
}
}
@Task()
Future fixCopyright() async {
await for (var file in _filesWithoutCopyright()) {
var contents = await file.readAsString();
await file.writeAsString('$_copyright\n\n$contents');
}
}
Stream<File> _filesWithoutCopyright() async* {
var set = FileSet.fromDir(Directory('.'), recurse: true);
var dartFiles =
set.files.where((file) => path.extension(file.path) == '.dart');
for (var file in dartFiles) {
var firstThreeLines = await file
.openRead()
.transform(utf8.decoder)
.transform(const LineSplitter())
.take(3)
.fold<String>('', (previous, element) {
if (previous == '') return element;
return '$previous\n$element';
});
if (firstThreeLines != _copyright) {
yield file;
}
}
}
| samples/experimental/web_dashboard/tool/grind.dart/0 | {
"file_path": "samples/experimental/web_dashboard/tool/grind.dart",
"repo_id": "samples",
"token_count": 1022
} | 1,228 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Form App rebuild script
steps:
- name: Remove runners
rmdirs:
- android
- ios
- macos
- linux
- windows
- web
- name: Flutter recreate
flutter: create --platforms android,ios,windows,linux,macos,web --org dev.flutter.formApp .
- name: Drop widget_test.dart
rm: test/widget_test.dart
- name: Flutter upgrade
flutter: pub upgrade --major-versions
- name: Patch web/manifest.json
path: web/manifest.json
patch-u: |
--- b/form_app/web/manifest.json
+++ a/form_app/web/manifest.json
@@ -5,7 +5,7 @@
"display": "standalone",
"background_color": "#0175C2",
"theme_color": "#0175C2",
- "description": "A new Flutter project.",
+ "description": "A sample demonstrating different types of forms and best practices",
"orientation": "portrait-primary",
"prefer_related_applications": false,
"icons": [
- name: Flutter build macOS
flutter: build macos
- name: Flutter build ios
flutter: build ios --simulator
| samples/form_app/codelab_rebuild.yaml/0 | {
"file_path": "samples/form_app/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 492
} | 1,229 |
// 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.
const gameLevels = [
GameLevel(
number: 1,
difficulty: 5,
// TODO: When ready, change these achievement IDs.
// You configure this in App Store Connect.
achievementIdIOS: 'first_win',
// You get this string when you configure an achievement in Play Console.
achievementIdAndroid: 'NhkIwB69ejkMAOOLDb',
),
GameLevel(
number: 2,
difficulty: 42,
),
GameLevel(
number: 3,
difficulty: 100,
achievementIdIOS: 'finished',
achievementIdAndroid: 'CdfIhE96aspNWLGSQg',
),
];
class GameLevel {
final int number;
final int difficulty;
/// The achievement to unlock when the level is finished, if any.
final String? achievementIdIOS;
final String? achievementIdAndroid;
bool get awardsAchievement => achievementIdAndroid != null;
const GameLevel({
required this.number,
required this.difficulty,
this.achievementIdIOS,
this.achievementIdAndroid,
}) : assert(
(achievementIdAndroid != null && achievementIdIOS != null) ||
(achievementIdAndroid == null && achievementIdIOS == null),
'Either both iOS and Android achievement ID must be provided, '
'or none');
}
| samples/game_template/lib/src/level_selection/levels.dart/0 | {
"file_path": "samples/game_template/lib/src/level_selection/levels.dart",
"repo_id": "samples",
"token_count": 481
} | 1,230 |
// 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 'package:flutter/material.dart';
/// A widget that makes it easy to create a screen with a square-ish
/// main area, a smaller menu area, and a small area for a message on top.
/// It works in both orientations on mobile- and tablet-sized screens.
class ResponsiveScreen extends StatelessWidget {
/// This is the "hero" of the screen. It's more or less square, and will
/// be placed in the visual "center" of the screen.
final Widget squarishMainArea;
/// The second-largest area after [squarishMainArea]. It can be narrow
/// or wide.
final Widget rectangularMenuArea;
/// An area reserved for some static text close to the top of the screen.
final Widget topMessageArea;
/// How much bigger should the [squarishMainArea] be compared to the other
/// elements.
final double mainAreaProminence;
const ResponsiveScreen({
required this.squarishMainArea,
required this.rectangularMenuArea,
this.topMessageArea = const SizedBox.shrink(),
this.mainAreaProminence = 0.8,
super.key,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
// This widget wants to fill the whole screen.
final size = constraints.biggest;
final padding = EdgeInsets.all(size.shortestSide / 30);
if (size.height >= size.width) {
// "Portrait" / "mobile" mode.
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SafeArea(
bottom: false,
child: Padding(
padding: padding,
child: topMessageArea,
),
),
Expanded(
flex: (mainAreaProminence * 100).round(),
child: SafeArea(
top: false,
bottom: false,
minimum: padding,
child: squarishMainArea,
),
),
SafeArea(
top: false,
maintainBottomViewPadding: true,
child: Padding(
padding: padding,
child: rectangularMenuArea,
),
),
],
);
} else {
// "Landscape" / "tablet" mode.
final isLarge = size.width > 900;
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
flex: isLarge ? 7 : 5,
child: SafeArea(
right: false,
maintainBottomViewPadding: true,
minimum: padding,
child: squarishMainArea,
),
),
Expanded(
flex: 3,
child: Column(
children: [
SafeArea(
bottom: false,
left: false,
maintainBottomViewPadding: true,
child: Padding(
padding: padding,
child: topMessageArea,
),
),
Expanded(
child: SafeArea(
top: false,
left: false,
maintainBottomViewPadding: true,
child: Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: padding,
child: rectangularMenuArea,
),
),
),
)
],
),
),
],
);
}
},
);
}
}
| samples/game_template/lib/src/style/responsive_screen.dart/0 | {
"file_path": "samples/game_template/lib/src/style/responsive_screen.dart",
"repo_id": "samples",
"token_count": 2159
} | 1,231 |
// 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 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:window_size/window_size.dart';
import 'src/api/item.dart';
import 'src/catalog.dart';
import 'src/item_tile.dart';
void main() {
setupWindow();
runApp(const MyApp());
}
const double windowWidth = 480;
const double windowHeight = 854;
void setupWindow() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowTitle('Infinite List');
setWindowMinSize(const Size(windowWidth, windowHeight));
setWindowMaxSize(const Size(windowWidth, windowHeight));
getCurrentScreen().then((screen) {
setWindowFrame(Rect.fromCenter(
center: screen!.frame.center,
width: windowWidth,
height: windowHeight,
));
});
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<Catalog>(
create: (context) => Catalog(),
child: MaterialApp(
title: 'Infinite List Sample',
theme: ThemeData.light(),
home: const MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Infinite List Sample'),
),
body: Selector<Catalog, int?>(
// Selector is a widget from package:provider. It allows us to listen
// to only one aspect of a provided value. In this case, we are only
// listening to the catalog's `itemCount`, because that's all we need
// at this level.
selector: (context, catalog) => catalog.itemCount,
builder: (context, itemCount, child) => ListView.builder(
// When `itemCount` is null, `ListView` assumes an infinite list.
// Once we provide a value, it will stop the scrolling beyond
// the last element.
itemCount: itemCount,
padding: const EdgeInsets.symmetric(vertical: 18),
itemBuilder: (context, index) {
// Every item of the `ListView` is individually listening
// to the catalog.
var catalog = Provider.of<Catalog>(context);
// Catalog provides a single synchronous method for getting the
// current data.
return switch (catalog.getByIndex(index)) {
Item(isLoading: true) => const LoadingItemTile(),
var item => ItemTile(item: item)
};
},
),
),
);
}
}
| samples/infinite_list/lib/main.dart/0 | {
"file_path": "samples/infinite_list/lib/main.dart",
"repo_id": "samples",
"token_count": 1098
} | 1,232 |
package dev.flutter.isolate_example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/isolate_example/android/app/src/main/kotlin/dev/flutter/isolate_example/MainActivity.kt/0 | {
"file_path": "samples/isolate_example/android/app/src/main/kotlin/dev/flutter/isolate_example/MainActivity.kt",
"repo_id": "samples",
"token_count": 40
} | 1,233 |
#import "GeneratedPluginRegistrant.h"
| samples/navigation_and_routing/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/navigation_and_routing/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,234 |
// 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/material.dart';
import '../data.dart';
class AuthorList extends StatelessWidget {
final List<Author> authors;
final ValueChanged<Author>? onTap;
const AuthorList({
required this.authors,
this.onTap,
super.key,
});
@override
Widget build(BuildContext context) => ListView.builder(
itemCount: authors.length,
itemBuilder: (context, index) => ListTile(
title: Text(
authors[index].name,
),
subtitle: Text(
'${authors[index].books.length} books',
),
onTap: onTap != null ? () => onTap!(authors[index]) : null,
),
);
}
| samples/navigation_and_routing/lib/src/widgets/author_list.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/widgets/author_list.dart",
"repo_id": "samples",
"token_count": 339
} | 1,235 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Place Tracker rebuild script
steps:
- name: Remove runner
rmdirs:
- android
- ios
- web
- name: Rebuild Runner
flutter: create --org dev.flutter --platform android,ios,web .
- name: Update deps
flutter: pub upgrade --major-versions
- name: Patch android/app/build.gradle
path: android/app/build.gradle
patch-u: |
--- b/place_tracker/android/app/build.gradle
+++ a/place_tracker/android/app/build.gradle
@@ -43,9 +43,8 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "dev.flutter.place_tracker"
- // You can update the following values to match your application needs.
- // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
- minSdkVersion flutter.minSdkVersion
+ // Google Maps requires a minimum SDK version of 20
+ minSdkVersion 20
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
- name: Patch android/app/src/main/AndroidManifest.xml
path: android/app/src/main/AndroidManifest.xml
patch-u: |
--- b/place_tracker/android/app/src/main/AndroidManifest.xml
+++ a/place_tracker/android/app/src/main/AndroidManifest.xml
@@ -3,6 +3,12 @@
android:label="place_tracker"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
+ <meta-data
+ android:name="com.google.android.gms.version"
+ android:value="@integer/google_play_services_version" />
+ <meta-data
+ android:name="com.google.android.geo.API_KEY"
+ android:value="YOUR API KEY HERE" />
<activity
android:name=".MainActivity"
android:exported="true"
- name: Patch ios/Runner/AppDelegate.swift
path: ios/Runner/AppDelegate.swift
patch-u: |
--- b/place_tracker/ios/Runner/AppDelegate.swift
+++ a/place_tracker/ios/Runner/AppDelegate.swift
@@ -1,5 +1,6 @@
import UIKit
import Flutter
+import GoogleMaps
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
@@ -7,6 +8,7 @@ import Flutter
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
+ GMSServices.provideAPIKey("YOUR KEY HERE")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
- name: Patch ios/Flutter/AppFrameworkInfo.plist
path: ios/Flutter/AppFrameworkInfo.plist
patch-u: |
--- b/place_tracker/ios/Flutter/AppFrameworkInfo.plist
+++ a/place_tracker/ios/Flutter/AppFrameworkInfo.plist
@@ -21,6 +21,6 @@
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
- <string>11.0</string>
+ <string>13.0</string>
</dict>
</plist>
- name: Patch ios/Podfile
path: ios/Podfile
patch-u: |
--- b/place_tracker/ios/Podfile
+++ a/place_tracker/ios/Podfile
@@ -1,5 +1,5 @@
-# Uncomment this line to define a global platform for your project
-# platform :ios, '11.0'
+# Google Maps requires iOS 13: https://developers.google.com/maps/documentation/ios-sdk/overview#supported_platforms
+platform :ios, '13.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
- name: Patch web/index.html
path: web/index.html
patch-u: |
--- b/place_tracker/web/index.html
+++ a/place_tracker/web/index.html
@@ -32,6 +32,9 @@
<title>place_tracker</title>
<link rel="manifest" href="manifest.json">
+ <!-- Google Maps: https://pub.dev/packages/google_maps_flutter_web -->
+ <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
+
<script>
// The value below is injected by flutter build, do not touch.
const serviceWorkerVersion = null;
- name: Build iOS simulator bundle
platforms: [ macos ]
flutter: build ios --simulator
| samples/place_tracker/codelab_rebuild.yaml/0 | {
"file_path": "samples/place_tracker/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 2078
} | 1,236 |
name: place_tracker
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
google_maps_flutter: ^2.2.0
provider: ^6.0.2
uuid: ^4.0.0
go_router: ">=10.0.0 <14.0.0"
collection: ^1.16.0
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
assets:
- assets/
uses-material-design: true
| samples/place_tracker/pubspec.yaml/0 | {
"file_path": "samples/place_tracker/pubspec.yaml",
"repo_id": "samples",
"token_count": 210
} | 1,237 |
// 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 CoreMotion
class AccelerometerStreamHandler: NSObject, FlutterStreamHandler {
var motionManager: CMMotionManager;
override init() {
motionManager = CMMotionManager()
}
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
if !motionManager.isAccelerometerAvailable {
events(FlutterError(code: "SENSOR_UNAVAILABLE", message: "Accelerometer is not available", details: nil))
}
motionManager.accelerometerUpdateInterval = 0.1
motionManager.startAccelerometerUpdates(to: OperationQueue.main) {(data, error) in
guard let accelerationData = data?.acceleration else {
events(FlutterError(code: "DATA_UNAVAILABLE", message: "Cannot get accelerometer data", details: nil ))
return
}
events([accelerationData.x, accelerationData.y, accelerationData.z])
}
return nil
}
func onCancel(withArguments arguments: Any?) -> FlutterError? {
return nil
}
}
| samples/platform_channels/ios/Runner/AccelerometerStreamHandler.swift/0 | {
"file_path": "samples/platform_channels/ios/Runner/AccelerometerStreamHandler.swift",
"repo_id": "samples",
"token_count": 530
} | 1,238 |
// 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 includes the implementation for [EventChannel] to listen to value
/// changes from the Accelerometer sensor from native side. It has a [readings]
/// getter to provide a stream of [AccelerometerReadings].
class Accelerometer {
static const _eventChannel = EventChannel('eventChannelDemo');
/// Method responsible for providing a stream of [AccelerometerReadings] to listen
/// to value changes from the Accelerometer sensor.
static Stream<AccelerometerReadings> get readings {
return _eventChannel.receiveBroadcastStream().map(
(dynamic event) => AccelerometerReadings(
event[0] as double,
event[1] as double,
event[2] as double,
),
);
}
}
class AccelerometerReadings {
/// Acceleration force along the x-axis.
final double x;
/// Acceleration force along the y-axis.
final double y;
/// Acceleration force along the z-axis.
final double z;
AccelerometerReadings(this.x, this.y, this.z);
}
| samples/platform_channels/lib/src/accelerometer_event_channel.dart/0 | {
"file_path": "samples/platform_channels/lib/src/accelerometer_event_channel.dart",
"repo_id": "samples",
"token_count": 376
} | 1,239 |
// 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 'news_tab.dart';
import 'profile_tab.dart';
import 'settings_tab.dart';
import 'songs_tab.dart';
import 'widgets.dart';
void main() => runApp(const MyAdaptingApp());
class MyAdaptingApp extends StatelessWidget {
const MyAdaptingApp({super.key});
@override
Widget build(context) {
// Either Material or Cupertino widgets work in either Material or Cupertino
// Apps.
return MaterialApp(
title: 'Adaptive Music App',
theme: ThemeData(
// Use the green theme for Material widgets.
primarySwatch: Colors.green,
),
darkTheme: ThemeData.dark(),
builder: (context, child) {
return CupertinoTheme(
// Instead of letting Cupertino widgets auto-adapt to the Material
// theme (which is green), this app will use a different theme
// for Cupertino (which is blue by default).
data: const CupertinoThemeData(),
child: Material(child: child),
);
},
home: const PlatformAdaptingHomePage(),
);
}
}
// Shows a different type of scaffold depending on the platform.
//
// This file has the most amount of non-sharable code since it behaves the most
// differently between the platforms.
//
// These differences are also subjective and have more than one 'right' answer
// depending on the app and content.
class PlatformAdaptingHomePage extends StatefulWidget {
const PlatformAdaptingHomePage({super.key});
@override
State<PlatformAdaptingHomePage> createState() =>
_PlatformAdaptingHomePageState();
}
class _PlatformAdaptingHomePageState extends State<PlatformAdaptingHomePage> {
// This app keeps a global key for the songs tab because it owns a bunch of
// data. Since changing platform re-parents those tabs into different
// scaffolds, keeping a global key to it lets this app keep that tab's data as
// the platform toggles.
//
// This isn't needed for apps that doesn't toggle platforms while running.
final songsTabKey = GlobalKey();
// In Material, this app uses the hamburger menu paradigm and flatly lists
// all 4 possible tabs. This drawer is injected into the songs tab which is
// actually building the scaffold around the drawer.
Widget _buildAndroidHomePage(BuildContext context) {
return SongsTab(
key: songsTabKey,
androidDrawer: _AndroidDrawer(),
);
}
// On iOS, the app uses a bottom tab paradigm. Here, each tab view sits inside
// a tab in the tab scaffold. The tab scaffold also positions the tab bar
// in a row at the bottom.
//
// An important thing to note is that while a Material Drawer can display a
// large number of items, a tab bar cannot. To illustrate one way of adjusting
// for this, the app folds its fourth tab (the settings page) into the
// third tab. This is a common pattern on iOS.
Widget _buildIosHomePage(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const [
BottomNavigationBarItem(
label: SongsTab.title,
icon: SongsTab.iosIcon,
),
BottomNavigationBarItem(
label: NewsTab.title,
icon: NewsTab.iosIcon,
),
BottomNavigationBarItem(
label: ProfileTab.title,
icon: ProfileTab.iosIcon,
),
],
),
tabBuilder: (context, index) {
assert(index <= 2 && index >= 0, 'Unexpected tab index: $index');
return switch (index) {
0 => CupertinoTabView(
defaultTitle: SongsTab.title,
builder: (context) => SongsTab(key: songsTabKey),
),
1 => CupertinoTabView(
defaultTitle: NewsTab.title,
builder: (context) => const NewsTab(),
),
2 => CupertinoTabView(
defaultTitle: ProfileTab.title,
builder: (context) => const ProfileTab(),
),
_ => const SizedBox.shrink(),
};
},
);
}
@override
Widget build(context) {
return PlatformWidget(
androidBuilder: _buildAndroidHomePage,
iosBuilder: _buildIosHomePage,
);
}
}
class _AndroidDrawer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Drawer(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DrawerHeader(
decoration: const BoxDecoration(color: Colors.green),
child: Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Icon(
Icons.account_circle,
color: Colors.green.shade800,
size: 96,
),
),
),
ListTile(
leading: SongsTab.androidIcon,
title: const Text(SongsTab.title),
onTap: () {
Navigator.pop(context);
},
),
ListTile(
leading: NewsTab.androidIcon,
title: const Text(NewsTab.title),
onTap: () {
Navigator.pop(context);
Navigator.push<void>(context,
MaterialPageRoute(builder: (context) => const NewsTab()));
},
),
ListTile(
leading: ProfileTab.androidIcon,
title: const Text(ProfileTab.title),
onTap: () {
Navigator.pop(context);
Navigator.push<void>(context,
MaterialPageRoute(builder: (context) => const ProfileTab()));
},
),
// Long drawer contents are often segmented.
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: Divider(),
),
ListTile(
leading: SettingsTab.androidIcon,
title: const Text(SettingsTab.title),
onTap: () {
Navigator.pop(context);
Navigator.push<void>(context,
MaterialPageRoute(builder: (context) => const SettingsTab()));
},
),
],
),
);
}
}
| samples/platform_design/lib/main.dart/0 | {
"file_path": "samples/platform_design/lib/main.dart",
"repo_id": "samples",
"token_count": 2648
} | 1,240 |
include: package:analysis_defaults/flutter.yaml
| samples/provider_counter/analysis_options.yaml/0 | {
"file_path": "samples/provider_counter/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,241 |
# provider_shopper
A Flutter sample app that shows a state management approach using the [Provider][] package.
This is the app discussed in the [Simple app state management][simple] section of
[flutter.dev][].
[Provider]: https://pub.dev/packages/provider
[simple]: https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple
[flutter.dev]: https://flutter.dev/
## Goals for this sample
* Show simple use of `Provider` for providing an immutable value to a subtree
* Illustrate a simple state management approach using the ChangeNotifier class
* Show use of `ProxyProvider` for provided objects that depend on other provided objects
## The important bits
### `lib/main.dart`
Here the app sets up objects it needs to track state: a catalog and a shopping cart. It builds
a `MultiProvider` to provide both objects at once to widgets further down the tree.
The `CartModel` instance is provided using a `ChangeNotifierProxyProvider`, which combines
two types of functionality:
1. It will automatically subscribe to changes in `CartModel` (if you only want this functionality
simply use `ChangeNotifierProvider`).
2. It takes the value of a previously provided object (in this case, `CatalogModel`, provided
just above), and uses it to build the value of `CartModel` (if you only want
_this_ functionality, simply use `ProxyProvider`).
### `lib/models/*`
This directory contains the model classes that are provided in `main.dart`. These classes
represent the app state.
### `lib/screens/*`
This directory contains widgets used to construct the two screens of the app: the catalog and
the cart. These widgets have access to the current state of both the catalog and the cart
via `Provider.of`.
## Questions/issues
If you have a general question about Provider, the best places to go are:
* [Provider documentation](https://pub.dev/documentation/provider/latest/)
* [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
If you run into an issue with the sample itself, please file an issue
in the [main Flutter repo](https://github.com/flutter/flutter/issues).
| samples/provider_shopper/README.md/0 | {
"file_path": "samples/provider_shopper/README.md",
"repo_id": "samples",
"token_count": 549
} | 1,242 |
// 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:provider_shopper/main.dart';
import 'package:provider_shopper/models/cart.dart';
import 'package:provider_shopper/models/catalog.dart';
void main() {
testWidgets('Login page Widget test', (tester) async {
await tester.pumpWidget(MultiProvider(
providers: [
Provider(create: (context) => CatalogModel()),
ChangeNotifierProxyProvider<CatalogModel, CartModel>(
create: (context) => CartModel(),
update: (context, catalog, cart) {
cart!.catalog = catalog;
return cart;
},
),
],
child: MaterialApp.router(routerConfig: router()),
));
// Verifying the behaviour of ENTER button.
await tester.tap(find.text('ENTER'));
await tester.pumpAndSettle();
expect(find.text('Catalog'), findsOneWidget);
});
}
| samples/provider_shopper/test/login_widget_test.dart/0 | {
"file_path": "samples/provider_shopper/test/login_widget_test.dart",
"repo_id": "samples",
"token_count": 424
} | 1,243 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/simplistic_calculator/android/gradle.properties/0 | {
"file_path": "samples/simplistic_calculator/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,244 |
include: package:analysis_defaults/flutter.yaml
| samples/simplistic_editor/analysis_options.yaml/0 | {
"file_path": "samples/simplistic_editor/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,245 |
import 'package:flutter/material.dart';
import 'app_state.dart';
import 'app_state_manager.dart';
import 'basic_text_field.dart';
import 'formatting_toolbar.dart';
import 'replacements.dart';
import 'text_editing_delta_history_view.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return AppStateWidget(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Simplistic Editor',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Simplistic Editor'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late ReplacementTextEditingController _replacementTextEditingController;
final FocusNode _focusNode = FocusNode();
@override
void initState() {
super.initState();
_replacementTextEditingController = ReplacementTextEditingController();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_replacementTextEditingController =
AppStateManager.of(context).appState.replacementsController;
}
static Route<Object?> _aboutDialogBuilder(
BuildContext context, Object? arguments) {
const String aboutContent =
'TextEditingDeltas are a new feature in the latest Flutter stable release that give the user'
' finer grain control over the changes that occur during text input. There are four types of'
' deltas: Insertion, Deletion, Replacement, and NonTextUpdate. To gain access to these TextEditingDeltas'
' you must implement DeltaTextInputClient, and set enableDeltaModel to true in the TextInputConfiguration.'
' Before Flutter only provided the TextInputClient, which does not provide a delta between the current'
' and previous text editing states. DeltaTextInputClient does provide these deltas, allowing the user to build'
' more powerful rich text editing applications such as this small example. This feature is supported on all platforms.';
return DialogRoute<void>(
context: context,
builder: (context) => const AlertDialog(
title: Center(child: Text('About')),
content: Text(aboutContent),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).restorablePush(_aboutDialogBuilder);
},
icon: const Icon(Icons.info_outline),
),
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Column(
children: [
const FormattingToolbar(),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 35.0),
child: BasicTextField(
controller: _replacementTextEditingController,
style: const TextStyle(
fontSize: 18.0,
color: Colors.black,
),
focusNode: _focusNode,
),
),
),
const Expanded(
child: TextEditingDeltaHistoryView(),
),
],
),
),
),
);
}
}
| samples/simplistic_editor/lib/main.dart/0 | {
"file_path": "samples/simplistic_editor/lib/main.dart",
"repo_id": "samples",
"token_count": 1524
} | 1,246 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/simplistic_editor/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/simplistic_editor/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,247 |
// 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 'package:flutter/foundation.dart';
import 'package:veggieseasons/data/local_veggie_provider.dart';
import 'package:veggieseasons/data/veggie.dart';
class AppState extends ChangeNotifier {
final List<Veggie> _veggies;
AppState() : _veggies = LocalVeggieProvider.veggies;
List<Veggie> get allVeggies => List<Veggie>.from(_veggies);
List<Veggie> get availableVeggies {
var currentSeason = _getSeasonForDate(DateTime.now());
return _veggies.where((v) => v.seasons.contains(currentSeason)).toList();
}
List<Veggie> get favoriteVeggies =>
_veggies.where((v) => v.isFavorite).toList();
List<Veggie> get unavailableVeggies {
var currentSeason = _getSeasonForDate(DateTime.now());
return _veggies.where((v) => !v.seasons.contains(currentSeason)).toList();
}
Veggie getVeggie(int? id) => _veggies.singleWhere((v) => v.id == id);
List<Veggie> searchVeggies(String? terms) => _veggies
.where((v) => v.name.toLowerCase().contains(terms!.toLowerCase()))
.toList();
void setFavorite(int? id, bool isFavorite) {
var veggie = getVeggie(id);
veggie.isFavorite = isFavorite;
notifyListeners();
}
/// Used in tests to set the season independent of the current date.
static Season? debugCurrentSeason;
static Season? _getSeasonForDate(DateTime date) {
if (debugCurrentSeason != null) {
return debugCurrentSeason;
}
// Technically the start and end dates of seasons can vary by a day or so,
// but this is close enough for produce.
switch (date.month) {
case 1:
return Season.winter;
case 2:
return Season.winter;
case 3:
return date.day < 21 ? Season.winter : Season.spring;
case 4:
return Season.spring;
case 5:
return Season.spring;
case 6:
return date.day < 21 ? Season.spring : Season.summer;
case 7:
return Season.summer;
case 8:
return Season.summer;
case 9:
return date.day < 22 ? Season.autumn : Season.winter;
case 10:
return Season.autumn;
case 11:
return Season.autumn;
case 12:
return date.day < 22 ? Season.autumn : Season.winter;
default:
throw ArgumentError('Can\'t return a season for month #${date.month}.');
}
}
}
| samples/veggieseasons/lib/data/app_state.dart/0 | {
"file_path": "samples/veggieseasons/lib/data/app_state.dart",
"repo_id": "samples",
"token_count": 932
} | 1,248 |
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:veggieseasons/data/app_state.dart';
import 'package:veggieseasons/data/veggie.dart';
import 'package:veggieseasons/styles.dart';
/// Presents a series of trivia questions about a particular widget, and tracks
/// the user's score.
class TriviaView extends StatefulWidget {
final int? id;
final String? restorationId;
const TriviaView({this.id, this.restorationId, super.key});
@override
State<TriviaView> createState() => _TriviaViewState();
}
/// Possible states of the game.
enum PlayerStatus {
readyToAnswer,
wasCorrect,
wasIncorrect,
}
class _TriviaViewState extends State<TriviaView> with RestorationMixin {
/// Current app state. This is used to fetch veggie data.
late AppState appState;
/// The veggie trivia about which to show.
late Veggie veggie;
/// Index of the current trivia question.
RestorableInt triviaIndex = RestorableInt(0);
/// User's score on the current veggie.
RestorableInt score = RestorableInt(0);
/// Trivia question currently being displayed.
Trivia get currentTrivia => veggie.trivia[triviaIndex.value];
/// The current state of the game.
_RestorablePlayerStatus status =
_RestorablePlayerStatus(PlayerStatus.readyToAnswer);
@override
String? get restorationId => widget.restorationId;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(triviaIndex, 'index');
registerForRestoration(score, 'score');
registerForRestoration(status, 'status');
}
// Called at init and again if any dependencies (read: InheritedWidgets) on
// on which this object relies are changed.
@override
void didChangeDependencies() {
super.didChangeDependencies();
final newAppState = Provider.of<AppState>(context);
setState(() {
appState = newAppState;
veggie = appState.getVeggie(widget.id);
});
}
// Called when the widget associated with this object is swapped out for a new
// one. If the new widget has a different Veggie ID value, the state object
// needs to do a little work to reset itself for the new Veggie.
@override
void didUpdateWidget(TriviaView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.id != widget.id) {
setState(() {
veggie = appState.getVeggie(widget.id);
});
_resetGame();
}
}
@override
void dispose() {
triviaIndex.dispose();
score.dispose();
status.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (triviaIndex.value >= veggie.trivia.length) {
return _buildFinishedView();
} else if (status.value == PlayerStatus.readyToAnswer) {
return _buildQuestionView();
} else {
return _buildResultView();
}
}
void _resetGame() {
setState(() {
triviaIndex.value = 0;
score.value = 0;
status.value = PlayerStatus.readyToAnswer;
});
}
void _processAnswer(int answerIndex) {
setState(() {
if (answerIndex == currentTrivia.correctAnswerIndex) {
status.value = PlayerStatus.wasCorrect;
score.value++;
} else {
status.value = PlayerStatus.wasIncorrect;
}
});
}
// Widget shown when the game is over. It includes the score and a button to
// restart everything.
Widget _buildFinishedView() {
final themeData = CupertinoTheme.of(context);
return Padding(
padding: const EdgeInsets.all(32),
child: Column(
children: [
Text(
'All done!',
style: Styles.triviaFinishedTitleText(themeData),
),
const SizedBox(height: 16),
Text('You answered', style: themeData.textTheme.textStyle),
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
'${score.value}',
style: Styles.triviaFinishedBigText(themeData),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(' of ', style: themeData.textTheme.textStyle),
),
Text(
'${veggie.trivia.length}',
style: Styles.triviaFinishedBigText(themeData),
),
],
),
Text('questions correctly!', style: themeData.textTheme.textStyle),
const SizedBox(height: 16),
CupertinoButton(
child: const Text('Try Again'),
onPressed: () => _resetGame(),
),
],
),
);
}
// Presents the current trivia's question and answer choices.
Widget _buildQuestionView() {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
const SizedBox(height: 16),
Text(
currentTrivia.question,
style: CupertinoTheme.of(context).textTheme.textStyle,
),
const SizedBox(height: 32),
for (int i = 0; i < currentTrivia.answers.length; i++)
Padding(
padding: const EdgeInsets.all(8),
child: CupertinoButton(
color: CupertinoColors.activeBlue,
child: Text(
currentTrivia.answers[i],
textAlign: TextAlign.center,
),
onPressed: () => _processAnswer(i),
),
),
],
),
);
}
// Shows whether the last answer was right or wrong and prompts the user to
// continue through the game.
Widget _buildResultView() {
return Padding(
padding: const EdgeInsets.all(32),
child: Column(
children: [
Text(
status.value == PlayerStatus.wasCorrect
? 'That\'s right!'
: 'Sorry, that wasn\'t the right answer.',
style: CupertinoTheme.of(context).textTheme.textStyle,
),
const SizedBox(height: 16),
CupertinoButton(
child: const Text('Next Question'),
onPressed: () => setState(() {
triviaIndex.value++;
status.value = PlayerStatus.readyToAnswer;
}),
),
],
),
);
}
}
class _RestorablePlayerStatus extends RestorableValue<PlayerStatus> {
_RestorablePlayerStatus(this._defaultValue);
final PlayerStatus _defaultValue;
@override
PlayerStatus createDefaultValue() {
return _defaultValue;
}
@override
PlayerStatus fromPrimitives(Object? data) {
return PlayerStatus.values[data as int];
}
@override
Object toPrimitives() {
return value.index;
}
@override
void didUpdateValue(PlayerStatus? oldValue) {
notifyListeners();
}
}
| samples/veggieseasons/lib/widgets/trivia.dart/0 | {
"file_path": "samples/veggieseasons/lib/widgets/trivia.dart",
"repo_id": "samples",
"token_count": 2848
} | 1,249 |
name: veggieseasons
description: An iOS app that shows the fruits and veggies currently in season.
publish_to: none
version: 1.2.0
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
font_awesome_flutter: ^10.1.0
intl: ^0.19.0
provider: ^6.0.1
shared_preferences: ^2.0.14
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding
path: plugins/window_size
# TODO: https://github.com/flutter/samples/issues/1838
# go_router ^7.1.0 is breaking the state restoration tests
go_router: 7.0.2
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter_launcher_icons: ^0.13.0
flutter:
assets:
- assets/images/apple.jpg
- assets/images/artichoke.jpg
- assets/images/asparagus.jpg
- assets/images/avocado.jpg
- assets/images/blackberry.jpg
- assets/images/cantaloupe.jpg
- assets/images/cauliflower.jpg
- assets/images/endive.jpg
- assets/images/fig.jpg
- assets/images/grape.jpg
- assets/images/green_bell_pepper.jpg
- assets/images/habanero.jpg
- assets/images/kale.jpg
- assets/images/kiwi.jpg
- assets/images/lemon.jpg
- assets/images/lime.jpg
- assets/images/mango.jpg
- assets/images/mushroom.jpg
- assets/images/nectarine.jpg
- assets/images/persimmon.jpg
- assets/images/plum.jpg
- assets/images/potato.jpg
- assets/images/radicchio.jpg
- assets/images/radish.jpg
- assets/images/squash.jpg
- assets/images/strawberry.jpg
- assets/images/tangelo.jpg
- assets/images/tomato.jpg
- assets/images/watermelon.jpg
- assets/images/orange_bell_pepper.jpg
fonts:
- family: NotoSans
fonts:
- asset: assets/fonts/NotoSans-Regular.ttf
weight: 400
- asset: assets/fonts/NotoSans-Bold.ttf
weight: 700
- asset: assets/fonts/NotoSans-BoldItalic.ttf
weight: 700
style: italic
- asset: assets/fonts/NotoSans-Italic.ttf
style: italic
weight: 400
flutter_icons:
ios: true
image_path: "assets/icon/launcher_icon.png"
| samples/veggieseasons/pubspec.yaml/0 | {
"file_path": "samples/veggieseasons/pubspec.yaml",
"repo_id": "samples",
"token_count": 951
} | 1,250 |
include: package:lints/recommended.yaml
| samples/web/_tool/analysis_options.yaml/0 | {
"file_path": "samples/web/_tool/analysis_options.yaml",
"repo_id": "samples",
"token_count": 13
} | 1,251 |
// 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:grinder/grinder.dart';
import 'package:image/image.dart' as image;
import 'package:path/path.dart' as path;
import 'package:samples_index/samples_index.dart';
import 'package:samples_index/src/templates.dart' as templates;
Future<void> main(List<String> args) => grind(args);
@Task('Run tests in the VM')
Future<void> testCli() async =>
await TestRunner().testAsync(platformSelector: 'vm');
@Task()
void analyze() {
run('dart', arguments: const ['analyze', '--fatal-infos', '.']);
}
@Task('deploy')
@Depends(analyze, testCli, generate, buildRelease)
void deploy() {
log('All tasks completed. ');
log('');
}
@Task('Run build_runner to public/ directory')
@Depends(createThumbnails)
Future<void> buildRelease() async {
var app = PubApp.local('build_runner');
await app.runAsync(
'build --release --output web:public --delete-conflicting-outputs'
.split(' ')
.toList());
}
@DefaultTask('Build the project.')
@Depends(clean)
Future<void> generate() async {
var samples = await getSamples();
log('Generating index for ${samples.length} samples...');
var outputFile = File('web/index.html');
await outputFile.create(recursive: true);
await outputFile.writeAsString(templates.index(samples));
var futures = <Future<void>>[];
for (final sample in samples) {
var file = File('web/${sample.filename}.html');
var future = file.create(recursive: true).then((_) async {
await file.writeAsString(templates.description(sample));
});
futures.add(future);
}
await Future.wait<void>(futures);
log('Generated index for ${samples.length} samples.');
}
@Task('creates thumbnail images in web/images')
Future<void> createThumbnails() async {
await _createThumbnails(Directory('web/images'));
}
// Creates a thumbnail image for each png file
Future<void> _createThumbnails(Directory directory) async {
var files = await directory.list().toList();
var filesToWrite = <Future<void>>{};
for (final entity in files) {
var extension = path.extension(entity.path);
var filename = path.basenameWithoutExtension(entity.path);
if (extension != '.png' || entity is! File || filename.endsWith('_thumb')) {
continue;
}
var pathPrefix = path.dirname(entity.path);
var thumbnailFile = File(path.join(pathPrefix, '${filename}_thumb.png'));
var img = image.decodeImage(await entity.readAsBytes());
var resized = image.copyResize(img!, width: 640);
filesToWrite.add(thumbnailFile.writeAsBytes(image.encodePng(resized)));
}
await Future.wait<void>(filesToWrite);
}
@Task('remove generated HTML files')
Future<void> clean() async {
var tasks = <Future<void>>[];
await for (final file in Directory('web').list(recursive: true)) {
if (path.extension(file.path) == '.html') {
tasks.add(file.delete());
}
}
await Future.wait<void>(tasks);
}
| samples/web/samples_index/tool/grind.dart/0 | {
"file_path": "samples/web/samples_index/tool/grind.dart",
"repo_id": "samples",
"token_count": 1045
} | 1,252 |
@font-face {
font-family: "DM Sans";
src: url(../fonts/DMSans-Regular.ttf);
font-weight: normal;
}
@font-face {
font-family: "DM Sans";
src: url(../fonts/DMSans-Bold.ttf);
font-weight: 700;
}
/** Reset */
* {
box-sizing: border-box;
font-family: "DM Sans", sans-serif;
}
html, body {
margin: 0;
padding: 0;
min-height: 100vh;
}
body {
background-color: #fff;
background-image: radial-gradient(
ellipse at bottom,
#fafafa 5%,
transparent 60%
),
linear-gradient(136deg, transparent, #eee 290%),
linear-gradient(115deg, #fafafa, transparent 40%),
linear-gradient(180deg, transparent 0, #ddd 70%),
radial-gradient(ellipse at -70% -180%, transparent 80%, #eee 0),
radial-gradient(ellipse at bottom, #71c7ee 40%, transparent 80%),
radial-gradient(ellipse at 5% 340%, transparent 80%, #ddd 0);
background-repeat: no-repeat;
color: #555;
}
/** Layout **/
body { display: flex; flex-direction: column; }
section.contents {
flex: 1 1 auto;
flex-direction: row;
display: flex;
}
section.contents aside {
flex: 0;
display: flex;
flex-direction: column;
order: -1;
}
section.contents aside fieldset {
display: flex;
flex-flow: wrap;
justify-content: space-between;
align-items: flex-end;
}
section.contents aside .align-top {
align-self: flex-start;
}
section.contents article {
flex: 1;
margin-top: 50px;
display: flex;
justify-content: center;
overflow: hidden;
}
/** Title */
h1 {
font-weight: 700;
font-size: 48px;
padding: 0;
line-height: .9em;
letter-spacing: -2px;
margin: 0 0 30px 0;
}
/** Controls for the demo (left column) */
#demo_controls {
background: linear-gradient(90deg, rgba(255,255,255,1) 10%, rgba(255,255,255,0) 100%);
padding: 40px 20px 0px 20px;
z-index: 10;
}
#demo_controls fieldset {
padding: 0;
border: none;
width: 210px;
}
#demo_controls legend {
text-align: center;
font-size: 20px;
line-height: 40px;
margin-bottom: 3px;
}
#demo_controls select.screen {
display: block;
width: 120px;
padding: 4px;
text-align: center;
margin-bottom: 10px;
}
#demo_controls input {
display: block;
width: 100px;
margin: 0 0 10px 0;
text-align: center;
}
/** Keep controls that */
#demo_controls .tight input {
margin: 0px;
}
#demo_controls input[type="button"] {
line-height: 10px;
font-size: 14px;
border-radius: 15px;
border: 1px solid #aaa;
border-style: outset;
background-color: #fff;
height: 30px;
color: #555;
transition: all 100ms ease-in-out;
cursor: pointer;
}
#demo_controls input[type="button"]:hover {
/* .active:hover background-color: #96B6E3;*/
border-color: #1c68d4;
background-color: #1c68d4;
color: white;
}
#demo_controls input[type="button"].active {
border-color: #1c68d4;
background-color: #1c68d4;
color: white;
}
#demo_controls input#value {
font-size: 32px;
line-height: 1em;
min-height: 30px;
color: #888;
}
#demo_controls input#increment {
/* Center vertically next to taller input#value */
position: relative;
top: -6px;
}
#demo_controls .disabled {
pointer-events: none;
opacity: .5;
}
/** The style for the DIV where flutter will be rendered, and the CSS fx */
#flutter_target {
border: 1px solid #aaa;
width: 320px;
height: 480px;
border-radius: 0px;
transition: all 150ms ease-in;
align-self: center;
}
#flutter_target.resize {
width: 480px;
height: 320px;
}
#flutter_target.spin { animation: spin 6400ms ease-in-out infinite; }
#flutter_target.shadow { position: relative; }
#flutter_target.shadow::before {
content: "";
position: absolute;
display: block;
width: 100%;
top: calc(100% - 1px);
left: 0;
height: 1px;
background-color: black;
border-radius: 50%;
z-index: -1;
transform: rotateX(80deg);
box-shadow: 0px 0px 60px 38px rgb(0 0 0 / 25%);
}
#flutter_target.mirror {
-webkit-box-reflect: below 0px linear-gradient(to bottom, rgba(0,0,0,0.0), rgba(0,0,0,0.4));
}
@keyframes spin {
0% {
transform: perspective(1000px) rotateY(0deg);
animation-timing-function: ease-in;
}
15% {
transform: perspective(1000px) rotateY(165deg);
animation-timing-function: linear;
}
75% {
transform: perspective(1000px) rotateY(195deg);
animation-timing-function: linear;
}
90% {
transform: perspective(1000px) rotateY(359deg);
animation-timing-function: ease-out;
}
100% {
transform: perspective(1000px) rotateY(359deg);
animation-timing-function: linear;
}
}
/** "Handheld"/Device mode container */
#handheld::before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: url(../icons/unsplash-x9WGMWwp1NM.png) no-repeat;
background-size: 1000px;
background-position: top right;
opacity: 1;
transition: opacity 200ms ease-out;
}
#handheld::after {
content: "";
position: absolute;
display: block;
width: 77px;
height: 67px;
top: 534px;
right: 573px;
background: url(../icons/nail.png) no-repeat;
background-size: 77px;
opacity: 1;
transition: opacity 200ms ease-out;
}
#handheld.hidden::before,
#handheld.hidden::after {
opacity: 0;
}
#flutter_target.handheld {
position: absolute;
right: 0px;
transform-origin: 0px 0px 0px;
transform: rotate(-14.1deg) scale(0.80) translate(-539px, -45px);
width: 316px;
height: 678px;
border-radius: 34px;
border: 1px solid #000;
overflow: hidden;
align-self: initial;
}
.imageAttribution {
position: absolute;
bottom: 6px;
right: 6px;
font-size: 10px;
}
.imageAttribution, .imageAttribution a { color: #fff; } | samples/web_embedding/element_embedding_demo/web/css/style.css/0 | {
"file_path": "samples/web_embedding/element_embedding_demo/web/css/style.css",
"repo_id": "samples",
"token_count": 2185
} | 1,253 |
name: ng_companion
description: A flutter app with a counter that can be manipulated from JS.
publish_to: 'none'
version: 1.0.0
environment:
sdk: ^3.3.0
flutter: ">=3.19.0"
dependencies:
flutter:
sdk: flutter
web: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
assets:
- assets/
| samples/web_embedding/ng-flutter/flutter/pubspec.yaml/0 | {
"file_path": "samples/web_embedding/ng-flutter/flutter/pubspec.yaml",
"repo_id": "samples",
"token_count": 161
} | 1,254 |
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, Routes } from '@angular/router';
import { AppComponent } from './app/app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { importProvidersFrom } from '@angular/core';
const appRoutes: Routes = [];
bootstrapApplication(AppComponent, {
providers: [
provideRouter(appRoutes),
importProvidersFrom(BrowserAnimationsModule)
]
})
| samples/web_embedding/ng-flutter/src/main.ts/0 | {
"file_path": "samples/web_embedding/ng-flutter/src/main.ts",
"repo_id": "samples",
"token_count": 143
} | 1,255 |
# Default Codeowners
* @atsansone @parlough @sfshaza2 @domesticmouse @MaryaBelanger
# Covers staging and deploying with Cloud Build
/cloud_build/ @parlough @khanhnwin @sfshaza2 @atsansone
# Covers all web content
/src/ @sfshaza2 @atsansone @parlough @domesticmouse @MaryaBelanger
# Covers Jekyll plugins
/src/_plugins/ @khanhnwin @parlough @sfshaza2 @atsansone @domesticmouse @MaryaBelanger
# Covers website styles
/src/_sass/ @khanhnwin @parlough @sfshaza2 @atsansone @domesticmouse @MaryaBelanger
# Covers website tooling
/tool/ @sfshaza2 @atsansone @parlough @khanhnwin @domesticmouse @MaryaBelanger
# Covers examples in files
/examples/ @sfshaza2 @domesticmouse @johnpryan @khanhnwin @parlough @MaryaBelanger @atsansone
# Covers all configuration files for the website
/* @sfshaza2 @atsansone @parlough @khanhnwin @domesticmouse @MaryaBelanger
| website/CODEOWNERS/0 | {
"file_path": "website/CODEOWNERS",
"repo_id": "website",
"token_count": 326
} | 1,256 |
name: basic_hero_transition
publish_to: none
description: >-
Shows how to create a simple or Hero animation using the Hero class directly.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../example_utils
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/flippers-alpha.png
| website/examples/_animation/basic_hero_animation/pubspec.yaml/0 | {
"file_path": "website/examples/_animation/basic_hero_animation/pubspec.yaml",
"repo_id": "website",
"token_count": 144
} | 1,257 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Opacity Demo';
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
// The StatefulWidget's job is to take data and create a State class.
// In this case, the widget takes a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
required this.title,
});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
// The State class is responsible for two things: holding some data you can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
// Whether the green box should be visible
bool _visible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
// #docregion AnimatedOpacity
child: AnimatedOpacity(
// If the widget is visible, animate to 0.0 (invisible).
// If the widget is hidden, animate to 1.0 (fully visible).
opacity: _visible ? 1.0 : 0.0,
duration: const Duration(milliseconds: 500),
// The green box must be a child of the AnimatedOpacity widget.
// #docregion Container
child: Container(
width: 200,
height: 200,
color: Colors.green,
),
// #enddocregion Container
),
// #enddocregion AnimatedOpacity
),
// #docregion FAB
floatingActionButton: FloatingActionButton(
onPressed: () {
// Call setState. This tells Flutter to rebuild the
// UI with the changes.
setState(() {
_visible = !_visible;
});
},
tooltip: 'Toggle Opacity',
child: const Icon(Icons.flip),
),
// #enddocregion FAB
);
}
}
| website/examples/cookbook/animation/opacity_animation/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/animation/opacity_animation/lib/main.dart",
"repo_id": "website",
"token_count": 846
} | 1,258 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const appTitle = 'Drawer Demo';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: _widgetOptions[_selectedIndex],
),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Home'),
selected: _selectedIndex == 0,
onTap: () {
// Update the state of the app
_onItemTapped(0);
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: const Text('Business'),
selected: _selectedIndex == 1,
onTap: () {
// Update the state of the app
_onItemTapped(1);
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: const Text('School'),
selected: _selectedIndex == 2,
onTap: () {
// Update the state of the app
_onItemTapped(2);
// Then close the drawer
Navigator.pop(context);
},
),
],
),
),
);
}
}
| website/examples/cookbook/design/drawer/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/design/drawer/lib/main.dart",
"repo_id": "website",
"token_count": 1344
} | 1,259 |
name: snackbars
description: Sample code for snackbars 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/snackbars/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/design/snackbars/pubspec.yaml",
"repo_id": "website",
"token_count": 91
} | 1,260 |
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
@immutable
class BubbleBackground extends StatelessWidget {
const BubbleBackground({
super.key,
required this.colors,
this.child,
});
final List<Color> colors;
final Widget? child;
@override
Widget build(BuildContext context) {
return CustomPaint(
// #docregion ScrollableContext
painter: BubblePainter(
colors: colors,
bubbleContext: context,
scrollable: ScrollableState(),
),
// #enddocregion ScrollableContext
child: child,
);
}
}
// #docregion BPWithoutPaint
class BubblePainter extends CustomPainter {
BubblePainter({
required ScrollableState scrollable,
required BuildContext bubbleContext,
required List<Color> colors,
}) : _scrollable = scrollable,
_bubbleContext = bubbleContext,
_colors = colors;
final ScrollableState _scrollable;
final BuildContext _bubbleContext;
final List<Color> _colors;
@override
bool shouldRepaint(BubblePainter oldDelegate) {
return oldDelegate._scrollable != _scrollable ||
oldDelegate._bubbleContext != _bubbleContext ||
oldDelegate._colors != _colors;
}
// #enddocregion BPWithoutPaint
@override
void paint(Canvas canvas, Size size) {
final scrollableBox = _scrollable.context.findRenderObject() as RenderBox;
final scrollableRect = Offset.zero & scrollableBox.size;
final bubbleBox = _bubbleContext.findRenderObject() as RenderBox;
final origin =
bubbleBox.localToGlobal(Offset.zero, ancestor: scrollableBox);
final paint = Paint()
..shader = ui.Gradient.linear(
scrollableRect.topCenter,
scrollableRect.bottomCenter,
_colors,
[0.0, 1.0],
TileMode.clamp,
Matrix4.translationValues(-origin.dx, -origin.dy, 0.0).storage,
);
canvas.drawRect(Offset.zero & size, paint);
}
}
| website/examples/cookbook/effects/gradient_bubbles/lib/bubble_painter.dart/0 | {
"file_path": "website/examples/cookbook/effects/gradient_bubbles/lib/bubble_painter.dart",
"repo_id": "website",
"token_count": 718
} | 1,261 |
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleUiLoadingAnimation(),
debugShowCheckedModeBanner: false,
),
);
}
const _shimmerGradient = LinearGradient(
colors: [
Color(0xFFEBEBF4),
Color(0xFFF4F4F4),
Color(0xFFEBEBF4),
],
stops: [
0.1,
0.3,
0.4,
],
begin: Alignment(-1.0, -0.3),
end: Alignment(1.0, 0.3),
tileMode: TileMode.clamp,
);
class ExampleUiLoadingAnimation extends StatefulWidget {
const ExampleUiLoadingAnimation({
super.key,
});
@override
State<ExampleUiLoadingAnimation> createState() =>
_ExampleUiLoadingAnimationState();
}
class _ExampleUiLoadingAnimationState extends State<ExampleUiLoadingAnimation> {
bool _isLoading = true;
void _toggleLoading() {
setState(() {
_isLoading = !_isLoading;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Shimmer(
linearGradient: _shimmerGradient,
child: ListView(
physics: _isLoading ? const NeverScrollableScrollPhysics() : null,
children: [
const SizedBox(height: 16),
_buildTopRowList(),
const SizedBox(height: 16),
_buildListItem(),
_buildListItem(),
_buildListItem(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggleLoading,
child: Icon(
_isLoading ? Icons.hourglass_full : Icons.hourglass_bottom,
),
),
);
}
Widget _buildTopRowList() {
return SizedBox(
height: 72,
child: ListView(
physics: _isLoading ? const NeverScrollableScrollPhysics() : null,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: [
const SizedBox(width: 16),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
],
),
);
}
Widget _buildTopRowItem() {
return ShimmerLoading(
isLoading: _isLoading,
child: const CircleListItem(),
);
}
Widget _buildListItem() {
return ShimmerLoading(
isLoading: _isLoading,
child: CardListItem(
isLoading: _isLoading,
),
);
}
}
class Shimmer extends StatefulWidget {
static ShimmerState? of(BuildContext context) {
return context.findAncestorStateOfType<ShimmerState>();
}
const Shimmer({
super.key,
required this.linearGradient,
this.child,
});
final LinearGradient linearGradient;
final Widget? child;
@override
ShimmerState createState() => ShimmerState();
}
// #docregion ShimmerStateAnimation
class ShimmerState extends State<Shimmer> with SingleTickerProviderStateMixin {
late AnimationController _shimmerController;
@override
void initState() {
super.initState();
_shimmerController = AnimationController.unbounded(vsync: this)
..repeat(min: -0.5, max: 1.5, period: const Duration(milliseconds: 1000));
}
@override
void dispose() {
_shimmerController.dispose();
super.dispose();
}
// code-excerpt-closing-bracket
// #enddocregion ShimmerStateAnimation
// #docregion LinearGradient
LinearGradient get gradient => LinearGradient(
colors: widget.linearGradient.colors,
stops: widget.linearGradient.stops,
begin: widget.linearGradient.begin,
end: widget.linearGradient.end,
transform:
_SlidingGradientTransform(slidePercent: _shimmerController.value),
);
// #enddocregion LinearGradient
bool get isSized =>
(context.findRenderObject() as RenderBox?)?.hasSize ?? false;
Size get size => (context.findRenderObject() as RenderBox).size;
Offset getDescendantOffset({
required RenderBox descendant,
Offset offset = Offset.zero,
}) {
final shimmerBox = context.findRenderObject() as RenderBox;
return descendant.localToGlobal(offset, ancestor: shimmerBox);
}
// #docregion shimmerChanges
Listenable get shimmerChanges => _shimmerController;
// #enddocregion shimmerChanges
@override
Widget build(BuildContext context) {
return widget.child ?? const SizedBox();
}
}
// #docregion SlidingGradientTransform
class _SlidingGradientTransform extends GradientTransform {
const _SlidingGradientTransform({
required this.slidePercent,
});
final double slidePercent;
@override
Matrix4? transform(Rect bounds, {TextDirection? textDirection}) {
return Matrix4.translationValues(bounds.width * slidePercent, 0.0, 0.0);
}
}
// #enddocregion SlidingGradientTransform
class ShimmerLoading extends StatefulWidget {
const ShimmerLoading({
super.key,
required this.isLoading,
required this.child,
});
final bool isLoading;
final Widget child;
@override
State<ShimmerLoading> createState() => _ShimmerLoadingState();
}
// #docregion ShimmerLoadingState
class _ShimmerLoadingState extends State<ShimmerLoading> {
Listenable? _shimmerChanges;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_shimmerChanges != null) {
_shimmerChanges!.removeListener(_onShimmerChange);
}
_shimmerChanges = Shimmer.of(context)?.shimmerChanges;
if (_shimmerChanges != null) {
_shimmerChanges!.addListener(_onShimmerChange);
}
}
@override
void dispose() {
_shimmerChanges?.removeListener(_onShimmerChange);
super.dispose();
}
void _onShimmerChange() {
if (widget.isLoading) {
setState(() {
// update the shimmer painting.
});
}
}
// code-excerpt-closing-bracket
// #enddocregion ShimmerLoadingState
@override
Widget build(BuildContext context) {
if (!widget.isLoading) {
return widget.child;
}
// Collect ancestor shimmer info.
final shimmer = Shimmer.of(context)!;
if (!shimmer.isSized) {
// The ancestor Shimmer widget has not laid
// itself out yet. Return an empty box.
return const SizedBox();
}
final shimmerSize = shimmer.size;
final gradient = shimmer.gradient;
final offsetWithinShimmer = shimmer.getDescendantOffset(
descendant: context.findRenderObject() as RenderBox,
);
return ShaderMask(
blendMode: BlendMode.srcATop,
shaderCallback: (bounds) {
return gradient.createShader(
Rect.fromLTWH(
-offsetWithinShimmer.dx,
-offsetWithinShimmer.dy,
shimmerSize.width,
shimmerSize.height,
),
);
},
child: widget.child,
);
}
}
//----------- List Items ---------
class CircleListItem extends StatelessWidget {
const CircleListItem({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Container(
width: 54,
height: 54,
decoration: const BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
),
child: ClipOval(
child: Image.network(
'https://docs.flutter.dev/cookbook'
'/img-files/effects/split-check/Avatar1.jpg',
fit: BoxFit.cover,
),
),
),
);
}
}
class CardListItem extends StatelessWidget {
const CardListItem({
super.key,
required this.isLoading,
});
final bool isLoading;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildImage(),
const SizedBox(height: 16),
_buildText(),
],
),
);
}
Widget _buildImage() {
return AspectRatio(
aspectRatio: 16 / 9,
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network(
'https://docs.flutter.dev/cookbook'
'/img-files/effects/split-check/Food1.jpg',
fit: BoxFit.cover,
),
),
),
);
}
Widget _buildText() {
if (isLoading) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
height: 24,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
),
const SizedBox(height: 16),
Container(
width: 250,
height: 24,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
),
],
);
} else {
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 8),
child: Text(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do '
'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
),
);
}
}
}
| website/examples/cookbook/effects/shimmer_loading/lib/original_example.dart/0 | {
"file_path": "website/examples/cookbook/effects/shimmer_loading/lib/original_example.dart",
"repo_id": "website",
"token_count": 3899
} | 1,262 |
// ignore_for_file: unused_element, unused_field
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import './excerpt1.dart';
// #docregion Bubbles
class _TypingIndicatorState extends State<TypingIndicator>
with TickerProviderStateMixin {
late AnimationController _appearanceController;
late Animation<double> _indicatorSpaceAnimation;
late Animation<double> _smallBubbleAnimation;
late Animation<double> _mediumBubbleAnimation;
late Animation<double> _largeBubbleAnimation;
late AnimationController _repeatingController;
final List<Interval> _dotIntervals = const [
Interval(0.25, 0.8),
Interval(0.35, 0.9),
Interval(0.45, 1.0),
];
@override
void initState() {
super.initState();
_appearanceController = AnimationController(
vsync: this,
)..addListener(() {
setState(() {});
});
_indicatorSpaceAnimation = CurvedAnimation(
parent: _appearanceController,
curve: const Interval(0.0, 0.4, curve: Curves.easeOut),
reverseCurve: const Interval(0.0, 1.0, curve: Curves.easeOut),
).drive(Tween<double>(
begin: 0.0,
end: 60.0,
));
_smallBubbleAnimation = CurvedAnimation(
parent: _appearanceController,
curve: const Interval(0.0, 0.5, curve: Curves.elasticOut),
reverseCurve: const Interval(0.0, 0.3, curve: Curves.easeOut),
);
_mediumBubbleAnimation = CurvedAnimation(
parent: _appearanceController,
curve: const Interval(0.2, 0.7, curve: Curves.elasticOut),
reverseCurve: const Interval(0.2, 0.6, curve: Curves.easeOut),
);
_largeBubbleAnimation = CurvedAnimation(
parent: _appearanceController,
curve: const Interval(0.3, 1.0, curve: Curves.elasticOut),
reverseCurve: const Interval(0.5, 1.0, curve: Curves.easeOut),
);
if (widget.showIndicator) {
_showIndicator();
}
}
@override
void didUpdateWidget(TypingIndicator oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.showIndicator != oldWidget.showIndicator) {
if (widget.showIndicator) {
_showIndicator();
} else {
_hideIndicator();
}
}
}
@override
void dispose() {
_appearanceController.dispose();
super.dispose();
}
void _showIndicator() {
_appearanceController
..duration = const Duration(milliseconds: 750)
..forward();
}
void _hideIndicator() {
_appearanceController
..duration = const Duration(milliseconds: 150)
..reverse();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _indicatorSpaceAnimation,
builder: (context, child) {
return SizedBox(
height: _indicatorSpaceAnimation.value,
child: child,
);
},
child: Stack(
children: [
AnimatedBubble(
animation: _smallBubbleAnimation,
left: 8,
bottom: 8,
bubble: CircleBubble(
size: 8,
bubbleColor: widget.bubbleColor,
),
),
AnimatedBubble(
animation: _mediumBubbleAnimation,
left: 10,
bottom: 10,
bubble: CircleBubble(
size: 16,
bubbleColor: widget.bubbleColor,
),
),
AnimatedBubble(
animation: _largeBubbleAnimation,
left: 12,
bottom: 12,
bubble: StatusBubble(
dotIntervals: _dotIntervals,
flashingCircleDarkColor: widget.flashingCircleDarkColor,
flashingCircleBrightColor: widget.flashingCircleBrightColor,
bubbleColor: widget.bubbleColor,
),
),
],
),
);
}
}
class CircleBubble extends StatelessWidget {
const CircleBubble({
super.key,
required this.size,
required this.bubbleColor,
});
final double size;
final Color bubbleColor;
@override
Widget build(BuildContext context) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: bubbleColor,
),
);
}
}
class AnimatedBubble extends StatelessWidget {
const AnimatedBubble({
super.key,
required this.animation,
required this.left,
required this.bottom,
required this.bubble,
});
final Animation<double> animation;
final double left;
final double bottom;
final Widget bubble;
@override
Widget build(BuildContext context) {
return Positioned(
left: left,
bottom: bottom,
child: AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Transform.scale(
scale: animation.value,
alignment: Alignment.bottomLeft,
child: child,
);
},
child: bubble,
),
);
}
}
class StatusBubble extends StatelessWidget {
const StatusBubble({
super.key,
required this.dotIntervals,
required this.flashingCircleBrightColor,
required this.flashingCircleDarkColor,
required this.bubbleColor,
});
final List<Interval> dotIntervals;
final Color flashingCircleDarkColor;
final Color flashingCircleBrightColor;
final Color bubbleColor;
@override
Widget build(BuildContext context) {
return Container(
width: 85,
height: 44,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(27),
color: bubbleColor,
),
);
}
}
// #enddocregion Bubbles
| website/examples/cookbook/effects/typing_indicator/lib/excerpt3.dart/0 | {
"file_path": "website/examples/cookbook/effects/typing_indicator/lib/excerpt3.dart",
"repo_id": "website",
"token_count": 2391
} | 1,263 |
name: handling_taps
description: Example on handling_taps 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/gestures/handling_taps/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/gestures/handling_taps/pubspec.yaml",
"repo_id": "website",
"token_count": 94
} | 1,264 |
import 'package:flutter/material.dart';
void main() {
runApp(
// #docregion MaterialApp
MaterialApp(
title: 'Named Routes Demo',
// Start the app with the "/" named route. In this case, the app starts
// on the FirstScreen widget.
initialRoute: '/',
routes: {
// When navigating to the "/" route, build the FirstScreen widget.
'/': (context) => const FirstScreen(),
// When navigating to the "/second" route, build the SecondScreen widget.
'/second': (context) => const SecondScreen(),
},
),
// #enddocregion MaterialApp
);
}
class FirstScreen extends StatelessWidget {
const FirstScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Screen'),
),
body: Center(
child: ElevatedButton(
// #docregion PushNamed
// Within the `FirstScreen` widget
onPressed: () {
// Navigate to the second screen using a named route.
Navigator.pushNamed(context, '/second');
},
// #enddocregion PushNamed
child: const Text('Launch screen'),
),
),
);
}
}
class SecondScreen extends StatelessWidget {
const SecondScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Screen'),
),
body: Center(
child: ElevatedButton(
// #docregion Pop
// Within the SecondScreen widget
onPressed: () {
// Navigate back to the first screen by popping the current route
// off the stack.
Navigator.pop(context);
},
// #enddocregion Pop
child: const Text('Go back!'),
),
),
);
}
}
| website/examples/cookbook/navigation/named_routes/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/navigation/named_routes/lib/main.dart",
"repo_id": "website",
"token_count": 785
} | 1,265 |
name: passing_data
description: Passing 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/passing_data/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/navigation/passing_data/pubspec.yaml",
"repo_id": "website",
"token_count": 85
} | 1,266 |
name: web_sockets
description: Web Sockets
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
web_socket_channel: ^2.4.3
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/networking/web_sockets/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/networking/web_sockets/pubspec.yaml",
"repo_id": "website",
"token_count": 101
} | 1,267 |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
// #docregion main
void main() async {
WidgetsFlutterBinding.ensureInitialized();
unawaited(MobileAds.instance.initialize());
runApp(MyApp());
}
// #enddocregion main
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}
| website/examples/cookbook/plugins/google_mobile_ads/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/plugins/google_mobile_ads/lib/main.dart",
"repo_id": "website",
"token_count": 150
} | 1,268 |
import 'package:flutter_test/flutter_test.dart';
// #docregion mockClient
import 'package:http/http.dart' as http;
import 'package:mocking/main.dart';
import 'package:mockito/annotations.dart';
// #enddocregion mockClient
import 'package:mockito/mockito.dart';
import 'fetch_album_test.mocks.dart';
// #docregion mockClient
// Generate a MockClient using the Mockito package.
// Create new instances of this class in each test.
@GenerateMocks([http.Client])
void main() {
// #enddocregion mockClient
group('fetchAlbum', () {
test('returns an Album if the http call completes successfully', () async {
final client = MockClient();
// Use Mockito to return a successful response when it calls the
// provided http.Client.
when(client
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
.thenAnswer((_) async =>
http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
expect(await fetchAlbum(client), isA<Album>());
});
test('throws an exception if the http call completes with an error', () {
final client = MockClient();
// Use Mockito to return an unsuccessful response when it calls the
// provided http.Client.
when(client
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
.thenAnswer((_) async => http.Response('Not Found', 404));
expect(fetchAlbum(client), throwsException);
});
});
// #docregion mockClient
}
// #enddocregion mockClient
| website/examples/cookbook/testing/unit/mocking/test/fetch_album_test.dart/0 | {
"file_path": "website/examples/cookbook/testing/unit/mocking/test/fetch_album_test.dart",
"repo_id": "website",
"token_count": 559
} | 1,269 |
import 'package:json_annotation/json_annotation.dart';
part 'address.g.dart';
@JsonSerializable()
class Address {
String street;
String city;
Address(this.street, this.city);
factory Address.fromJson(Map<String, dynamic> json) =>
_$AddressFromJson(json);
Map<String, dynamic> toJson() => _$AddressToJson(this);
}
| website/examples/development/data-and-backend/json/lib/nested/address.dart/0 | {
"file_path": "website/examples/development/data-and-backend/json/lib/nested/address.dart",
"repo_id": "website",
"token_count": 119
} | 1,270 |
// ignore_for_file: unused_local_variable
// #docregion import
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
// #enddocregion import
import 'package:flutter/widgets.dart';
class IOSCompositionWidget extends StatelessWidget {
const IOSCompositionWidget({super.key});
@override
// #docregion iOSCompositionWidget
Widget build(BuildContext context) {
// This is used in the platform side to register the view.
const String viewType = '<platform-view-type>';
// Pass parameters to the platform side.
final Map<String, dynamic> creationParams = <String, dynamic>{};
return UiKitView(
viewType: viewType,
layoutDirection: TextDirection.ltr,
creationParams: creationParams,
creationParamsCodec: const StandardMessageCodec(),
);
}
// #enddocregion iOSCompositionWidget
}
class TogetherWidget extends StatelessWidget {
const TogetherWidget({super.key});
@override
// #docregion TogetherWidget
Widget build(BuildContext context) {
// This is used in the platform side to register the view.
const String viewType = '<platform-view-type>';
// Pass parameters to the platform side.
final Map<String, dynamic> creationParams = <String, dynamic>{};
switch (defaultTargetPlatform) {
case TargetPlatform.android:
// return widget on Android.
case TargetPlatform.iOS:
// return widget on iOS.
default:
throw UnsupportedError('Unsupported platform view');
}
}
// #enddocregion TogetherWidget
}
| website/examples/development/platform_integration/lib/platform_views/native_view_example_3.dart/0 | {
"file_path": "website/examples/development/platform_integration/lib/platform_views/native_view_example_3.dart",
"repo_id": "website",
"token_count": 497
} | 1,271 |
import 'package:flutter/material.dart';
// ParentWidget manages the state for TapboxB.
//------------------------ ParentWidget --------------------------------
class ParentWidget extends StatefulWidget {
const ParentWidget({super.key});
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return SizedBox(
child: TapboxB(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
//------------------------- TapboxB ----------------------------------
class TapboxB extends StatelessWidget {
const TapboxB({
super.key,
this.active = false,
required this.onChanged,
});
final bool active;
final ValueChanged<bool> onChanged;
void _handleTap() {
onChanged(!active);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
child: Center(
child: Text(
active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32, color: Colors.white),
),
),
),
);
}
}
| website/examples/development/ui/interactive/lib/parent_managed.dart/0 | {
"file_path": "website/examples/development/ui/interactive/lib/parent_managed.dart",
"repo_id": "website",
"token_count": 560
} | 1,272 |
{
"@@locale": "en",
"hello":"Hello {userName}",
"@hello":{
"description":"A message with a single parameter",
"placeholders":{
"userName":{
"type":"String",
"example":"Bob"
}
}
}
}
| website/examples/get-started/flutter-for/android_devs/lib/arb_examples.arb/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/arb_examples.arb",
"repo_id": "website",
"token_count": 130
} | 1,273 |
import 'dart:developer' as developer;
import 'package:http/http.dart' as http;
Future<void> loadData() async {
var dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts');
http.Response response = await http.get(dataURL);
developer.log(response.body);
}
| website/examples/get-started/flutter-for/android_devs/lib/network.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/network.dart",
"repo_id": "website",
"token_count": 89
} | 1,274 |
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();
}
// #docregion 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);
});
}
// #enddocregion loadData
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);
},
),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/async.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/async.dart",
"repo_id": "website",
"token_count": 567
} | 1,275 |
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Widget> _getListData() {
List<Widget> widgets = [];
for (int i = 0; i < 100; i++) {
widgets.add(
GestureDetector(
onTap: () {
developer.log('row tapped');
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $i'),
),
),
);
}
return widgets;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample App'),
),
body: ListView(children: _getListData()),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/list_item_tapped.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/list_item_tapped.dart",
"repo_id": "website",
"token_count": 494
} | 1,276 |
import 'package:flutter/cupertino.dart';
void main() {
runApp(
const App(),
);
}
class App extends StatelessWidget {
const App({
super.key,
});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(
brightness: Brightness.dark,
),
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle:
// #docregion CustomFont
Text(
'Cupertino',
style: TextStyle(
fontSize: 40,
fontFamily: 'BungeeSpice',
),
)
// #enddocregion CustomFont
),
child: Center(
// #docregion StylingButtonExample
child: CupertinoButton(
color: CupertinoColors.systemYellow,
onPressed: () {},
padding: const EdgeInsets.all(16),
child: const Text(
'Do something',
style: TextStyle(
color: CupertinoColors.systemBlue,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
),
// #enddocregion StylingButtonExample
),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/stylingbutton.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/stylingbutton.dart",
"repo_id": "website",
"token_count": 663
} | 1,277 |
import 'package:flutter/material.dart';
class ColumnExample extends StatelessWidget {
const ColumnExample({super.key});
// #docregion Column
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Container(
color: Colors.red,
width: 100,
height: 100,
),
Container(
color: Colors.blue,
width: 100,
height: 100,
),
Container(
color: Colors.green,
width: 100,
height: 100,
),
],
),
);
// #enddocregion Column
}
}
class StackExample extends StatelessWidget {
const StackExample({super.key});
// #docregion Stack
@override
Widget build(BuildContext context) {
return Stack(
alignment: const Alignment(0.6, 0.6),
children: <Widget>[
const CircleAvatar(
backgroundImage: NetworkImage(
'https://avatars3.githubusercontent.com/u/14101776?v=4',
),
),
Container(
color: Colors.black45,
child: const Text('Flutter'),
),
],
);
// #enddocregion Stack
}
}
| website/examples/get-started/flutter-for/react_native_devs/lib/layouts.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/layouts.dart",
"repo_id": "website",
"token_count": 586
} | 1,278 |
import 'package:flutter/material.dart';
// #docregion MyApp
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'),
);
}
}
// #enddocregion MyApp
// #docregion MyHomePage
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
// #enddocregion MyHomePage
// #docregion MyHomePageState
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),
),
);
}
}
// #enddocregion MyHomePageState
| website/examples/get-started/flutter-for/xamarin_devs/lib/page.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/page.dart",
"repo_id": "website",
"token_count": 724
} | 1,279 |
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
| website/examples/internationalization/gen_l10n_example/l10n.yaml/0 | {
"file_path": "website/examples/internationalization/gen_l10n_example/l10n.yaml",
"repo_id": "website",
"token_count": 37
} | 1,280 |
name: intl_example
description: Example of a Flutter app using the intl library services.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: any # Use the pinned version from flutter_localizations
dev_dependencies:
example_utils:
path: ../../example_utils
flutter_test:
sdk: flutter
intl_translation: ^0.19.0
flutter:
uses-material-design: true
| website/examples/internationalization/intl_example/pubspec.yaml/0 | {
"file_path": "website/examples/internationalization/intl_example/pubspec.yaml",
"repo_id": "website",
"token_count": 159
} | 1,281 |
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugPaintSizeEnabled;
void main() {
debugPaintSizeEnabled = false; // Set to true for visual layout
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const showCard = true; // Set to false to show Stack
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter layout demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter layout demo'),
),
body: Center(child: showCard ? _buildCard() : _buildStack()),
),
);
}
// #docregion Card
Widget _buildCard() {
return SizedBox(
height: 210,
child: Card(
child: Column(
children: [
ListTile(
title: const Text(
'1625 Main Street',
style: TextStyle(fontWeight: FontWeight.w500),
),
subtitle: const Text('My City, CA 99984'),
leading: Icon(
Icons.restaurant_menu,
color: Colors.blue[500],
),
),
const Divider(),
ListTile(
title: const Text(
'(408) 555-1212',
style: TextStyle(fontWeight: FontWeight.w500),
),
leading: Icon(
Icons.contact_phone,
color: Colors.blue[500],
),
),
ListTile(
title: const Text('[email protected]'),
leading: Icon(
Icons.contact_mail,
color: Colors.blue[500],
),
),
],
),
),
);
}
// #enddocregion Card
// #docregion Stack
Widget _buildStack() {
return Stack(
alignment: const Alignment(0.6, 0.6),
children: [
const CircleAvatar(
backgroundImage: AssetImage('images/pic.jpg'),
radius: 100,
),
Container(
decoration: const BoxDecoration(
color: Colors.black45,
),
child: const Text(
'Mia B',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
);
}
// #enddocregion Stack
}
| website/examples/layout/card_and_stack/lib/main.dart/0 | {
"file_path": "website/examples/layout/card_and_stack/lib/main.dart",
"repo_id": "website",
"token_count": 1254
} | 1,282 |
// 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/material.dart';
enum CardType {
standard,
tappable,
selectable,
}
class TravelDestination {
const TravelDestination({
required this.assetName,
required this.title,
required this.description,
required this.city,
required this.location,
this.cardType = CardType.standard,
});
final String assetName;
final String title;
final String description;
final String city;
final String location;
final CardType cardType;
}
const List<TravelDestination> _destinations = [
TravelDestination(
assetName: 'places/india_thanjavur_market.png',
title: 'Top 10 Cities to Visit in Tamil Nadu',
description: 'Number 10',
city: 'Thanjavur',
location: 'Thanjavur, Tamil Nadu',
),
TravelDestination(
assetName: 'places/india_chettinad_silk_maker.png',
title: 'Artisans of Southern India',
description: 'Silk Spinners',
city: 'Chettinad',
location: 'Sivaganga, Tamil Nadu',
cardType: CardType.tappable,
),
TravelDestination(
assetName: 'places/india_tanjore_thanjavur_temple.png',
title: 'Brihadisvara Temple',
description: 'Temples',
city: 'Thanjavur',
location: 'Thanjavur, Tamil Nadu',
cardType: CardType.selectable,
),
];
class TravelDestinationItem extends StatelessWidget {
const TravelDestinationItem({
super.key,
required this.destination,
this.shape,
});
// Height that allows for all the Card's contents
// to fit comfortably within the card.
static const double height = 360;
final TravelDestination destination;
final ShapeBorder? shape;
@override
Widget build(BuildContext context) {
return SafeArea(
top: false,
bottom: false,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: [
const SectionTitle(title: 'Normal'),
SizedBox(
height: height,
child: Card(
// Ensures that the Card's children are clipped correctly.
clipBehavior: Clip.antiAlias,
shape: shape,
child: Semantics(
label: destination.title,
child: TravelDestinationContent(destination: destination),
),
),
),
],
),
),
);
}
}
class TappableTravelDestinationItem extends StatelessWidget {
const TappableTravelDestinationItem({
super.key,
required this.destination,
this.shape,
});
// Height that allows for all the Card's contents
// to fit comfortably within the card.
static const double height = 298;
final TravelDestination destination;
final ShapeBorder? shape;
@override
Widget build(BuildContext context) {
return SafeArea(
top: false,
bottom: false,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: [
const SectionTitle(title: 'Tappable'),
SizedBox(
height: height,
child: Card(
// Ensures that the Card's children (including the ink splash)
// are clipped correctly.
clipBehavior: Clip.antiAlias,
shape: shape,
child: InkWell(
onTap: () {},
splashColor:
Theme.of(context).colorScheme.onSurface.withOpacity(0.12),
highlightColor: Colors.transparent,
child: Semantics(
label: destination.title,
child: TravelDestinationContent(destination: destination),
),
),
),
),
],
),
),
);
}
}
class SelectableTravelDestinationItem extends StatelessWidget {
const SelectableTravelDestinationItem({
super.key,
required this.destination,
required this.isSelected,
required this.onSelected,
this.shape,
});
final TravelDestination destination;
final ShapeBorder? shape;
final bool isSelected;
final VoidCallback onSelected;
// Height that allows for all the Card's contents
// to fit comfortably within the card.
static const double height = 298;
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final String selectedStatus = isSelected ? 'Selected' : 'Not selected';
return SafeArea(
top: false,
bottom: false,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: [
const SectionTitle(title: 'Selectable (long press)'),
SizedBox(
height: height,
child: Card(
// Ensures that the Card's children (including the ink splash)
// are clipped correctly.
clipBehavior: Clip.antiAlias,
shape: shape,
child: InkWell(
onLongPress: () {
onSelected();
},
splashColor: colorScheme.onSurface.withOpacity(0.12),
highlightColor: Colors.transparent,
child: Stack(
children: [
Container(
color: isSelected
? colorScheme.primary.withOpacity(0.08)
: Colors.transparent,
),
Semantics(
label: '${destination.title}, $selectedStatus',
onLongPressHint: isSelected ? 'Deselect' : 'Select',
child:
TravelDestinationContent(destination: destination),
),
Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.check_circle,
color: isSelected
? colorScheme.primary
: Colors.transparent,
),
),
),
],
),
),
),
),
],
),
),
);
}
}
class SectionTitle extends StatelessWidget {
const SectionTitle({
super.key,
required this.title,
});
final String title;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(4, 4, 4, 12),
child: Align(
alignment: Alignment.centerLeft,
child: Text(title, style: Theme.of(context).textTheme.titleMedium),
),
);
}
}
class TravelDestinationContent extends StatelessWidget {
const TravelDestinationContent({super.key, required this.destination});
final TravelDestination destination;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final titleStyle = theme.textTheme.headlineSmall!.copyWith(
color: Colors.white,
);
final descriptionStyle = theme.textTheme.titleMedium!;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 184,
child: Stack(
children: [
Positioned.fill(
// In order to have the ink splash appear above the image, you
// must use Ink.image. This allows the image to be painted as
// part of the Material and display ink effects above it.
// Using a standard Image will obscure the ink splash.
child: Ink.image(
image: AssetImage(
destination.assetName,
),
fit: BoxFit.cover,
child: Container(),
),
),
Positioned(
bottom: 16,
left: 16,
right: 16,
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Semantics(
container: true,
header: true,
child: Text(
destination.title,
style: titleStyle,
),
),
),
),
],
),
),
// Description and share/explore buttons.
Semantics(
container: true,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
child: DefaultTextStyle(
softWrap: false,
overflow: TextOverflow.ellipsis,
style: descriptionStyle,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// The three line description on each card demo.
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
destination.description,
style: descriptionStyle.copyWith(color: Colors.black54),
),
),
Text(destination.city),
Text(destination.location),
],
),
),
),
),
if (destination.cardType == CardType.standard)
// share, explore buttons
Padding(
padding: const EdgeInsets.all(8),
child: OverflowBar(
alignment: MainAxisAlignment.start,
spacing: 8,
children: [
TextButton(
onPressed: () {},
child: Text(
'Share',
semanticsLabel: 'Share ${destination.title}',
),
),
TextButton(
onPressed: () {},
child: Text(
'Explore',
semanticsLabel: 'Explore ${destination.title}',
),
),
],
),
),
],
);
}
}
class CardsDemo extends StatefulWidget {
const CardsDemo({super.key});
@override
State<CardsDemo> createState() => _CardsDemoState();
}
class _CardsDemoState extends State<CardsDemo> with RestorationMixin {
final RestorableBool _isSelected = RestorableBool(false);
@override
String get restorationId => 'cards_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_isSelected, 'is_selected');
}
@override
void dispose() {
_isSelected.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.green,
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text('Cards'),
),
body: Scrollbar(
child: ListView(
restorationId: 'cards_demo_list_view',
padding: const EdgeInsets.only(top: 8, left: 8, right: 8),
children: [
for (final destination in _destinations)
Container(
margin: const EdgeInsets.only(bottom: 8),
child: switch (destination.cardType) {
CardType.standard =>
TravelDestinationItem(destination: destination),
CardType.tappable =>
TappableTravelDestinationItem(destination: destination),
CardType.selectable => SelectableTravelDestinationItem(
destination: destination,
isSelected: _isSelected.value,
onSelected: () {
setState(() {
_isSelected.value = !_isSelected.value;
});
},
),
},
),
],
),
),
),
);
}
}
void main() {
runApp(const CardsDemo());
}
| website/examples/layout/gallery/lib/cards_demo.dart/0 | {
"file_path": "website/examples/layout/gallery/lib/cards_demo.dart",
"repo_id": "website",
"token_count": 6342
} | 1,283 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const String appTitle = 'Flutter layout demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
),
// #docregion addWidget
body: const SingleChildScrollView(
child: Column(
children: [
TitleSection(
name: 'Oeschinen Lake Campground',
location: 'Kandersteg, Switzerland',
),
],
),
),
// #enddocregion addWidget
),
);
}
}
// #docregion titleSection
class TitleSection extends StatelessWidget {
const TitleSection({
super.key,
required this.name,
required this.location,
});
final String name;
final String location;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
/*1*/
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
/*2*/
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
name,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Text(
location,
style: TextStyle(
color: Colors.grey[500],
),
),
],
),
),
/*3*/
Icon(
Icons.star,
color: Colors.red[500],
),
const Text('41'),
],
),
);
}
}
// #enddocregion titleSection
| website/examples/layout/lakes/step2/lib/main.dart/0 | {
"file_path": "website/examples/layout/lakes/step2/lib/main.dart",
"repo_id": "website",
"token_count": 1085
} | 1,284 |
import 'package:flutter/material.dart';
// #docregion debugPaintSizeEnabled
//add import to rendering library
import 'package:flutter/rendering.dart';
void main() {
debugPaintSizeEnabled = true;
runApp(const MyApp());
}
// #enddocregion debugPaintSizeEnabled
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Text('hello');
}
}
| website/examples/testing/code_debugging/lib/debug_flags.dart/0 | {
"file_path": "website/examples/testing/code_debugging/lib/debug_flags.dart",
"repo_id": "website",
"token_count": 134
} | 1,285 |
name: common_errors
description: Excerpts for common Flutter errors.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../example_utils
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/testing/common_errors/pubspec.yaml/0 | {
"file_path": "website/examples/testing/common_errors/pubspec.yaml",
"repo_id": "website",
"token_count": 129
} | 1,286 |
name: how_to
description: An example of setting up an integration test.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/testing/integration_tests/how_to/pubspec.yaml/0 | {
"file_path": "website/examples/testing/integration_tests/how_to/pubspec.yaml",
"repo_id": "website",
"token_count": 130
} | 1,287 |
import 'dart:async' show Future;
import 'package:flutter/material.dart';
// #docregion RootBundle
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
return await rootBundle.loadString('assets/config.json');
}
// #enddocregion RootBundle
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
// #docregion BackgroundImage
return const Image(image: AssetImage('assets/background.png'));
// #enddocregion BackgroundImage
}
}
AssetImage getHeartIconImage() {
// #docregion PackageImage
return const AssetImage('icons/heart.png', package: 'my_icons');
// #enddocregion PackageImage
}
| website/examples/ui/assets_and_images/lib/main.dart/0 | {
"file_path": "website/examples/ui/assets_and_images/lib/main.dart",
"repo_id": "website",
"token_count": 386
} | 1,288 |
import 'package:flutter/material.dart';
import '../global/device_type.dart';
class StyledTextButton extends StatelessWidget {
const StyledTextButton({
super.key,
required this.onPressed,
required this.child,
});
final VoidCallback onPressed;
final Widget child;
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
padding: MaterialStateProperty.all(const EdgeInsets.all(Insets.small)),
textStyle: MaterialStateProperty.all(TextStyles.buttonText2),
),
onPressed: onPressed,
child: child,
);
}
}
class SecondaryMenuButton extends StatelessWidget {
const SecondaryMenuButton({super.key, required this.label});
final String label;
@override
Widget build(BuildContext context) {
return StyledTextButton(
onPressed: () {},
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
child: Text(label),
),
);
}
}
class SelectedPageButton extends StatelessWidget {
const SelectedPageButton(
{super.key,
required this.onPressed,
required this.label,
required this.isSelected});
final VoidCallback? onPressed;
final String label;
final bool isSelected;
@override
Widget build(BuildContext context) {
return Container(
color: isSelected ? Colors.grey.shade200 : null,
child: TextButton(
onPressed: onPressed,
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(Insets.large),
child: Text(label, style: TextStyles.buttonText1, maxLines: 1),
),
),
);
}
}
| website/examples/ui/layout/adaptive_app_demos/lib/widgets/buttons.dart/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/lib/widgets/buttons.dart",
"repo_id": "website",
"token_count": 643
} | 1,289 |
import 'package:flutter/material.dart';
// #docregion Toggle
import 'package:flutter/rendering.dart';
void highlightRepaints() {
debugRepaintRainbowEnabled = true;
}
// #enddocregion Toggle
// #docregion EverythingRepaints
class EverythingRepaintsPage extends StatelessWidget {
const EverythingRepaintsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Repaint Example')),
body: const Center(
child: CircularProgressIndicator(),
),
);
}
}
// #enddocregion EverythingRepaints
// #docregion AreaRepaints
class AreaRepaintsPage extends StatelessWidget {
const AreaRepaintsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Repaint Example')),
body: const Center(
child: RepaintBoundary(
child: CircularProgressIndicator(),
),
),
);
}
}
// #enddocregion AreaRepaints
| website/examples/visual_debugging/lib/highlight_repaints.dart/0 | {
"file_path": "website/examples/visual_debugging/lib/highlight_repaints.dart",
"repo_id": "website",
"token_count": 352
} | 1,290 |
ChromeOSWeb:
degree: 1
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'X'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'X'
ChromeOSAndroid:
degree: 1
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'X'
visual-studio: 'X'
android-studio: 'Y'
errors: 2
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'X'
ChromeOSAndroidWeb:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'X'
visual-studio: 'X'
android-studio: 'Y'
errors: 0
add-android: 'N'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'X'
LinuxAndroid:
degree: 1
windows: 'X'
linux: 'N'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'X'
visual-studio: 'X'
android-studio: 'Y'
errors: 2
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'Y'
add-visual-studio: 'X'
LinuxAndroidWeb:
degree: 2
windows: 'X'
linux: 'N'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'X'
visual-studio: 'X'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'Y'
add-visual-studio: 'X'
LinuxDesktop:
degree: 1
windows: 'X'
linux: 'Y'
android-toolchain: 'N'
chrome: 'N'
xcode: 'X'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'N'
add-visual-studio: 'X'
LinuxDesktopAndroid:
degree: 2
windows: 'X'
linux: 'Y'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'X'
visual-studio: 'X'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'N'
add-visual-studio: 'X'
LinuxDesktopAndroidWeb:
degree: 3
windows: 'X'
linux: 'Y'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'X'
visual-studio: 'X'
android-studio: 'Y'
errors: 0
add-android: 'N'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'N'
add-visual-studio: 'X'
LinuxDesktopWeb:
degree: 2
windows: 'X'
linux: 'Y'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'X'
visual-studio: 'X'
android-studio: 'N'
errors: 2
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'N'
add-visual-studio: 'X'
LinuxWeb:
degree: 1
windows: 'X'
linux: 'N'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'X'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'Y'
add-visual-studio: 'X'
macOSAndroid:
degree: 1
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'N'
visual-studio: 'X'
android-studio: 'Y'
errors: 2
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'Y'
add-xcode: 'Y'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSAndroidWeb:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'N'
visual-studio: 'X'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'N'
add-simulator: 'Y'
add-xcode: 'Y'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktop:
degree: 1
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'N'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'Y'
add-simulator: 'Y'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopAndroid:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'Y'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopAndroidWeb:
degree: 3
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'Y'
errors: 0
add-android: 'N'
add-chrome: 'N'
add-simulator: 'Y'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopiOS:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'N'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'Y'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopiOSAndroid:
degree: 3
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopiOSAndroidWeb:
degree: 4
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'Y'
errors: 0
add-android: 'N'
add-chrome: 'N'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopiOSWeb:
degree: 3
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'N'
errors: 2
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSDesktopWeb:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'N'
errors: 2
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'Y'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSiOS:
degree: 1
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'N'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'Y'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSiOSAndroid:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSiOSWeb:
degree: 2
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'Y'
visual-studio: 'X'
android-studio: 'N'
errors: 2
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'N'
add-xcode: 'N'
add-linux-tools: 'X'
add-visual-studio: 'X'
macOSWeb:
degree: 1
windows: 'X'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'N'
visual-studio: 'X'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'Y'
add-xcode: 'Y'
add-linux-tools: 'X'
add-visual-studio: 'X'
WindowsAndroid:
degree: 1
windows: 'Y'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'X'
visual-studio: 'N'
android-studio: 'Y'
errors: 2
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'Y'
WindowsAndroidWeb:
degree: 2
windows: 'Y'
linux: 'X'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'X'
visual-studio: 'N'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'Y'
WindowsDesktop:
degree: 1
windows: 'Y'
linux: 'X'
android-toolchain: 'N'
chrome: 'N'
xcode: 'X'
visual-studio: 'Y'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'N'
WindowsDesktopAndroid:
degree: 2
windows: 'Y'
linux: 'X'
android-toolchain: 'Y'
chrome: 'N'
xcode: 'X'
visual-studio: 'Y'
android-studio: 'Y'
errors: 1
add-android: 'N'
add-chrome: 'Y'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'N'
WindowsDesktopAndroidWeb:
degree: 3
windows: 'Y'
linux: 'X'
android-toolchain: 'Y'
chrome: 'Y'
xcode: 'X'
visual-studio: 'Y'
android-studio: 'Y'
errors: 0
add-android: 'N'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'N'
WindowsDesktopWeb:
degree: 2
windows: 'Y'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'X'
visual-studio: 'Y'
android-studio: 'N'
errors: 2
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'N'
WindowsWeb:
degree: 1
windows: 'Y'
linux: 'X'
android-toolchain: 'N'
chrome: 'Y'
xcode: 'X'
visual-studio: 'N'
android-studio: 'N'
errors: 3
add-android: 'Y'
add-chrome: 'N'
add-simulator: 'X'
add-xcode: 'X'
add-linux-tools: 'X'
add-visual-studio: 'Y' | website/src/_data/doctor.yml/0 | {
"file_path": "website/src/_data/doctor.yml",
"repo_id": "website",
"token_count": 4199
} | 1,291 |
{% assign path_base = page.url %}
{% assign recipes = site.pages
| where_exp: "recipe", "recipe.url contains path_base"
| where_exp: "recipe", "recipe.url != path_base"
| sort: 'title' %}
{% for recipe in recipes -%}
- [{{ recipe.title }}]({{ recipe.url }})
{% endfor -%}
| website/src/_includes/docs/cookbook-group-index.md/0 | {
"file_path": "website/src/_includes/docs/cookbook-group-index.md",
"repo_id": "website",
"token_count": 121
} | 1,292 |
{% assign devos = include.devos %}
1. Allocate a minimum of 1 GB of storage for Google Chrome.
Consider allocating 2 GB of storage for an optimal configuration.
1. Download and install the {{devos}} version of [Google Chrome][]
to debug JavaScript code for web apps.
{% if devos == 'Linux' %}{% include docs/install/accordions/install-chrome-from-cli.md %}{% endif %}
[Google Chrome]: https://www.google.com/chrome/dr/download/
| website/src/_includes/docs/install/reqs/add-web.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/add-web.md",
"repo_id": "website",
"token_count": 133
} | 1,293 |
1. Press <kbd>Windows</kbd> + <kbd>Pause</kbd>.
If your keyboard lacks a <kbd>Pause</kbd> key,
try <kbd>Windows</kbd> + <kbd>Fn</kbd> + <kbd>B</kbd>.
The **System > About** dialog displays.
1. Click **Advanced System Settings**
<span aria-label="and then">></span> **Advanced**
<span aria-label="and then">></span> **Environment Variables...**
The **Environment Variables** dialog displays.
| website/src/_includes/docs/install/reqs/windows/open-envvars.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/windows/open-envvars.md",
"repo_id": "website",
"token_count": 153
} | 1,294 |
{% comment %}
Generates a list of testing recipes for the given type. The type
corresponds to the name of the directory under cookbook/testing/*.
Usage: {% include docs/testing_toc.md type='unit' %}
{% endcomment -%}
{% assign dir = 'cookbook/testing/' | append: include.type -%}
{% assign recipes = site.pages | where_exp:"item", "item.dir contains dir" | sort: 'title' -%}
{% for recipe in recipes -%}
{% comment -%}
Omit the index page for the given type
{% endcomment -%}
{% assign frag = recipe.url | split: '/' | last %}
{% if frag != include.type -%}
- [{{ recipe.title }}]({{ recipe.url }})
{% endif -%}
{% endfor %} | website/src/_includes/docs/testing-toc.md/0 | {
"file_path": "website/src/_includes/docs/testing-toc.md",
"repo_id": "website",
"token_count": 217
} | 1,295 |
---
layout: base
---
{% assign sidebar-col = 'col-12 col-md-3 col-xl-2' -%}
{% if page.toc -%}
{% assign main-col = 'col-12 col-md-9 offset-md-3 col-xl-8 offset-xl-2 col-xxl-8 offset-xxl-2' -%}
{% comment %}Side toc is col-xl-2{% endcomment -%}
{% else -%}
{% assign main-col = 'col-12 col-md-9 offset-md-3 col-xl-10 offset-xl-2 col-xxl-8 offset-xxl-2' -%}
{% endif -%}
<div class="container-fluid position-relative">
<div class="row flex-xl-nowrap">
<div class="fixed-col site-sidebar site-sidebar--fixed {{sidebar-col}} d-none d-md-block" data-fixed-column>
{% assign route = page.url | regex_replace:'/index$|/index\.html$|\.html$|/$' %}
{% include sidenav-level-1.html nav=site.data.sidenav page_url_path=route base_id="fixed" %}
</div>
{% if page.toc and layout.toc != false -%}
{% assign toc_content = content | toc_only -%}
{% include side-toc.html toc_content=toc_content -%}
{% endif -%}
<main class="site-content {{main-col}}">
<div class="container">
{% if page.deprecated %}
{% include snackbar.html class="snackbar--dismissible" label="This page is deprecated and its content may be out of date." action="Dismiss" %}
{% endif %}
{% include next-prev-nav.html prev=page.prev next=page.next %}
<header class="site-content__title">
{% include page-github-links.html %}
<h1>{{ page.title }}</h1>
{% if page.show_breadcrumbs -%}
{% include breadcrumbs.html %}
{% endif -%}
</header>
{% if page.toc and layout.toc != false -%}
{% include inline-toc.html toc_content=toc_content -%}
{% endif -%}
{{ content | inject_anchors }}
{% include next-prev-nav.html prev=page.prev next=page.next %}
</div>
</main>
</div>
</div>
| website/src/_layouts/default.html/0 | {
"file_path": "website/src/_layouts/default.html",
"repo_id": "website",
"token_count": 841
} | 1,296 |
# Copyright (c) 2012, the Dart 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.
require 'liquid/tag/parser' # https://github.com/envygeeks/liquid-tag-parser
require_relative 'dart_site_util'
require_relative 'prettify_core'
module Jekyll
module Tags
# Liquid Block plugin to render code that gets
# prettified by https://github.com/google/code-prettify.
#
# Arguments:
#
# - The first unnamed optional argument is the prettifier lang argument.
# Use 'nocode' or 'none' as the language to turn off prettifying.
# - class="...". CSS classes to be added to the opening <pre> tag.
# - context="html". When unspecified, the context is assumed to be markdown.
# In markdown, indentation of the block is preserved, in HTML the block
# isn't indented.
# - tag="...". See [PrettifyCore.code2html()] for a description of
# accepted tag specifiers. Defaults to 'pre'.
#
# Code highlighting is supported; see see [PrettifyCore] for details.
#
# Example usage:
#
# {% prettify dart %}
# var hello = 'world';
# {% endprettify %}
#
class Prettify < Liquid::Block
def initialize(tag_name, string_of_args, tokens)
super
@args = Liquid::Tag::Parser.new(string_of_args).args
end
def render(_context)
helper = DartSite::PrettifyCore.new
helper.code2html(super,
lang: @args[:argv1],
context: @args[:context] || 'markdown',
tag_specifier: @args[:tag],
user_classes: @args[:class])
end
end
end
end
Liquid::Template.register_tag('prettify', Jekyll::Tags::Prettify)
| website/src/_plugins/prettify.rb/0 | {
"file_path": "website/src/_plugins/prettify.rb",
"repo_id": "website",
"token_count": 729
} | 1,297 |
@use '../base/variables' as *;
@use '../vendor/bootstrap';
.site-header {
background-color: $site-color-white;
box-shadow: 0 2px 4px rgba(0, 0, 0, .1);
font-family: $site-font-family-alt;
position: sticky;
top: 0;
z-index: bootstrap.$zindex-fixed;
.navbar {
font-size: bootstrap.$font-size-lg;
min-height: $site-header-height;
@include bootstrap.media-breakpoint-up(md) {
font-size: bootstrap.$font-size-base;
}
.navbar-toggler {
color: $site-color-body;
margin-right: bootstrap.bs-spacer(4);
padding: 0;
.material-symbols {
font-size: 28px;
}
}
.navbar-brand {
margin-right: auto;
}
.nav-link {
color: $site-color-body-light;
padding: bootstrap.bs-spacer(5) 0;
position: relative;
@include bootstrap.media-breakpoint-up(md) {
padding: 0 bootstrap.bs-spacer(4);
}
&.active {
color: $site-color-body;
font-weight: 500;
@include bootstrap.media-breakpoint-up(md) {
&:after {
$nav-active-marker-thickness: 3px;
background-color: $site-color-primary;
content: '';
display: block;
height: $nav-active-marker-thickness;
left: 0;
position: absolute;
top: calc(50% + (#{$site-header-height} / 2) - #{$nav-active-marker-thickness});
width: 100%;
}
}
}
}
}
.navbar-collapse {
bottom: 0;
height: auto !important; // override bootstrap's height calculation
left: 0;
position: fixed;
right: 0;
top: 0;
transition-duration: 0s;
z-index: bootstrap.$zindex-fixed;
@include bootstrap.media-breakpoint-down(sm) {
pointer-events: none;
&:not(.show) {
display: block;
}
&.show {
pointer-events: auto;
transition-duration: 0.35s;
.site-header__sheet {
transform: translateX(0);
}
.site-header__sheet-bg {
opacity: 1;
}
}
.navbar-nav {
margin-bottom: bootstrap.bs-spacer(5);
overflow-y: auto;
overscroll-behavior: contain;
}
}
@include bootstrap.media-breakpoint-up(md) {
position: static;
}
}
&__sheet {
display: flex;
z-index: bootstrap.$zindex-modal;
@include bootstrap.media-breakpoint-down(sm) {
background: $site-color-white;
bottom: 0;
flex-direction: column;
left: 0;
position: absolute;
right: 60px;
top: 0;
transform: translateX(-100%);
transition: transform 0.35s ease-in-out;
> * {
margin: 0 $site-nav-mobile-side-padding;
}
}
@include bootstrap.media-breakpoint-up(md) {
align-items: center;
flex-direction: row;
}
}
&__sheet-bg {
cursor: pointer; // needed for iOS to recognize the div as clickable
z-index: bootstrap.$zindex-modal-backdrop;
@include bootstrap.media-breakpoint-down(sm) {
background: rgba(0, 0, 0, .4);
bottom: 0;
left: 0;
opacity: 0;
position: absolute;
right: 0;
top: 0;
transition: opacity 0.35s ease-in-out;
}
}
&__cta {
margin-left: bootstrap.bs-spacer(2);
padding: bootstrap.bs-spacer(2) bootstrap.bs-spacer(4) !important;
@include bootstrap.media-breakpoint-down(sm) { display: none; }
}
&__search {
position: relative;
&::before {
content: 'search';
font: $site-font-icon;
pointer-events: none;
position: absolute;
left: bootstrap.bs-spacer(1);
}
@include bootstrap.media-breakpoint-down(sm) {
border-bottom: 1px solid $site-color-light-grey;
flex-shrink: 0;
margin: 0;
order: -1;
padding: 0 $site-nav-mobile-side-padding;
&::before {
left: $site-nav-mobile-side-padding;
}
}
@include bootstrap.media-breakpoint-up(md) {
margin-left: bootstrap.bs-spacer(4);
}
}
&__searchfield {
border: 0;
font-size: bootstrap.$font-size-sm;
padding-left: bootstrap.bs-spacer(8);
@include bootstrap.media-breakpoint-down(md) {
font-size: bootstrap.$font-size-lg;
height: 66px;
width: 100% !important;
}
@include bootstrap.media-breakpoint-up(md) {
transition: width .35s ease-in-out;
width: 24px !important;
&:focus {
width: 220px !important;
}
}
}
&__social {
.nav-item.nav-link {
padding: 0 bootstrap.bs-spacer(2);
@include bootstrap.media-breakpoint-down(sm) {
padding: 0 bootstrap.bs-spacer(1);
font-size: smaller;
}
&.nav-icon {
color: $site-color-nav-links;
&:hover {
color: $site-color-body-light;
}
svg {
height: 24px;
width: 24px;
}
}
}
}
}
header.site-header {
.dropdown-menu {
top: 32px;
box-shadow: 0 2px 4px rgba(0, 0, 0, .1);
border-radius: 4px;
padding: 0.75rem;
border: 1px solid #eee;
}
.dropdown-item {
padding: 0.55rem 1.2rem;
font-size: 14px;
color: #444;
border-radius: 4px;
&:hover,
&.active {
color: #000;
background-color: #f6f6f6;
transition: background-color 300ms ease;
}
&.active {
font-weight: 500;
}
}
.dropdown-toggle::after {
position: relative;
top: 1px;
}
@include bootstrap.media-breakpoint-down(sm) {
.navbar-collapse {
.navbar-nav {
margin-top: 1.5rem;
margin-bottom: 1.5rem;
}
}
.site-header__sheet > * {
margin: 0;
}
}
@include bootstrap.media-breakpoint-down(md) {
.site-header__sheet .navbar-nav > .nav-item {
display: none;
}
}
@include bootstrap.media-breakpoint-down(lg) {
.site-header__sheet .navbar-nav .nav-item.docs-item {
display: none;
}
}
}
| website/src/_sass/components/_header.scss/0 | {
"file_path": "website/src/_sass/components/_header.scss",
"repo_id": "website",
"token_count": 2867
} | 1,298 |
---
title: Manage plugins and dependencies in add-to-app
short-title: Plugin setup
description: >
Learn how to use plugins and share your
plugin's library dependencies with your existing app.
---
This guide describes how to set up your project to consume
plugins and how to manage your Gradle library dependencies
between your existing Android app and your Flutter module's plugins.
## A. Simple scenario
In the simple cases:
* Your Flutter module uses a plugin that has no additional
Android Gradle dependency because it only uses Android OS
APIs, such as the camera plugin.
* Your Flutter module uses a plugin that has an Android
Gradle dependency, such as
[ExoPlayer from the video_player plugin][],
but your existing Android app didn't depend on ExoPlayer.
There are no additional steps needed. Your add-to-app
module will work the same way as a full-Flutter app.
Whether you integrate using Android Studio,
Gradle subproject or AARs,
transitive Android Gradle libraries are automatically
bundled as needed into your outer existing app.
## B. Plugins needing project edits
Some plugins require you to make some edits to the
Android side of your project.
For example, the integration instructions for the
[firebase_crashlytics][] plugin require manual
edits to your Android wrapper project's `build.gradle` file.
For full-Flutter apps, these edits are done in your
Flutter project's `/android/` directory.
In the case of a Flutter module, there are only Dart
files in your module project. Perform those Android
Gradle file edits on your outer, existing Android
app rather than in your Flutter module.
{{site.alert.note}}
Astute readers might notice that the Flutter module
directory also contains an `.android` and an
`.ios` directory. Those directories are Flutter-tool-generated
and are only meant to bootstrap Flutter into generic
Android or iOS libraries. They should not be edited or checked-in.
This allows Flutter to improve the integration point should
there be bugs or updates needed with new versions of Gradle,
Android, Android Gradle Plugin, etc.
For advanced users, if more modularity is needed and you must
not leak knowledge of your Flutter module's dependencies into
your outer host app, you can rewrap and repackage your Flutter
module's Gradle library inside another native Android Gradle
library that depends on the Flutter module's Gradle library.
You can make your Android specific changes such as editing the
AndroidManifest.xml, Gradle files or adding more Java files
in that wrapper library.
{{site.alert.end}}
## C. Merging libraries
The scenario that requires slightly more attention is if
your existing Android application already depends on the
same Android library that your Flutter module
does (transitively via a plugin).
For instance, your existing app's Gradle might already have:
<?code-excerpt title="ExistingApp/app/build.gradle"?>
```gradle
…
dependencies {
…
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
…
}
…
```
And your Flutter module also depends on
[firebase_crashlytics][] via `pubspec.yaml`:
<?code-excerpt title="flutter_module/pubspec.yaml"?>
```yaml
…
dependencies:
…
firebase_crashlytics: ^0.1.3
…
…
```
This plugin usage transitively adds a Gradle dependency again via
firebase_crashlytics v0.1.3's own [Gradle file][]:
<?code-excerpt title="firebase_crashlytics_via_pub/android/build.gradle"?>
```gradle
…
dependencies {
…
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
…
}
…
```
The two `com.crashlytics.sdk.android:crashlytics` dependencies
might not be the same version. In this example,
the host app requested v2.10.1 and the Flutter
module plugin requested v2.9.9.
By default, Gradle v5
[resolves dependency version conflicts][]
by using the newest version of the library.
This is generally ok as long as there are no API
or implementation breaking changes between the versions.
For example, you might use the new Crashlytics library
in your existing app as follows:
<?code-excerpt title="ExistingApp/app/build.gradle"?>
```gradle
…
dependencies {
…
implementation 'com.google.firebase:firebase-crashlytics:17.0.0-beta03
…
}
…
```
This approach won't work since there are major API differences
between the Crashlytics' Gradle library version
v17.0.0-beta03 and v2.9.9.
For Gradle libraries that follow semantic versioning,
you can generally avoid compilation and runtime errors
by using the same major semantic version in your
existing app and Flutter module plugin.
[ExoPlayer from the video_player plugin]: {{site.repo.packages}}/blob/main/packages/video_player/video_player_android/android/build.gradle
[firebase_crashlytics]: {{site.pub}}/packages/firebase_crashlytics
[Gradle file]: {{site.github}}/firebase/flutterfire/blob/bdb95fcacf7cf077d162d2f267eee54a8b0be3bc/packages/firebase_crashlytics/android/build.gradle#L40
[resolves dependency version conflicts]: https://docs.gradle.org/current/userguide/dependency_resolution.html#sub:resolution-strategy
| website/src/add-to-app/android/plugin-setup.md/0 | {
"file_path": "website/src/add-to-app/android/plugin-setup.md",
"repo_id": "website",
"token_count": 1437
} | 1,299 |
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 22.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="560px" height="156.66px" viewBox="0 0 560 156.66" enable-background="new 0 0 560 156.66" xml:space="preserve">
<g>
<g opacity="0.54" enable-background="new ">
<path d="M195.67,34.33h52.6v10.3h-41.9v31.1h37.8v10.2h-37.8v39.4h-10.7V34.33z"/>
<path d="M260.97,34.33h10.8v90.9h-10.8V34.33z"/>
<path d="M293.47,120.43c-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.9c2.8-1.9,5-4.5,6.6-7.6s2.3-6.4,2.3-9.9v-36.6h10.9v64.8h-10.3v-9.4h-0.5c-1.8,3.2-4.6,5.9-8.5,8.1
s-8,3.3-12.4,3.3C303.47,127.33,297.57,125.03,293.47,120.43z"/>
<path d="M377.27,126.03c-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.8v9.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.4C381.97,127.33,379.47,126.83,377.27,126.03z"/>
<path d="M423.07,126.03c-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.2v-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.4C427.77,127.33,425.37,126.83,423.07,126.03z"/>
<path d="M461.37,122.83c-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.6C471.87,127.33,466.27,125.83,461.37,122.83z M496.67,86.03
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
L496.67,86.03L496.67,86.03z"/>
<path d="M520.67,60.53h10.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.8H520.67z"/>
</g>
<g>
<g>
<g>
<defs>
<path id="SVGID_1_" d="M127.7,72.35L85.85,114.2l41.85,41.86l0,0H79.87l-17.94-17.94l0,0L38.01,114.2l41.86-41.85H127.7
L127.7,72.35L127.7,72.35z M79.87,0.6L2.13,78.33l23.92,23.92L127.7,0.6H79.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="127.7,72.35 127.7,72.35 127.7,72.35 79.87,72.35 38.01,114.21 61.93,138.12 "/>
</g>
</g>
</g>
<g>
<defs>
<path id="SVGID_3_" d="M127.7,72.35L85.85,114.2l41.85,41.86l0,0H79.87l-17.94-17.94l0,0L38.01,114.2l41.86-41.85H127.7
L127.7,72.35L127.7,72.35z M79.87,0.6L2.13,78.33l23.92,23.92L127.7,0.6H79.87z"/>
</defs>
<clipPath id="SVGID_4_">
<use xlink:href="#SVGID_3_" overflow="visible"/>
</clipPath>
<polygon clip-path="url(#SVGID_4_)" fill="#39CEFD" points="26.05,102.25 2.13,78.33 79.87,0.6 127.7,0.6 "/>
</g>
<g>
<defs>
<path id="SVGID_5_" d="M127.7,72.35L85.85,114.2l41.85,41.86l0,0H79.87l-17.94-17.94l0,0L38.01,114.2l41.86-41.85H127.7
L127.7,72.35L127.7,72.35z M79.87,0.6L2.13,78.33l23.92,23.92L127.7,0.6H79.87z"/>
</defs>
<clipPath id="SVGID_6_">
<use xlink:href="#SVGID_5_" overflow="visible"/>
</clipPath>
<polygon clip-path="url(#SVGID_6_)" fill="#03569B" points="61.93,138.12 79.87,156.06 127.7,156.06 127.7,156.06 85.85,114.21
"/>
</g>
<g>
<defs>
<path id="SVGID_7_" d="M127.7,72.35L85.85,114.2l41.85,41.86l0,0H79.87l-17.94-17.94l0,0L38.01,114.2l41.86-41.85H127.7
L127.7,72.35L127.7,72.35z M79.87,0.6L2.13,78.33l23.92,23.92L127.7,0.6H79.87z"/>
</defs>
<clipPath id="SVGID_8_">
<use xlink:href="#SVGID_7_" overflow="visible"/>
</clipPath>
<linearGradient id="SVGID_9_" gradientUnits="userSpaceOnUse" x1="6959.4136" y1="-3174.3264" x2="7030.6714" y2="-3103.0686" gradientTransform="matrix(0.25 0 0 -0.25 -1670.9502 -650.8373)">
<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="61.93,138.12 97.4,125.84 85.85,114.21 "/>
</g>
<g>
<defs>
<path id="SVGID_10_" d="M127.7,72.35L85.85,114.2l41.85,41.86l0,0H79.87l-17.94-17.94l0,0L38.01,114.2l41.86-41.85H127.7
L127.7,72.35L127.7,72.35z M79.87,0.6L2.13,78.33l23.92,23.92L127.7,0.6H79.87z"/>
</defs>
<clipPath id="SVGID_11_">
<use xlink:href="#SVGID_10_" overflow="visible"/>
</clipPath>
<g clip-path="url(#SVGID_11_)">
<rect x="45.02" y="97.29" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -62.6176 77.2396)" fill="#16B9FD" width="33.82" height="33.82"/>
</g>
</g>
</g>
<radialGradient id="SVGID_12_" cx="6706.4683" cy="-2648.1365" r="760.8189" gradientTransform="matrix(0.25 0 0 -0.25 -1670.9502 -650.8373)" 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="M127.7,72.35L85.85,114.2l41.85,41.86l0,0H79.87l-17.94-17.94l0,0L38.01,114.2l41.86-41.85H127.7
L127.7,72.35L127.7,72.35z M79.87,0.6L2.13,78.33l23.92,23.92L127.7,0.6H79.87z"/>
</g>
</g>
</svg>
| website/src/assets/images/branding/flutter/logo+text/horizontal/default.svg/0 | {
"file_path": "website/src/assets/images/branding/flutter/logo+text/horizontal/default.svg",
"repo_id": "website",
"token_count": 3888
} | 1,300 |
---
title: Codelabs
description: >-
Codelabs to help you quickly get started programming Flutter.
---
The Flutter codelabs provide a guided,
hands-on coding experience. Some codelabs
run in DartPad—no downloads required!
## Good for beginners
If you're new to Flutter, we recommend starting with
one of the following codelabs:
* [Building your first Flutter app][] (workshop)<br>
An instructor-led version of our very popular
"Write your first Flutter app" codelab
(listed below).
* [Your first Flutter app][]<br>
Create a simple app that automatically generates cool-sounding names,
such as "newstay", "lightstream", "mainbrake", or "graypine".
This app is responsive and runs on mobile, desktop, and web.
(This also replaces the previous "write your first Flutter app"
for mobile, part 1 and part 2 codelabs.)
* [Write your first Flutter app on the web][]<br>
Implement a simple web app in DartPad (no downloads
required!) that displays a sign-in screen
containing three text fields. As the user fills out the
fields, a progress bar animates along the top of the
sign-in area. This codelab is written specifically for
the web, but if you have downloaded and configured
Android and iOS tooling, the completed app
works on Android and iOS devices, as well.
[Building your first Flutter app]: {{site.yt.watch}}?v=8sAyPDLorek
[Your first Flutter app]: {{site.codelabs}}/codelabs/flutter-codelab-first
[Write your first Flutter app on the web]: /get-started/codelab-web
## Next steps
* [Records and Patterns in Dart 3][]<br>
Discover Dart 3's new records and patterns features.
Learn how you can use them in a Flutter app to help you
write more readable and maintainable Dart code.
* [Building scrolling experiences in Flutter][] (workshop)<br>
Start with an app that performs simple, straightforward scrolling
and enhance it to create fancy and custom scrolling effects
by using slivers.
* [Dart null safety in Action][] (workshop)<br>
An instructor-led workshop introducing the features
that enable Dart's null-safe type system.
* [How to manage application states using inherited widgets][inherited-widget-ws] (workshop)<br>
Learn how to manage the state of your app's data by
using the `InheritedWidget` class, one of the
[low-level state management][] classes provided
by Flutter.
[Records and Patterns in Dart 3]: {{site.codelabs}}/codelabs/dart-patterns-records
[Dart null safety in Action]: {{site.yt.watch}}?v=HdKwuHQvArY
[inherited-widget-ws]: {{site.yt.watch}}?v=LFcGPS6cGrY
[low-level state management]: /data-and-backend/state-mgmt/options#inheritedwidget--inheritedmodel
## Designing a Flutter UI
Learn about Material Design and basic Flutter concepts,
like layout and animations:
* [How to debug layout issues with the Flutter Inspector][]<br>
Not an official codelab, but step-by-step instructions on
how to debug common layout problems using the Flutter
Inspector and Layout Explorer.
* [Implicit animations][]<br>
Use DartPad (no downloads required!) to learn how to use
implicit animations to add motion and create
visual effects for the widgets in your UI.
* [Building Beautiful Transitions with Material Motion for Flutter][]<br>
Learn how to use the Material [animations][] package to
add pre-built transitions to a Material app called Reply.
* [Take your Flutter app from boring to beautiful][]<br>
Learn how to use some of the features in Material 3
to make your app more beautiful _and_ more responsive.
* [MDC-101 Flutter: Material Components (MDC) Basics][]<br>
Learn the basics of using Material Components by building
a simple app with core components. The four MDC codelabs
guide you through building an e-commerce app called Shrine.
You'll start by building a login page using several of MDC
Flutter's components.
* [MDC-102 Flutter: Material Structure and Layout][]<br>
Learn how to use Material for structure and layout in Flutter.
Continue building the e-commerce app, introduced in MDC-101,
by adding navigation, structure, and data.
* [MDC-103 Flutter: Material Theming with Color, Shape, Elevation, and Type][]<br>
Discover how Material Components for Flutter make it
easy to differentiate your product, and express your
brand through design. Continue building your e-commerce
app by adding a home screen that displays products.
* [MDC-104 Flutter: Material Advanced Components][]<br>
Improve your design and learn to use our advanced
component backdrop menu. Finish your e-commerce app
by adding a backdrop with a menu that filters
products by the selected category.
* [Adaptive Apps in Flutter][]<br>
Learn how to build a Flutter app that adapts to the
platform that it's running on, be that Android, iOS,
the web, Windows, macOS, or Linux.
* [Building next generation UIs in Flutter][]<br>
Learn how to build a Flutter app that uses the power of `flutter_animate`,
fragment shaders, and particle fields. You will craft a user interface that
evokes those science fiction movies and TV shows we all love
watching when we aren't coding.
[Building next generation UIs in Flutter]: {{site.codelabs}}/codelabs/flutter-next-gen-uis#0
[Adaptive Apps in Flutter]: {{site.codelabs}}/codelabs/flutter-adaptive-app
[animations]: {{site.pub}}/packages/animations
[Building Beautiful Transitions with Material Motion for Flutter]: {{site.codelabs}}/codelabs/material-motion-flutter
[Building scrolling experiences in Flutter]: {{site.yt.watch}}?v=YY-_yrZdjGc
[How to debug layout issues with the Flutter Inspector]: {{site.flutter-medium}}/how-to-debug-layout-issues-with-the-flutter-inspector-87460a7b9db
[Implicit animations]: /codelabs/implicit-animations
[MDC-101 Flutter: Material Components (MDC) Basics]: {{site.codelabs}}/codelabs/mdc-101-flutter
[MDC-102 Flutter: Material Structure and Layout]: {{site.codelabs}}/codelabs/mdc-102-flutter
[MDC-103 Flutter: Material Theming with Color, Shape, Elevation, and Type]: {{site.codelabs}}/codelabs/mdc-103-flutter
[MDC-104 Flutter: Material Advanced Components]: {{site.codelabs}}/codelabs/mdc-104-flutter
[Take your Flutter app from boring to beautiful]: {{site.codelabs}}/codelabs/flutter-boring-to-beautiful
## Using Flutter with
Learn how to use Flutter with other technologies.
{% comment %}
Once we get at least 3 codelabs on a specific topic,
add a subheader for that topic.
{% endcomment %}
### Monetizing Flutter
* [Adding AdMob Ads to a Flutter app][]<br>
Learn how to add an AdMob banner, an interstitial ad,
and a rewarded ad to an app called Awesome Drawing Quiz,
a game that lets players guess the name of the drawing.
* [Adding an AdMob banner and native inline ads to a Flutter app][]<br>
Learn how to implement inline banner and native ads
to a travel booking app that lists possible
flight destinations.
* [Adding in-app purchases to your Flutter app][]<br>
Extend a simple gaming app that uses the Dash mascot as
currency to offer three types of in-app purchases:
consumable, non-consumable, and subscription.
[Adding AdMob Ads to a Flutter app]: {{site.codelabs}}/codelabs/admob-ads-in-flutter
[Adding an AdMob banner and native inline ads to a Flutter app]: {{site.codelabs}}/codelabs/admob-inline-ads-in-flutter
[Adding in-app purchases to your Flutter app]: {{site.codelabs}}/codelabs/flutter-in-app-purchases
### Flutter and Firebase
* [Add a user authentication flow to a Flutter app using FirebaseUI][]<br>
Learn how to add Firebase authentication to a Flutter app
with only a few lines of code.
* [Get to know Firebase for Flutter][firebase-ws] (workshop)<br>
An instructor-led version of our popular
"Get to know Firebase for Flutter" codelab
(listed below).
* [Get to know Firebase for Flutter][]<br>
Build an event RSVP and guestbook chat app on both Android
and iOS using Flutter, authenticating users with Firebase
Authentication, and sync data using Cloud Firestore.
* [Local development for your Flutter apps using the Firebase Emulator Suite][]<br>
Learn how to use the Firebase Emulator Suite when
developing with Flutter. You will also learn to use
the Auth and Firestore emulators.
[Add a user authentication flow to a Flutter app using FirebaseUI]: {{site.firebase}}/codelabs/firebase-auth-in-flutter-apps
[firebase-ws]: {{site.yt.watch}}?v=wUSkeTaBonA
[Get to know Firebase for Flutter]: {{site.firebase}}/codelabs/firebase-get-to-know-flutter
[Local development for your Flutter apps using the Firebase Emulator Suite]: {{site.firebase}}/codelabs/get-started-firebase-emulators-and-flutter
### Flutter and TensorFlow
* [Create a custom text-classification model with TensorFlow Lite Model Maker][]<br>
* [Create a Flutter app to classify texts with TensorFlow][]<br>
Learn how to run a text-classification inference from a Flutter
app with TensorFlow Serving through REST and gRPC.
* [Train a comment-spam detection model with TensorFlow Lite Model Maker][]<br>
Learn how to install the TensorFlow Lite Model Maker with Colab,
how to use a data loader, and how to build a model.
[Create a custom text-classification model with TensorFlow Lite Model Maker]: {{site.developers}}/codelabs/classify-text-update-tensorflow-serving
[Create a Flutter app to classify texts with TensorFlow]: {{site.developers}}/codelabs/classify-texts-flutter-tensorflow-serving
[Train a comment-spam detection model with TensorFlow Lite Model Maker]: {{site.developers}}/codelabs/classify-text-tensorflow-serving
### Flutter and other technologies
* [Adding Google Maps to a Flutter app][]<br>
Display a Google map in an app, retrieve data from a
web service, and display the data as markers on the map.
* [Adding WebView to your Flutter app][]<br>
With the WebView Flutter plugin you can add a WebView
widget to your Android or iOS Flutter app.
* [Build voice bots for mobile with Dialogflow and Flutter][] (workshop)<br>
An instructor-led version of the Dialogflow
and Flutter codelab (listed below).
* [Build voice bots for Android with Dialogflow and Flutter][]<br>
Learn how to build a mobile FAQ bot that can answer most
common questions about the tool Dialogflow. End users
can interact with the text interface or stream a voice
interaction via the built-in microphone of a mobile device.
* [Introduction to Flame with Flutter][]<br>
Build a Breakout clone using the Flame 2D game engine and
embed it in a Flutter wrapper. You will use Flame's Effects
to animate and remove components, along with the `google_fonts` and
`flutter_animate` packages, to make the whole game look well designed.
* [Using FFI in a Flutter plugin][]<br>
Learn how to use Dart's FFI (foreign function interface)
library, ffigen, allowing you to leverage
existing native libraries that provide a
C interface.
* [Create haikus about Google products with the PaLM API and Flutter][]<br>
Learn how to build an app that uses the PaLM API to
generate haikus based on Google product names. The
PaLM API gives you access to Google's
state-of-the-art large language models.
[Adding Google Maps to a Flutter app]: {{site.codelabs}}/codelabs/google-maps-in-flutter
[Adding WebView to your Flutter app]: {{site.codelabs}}/codelabs/flutter-webview
[Build voice bots for Android with Dialogflow and Flutter]: {{site.codelabs}}/codelabs/dialogflow-flutter
[Build voice bots for mobile with Dialogflow and Flutter]: {{site.yt.watch}}?v=O7JfSF3CJ84
[Introduction to Flame with Flutter]: {{site.codelabs}}/codelabs/flutter-flame-brick-breaker
[Using FFI in a Flutter plugin]: {{site.codelabs}}/codelabs/flutter-ffigen
[Create haikus about Google products with the PaLM API and Flutter]: {{site.codelabs}}/haiku-generator
## Testing
Learn how to test your Flutter application.
* [How to test a Flutter app][]<br>
Start with a simple app that manages state with the Provider package.
Unit test the provider package. Write widget tests for two of the
widgets. Use Flutter Driver to create an integration test.
[How to test a Flutter app]: {{site.codelabs}}/codelabs/flutter-app-testing/#0
## Writing platform-specific code
Learn how to write code that's targeted for specific platforms,
like iOS, Android, desktop, or the web.
* [How to write a Flutter plugin][]<br>
Learn how to write a plugin by creating a music plugin
for iOS and Android that processes audio on the host platform.
Then make an example app that uses your plugin to make a music keyboard.
* [Using a plugin with a Flutter web app][]<br>
Finish an app that reports the number of stars on a GitHub repository.
Use Dart DevTools to do some simple debugging, and
host your app on Firebase and, finally, use a Flutter plugin to
launch the app and open the hosted privacy policy.
* [Write a Flutter desktop application][]<br>
Build a Flutter desktop app (Windows, Linux, or macOS)
that accesses GitHub APIs to retrieve your repositories,
assigned issues, and pull requests. As part of this task,
create and use plugins to interact with native APIs and desktop applications,
and use code generation to build type-safe client libraries for GitHub's APIs.
* [Adding a Home Screen widget to your Flutter app][home-screen]<br> **NEW**
Learn how to add a Home Screen widget to your Flutter app
on iOS. This applies to your home screen, lock screen, or the
today view.
[home-screen]: {{site.codelabs}}/flutter-home-screen-widgets
[How to write a Flutter plugin]: {{site.codelabs}}/codelabs/write-flutter-plugin
[provider]: {{site.pub-pkg}}/provider
[Using a plugin with a Flutter web app]: {{site.codelabs}}/codelabs/web-url-launcher
[Write a Flutter desktop application]: {{site.codelabs}}/codelabs/flutter-github-client
## Other resources
For Dart-specific codelabs, see the
[codelabs][] page on the [Dart site][].
We also recommend the following online class:
* [The Complete Flutter Development Bootcamp Using Dart][]
{{site.alert.note}}
If you have trouble viewing any of the codelabs
on [`codelabs.developers.google.com`]({{site.codelabs}}), try
[this mirror of the Flutter codelabs][].
{{site.alert.end}}
[codelabs]: {{site.dart-site}}/codelabs
[Dart site]: {{site.dart-site}}
[The Complete Flutter Development Bootcamp Using Dart]: https://www.appbrewery.co/p/flutter-development-bootcamp-with-dart
[this mirror of the Flutter codelabs]: https://codelabs.flutter-io.cn/
| website/src/codelabs/index.md/0 | {
"file_path": "website/src/codelabs/index.md",
"repo_id": "website",
"token_count": 4204
} | 1,301 |
---
title: Work with tabs
description: How to implement tabs in a layout.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/design/tabs/"?>
Working with tabs is a common pattern in apps that follow the
Material Design guidelines.
Flutter includes a convenient way to create tab layouts as part of
the [material library][].
This recipe creates a tabbed example using the following steps;
1. Create a `TabController`.
2. Create the tabs.
3. Create content for each tab.
## 1. Create a `TabController`
For tabs to work, you need to keep the selected tab and content
sections in sync.
This is the job of the [`TabController`][].
Either create a `TabController` manually,
or automatically by using a [`DefaultTabController`][] widget.
Using `DefaultTabController` is the simplest option, since it
creates a `TabController` and makes it available to all descendant widgets.
<?code-excerpt "lib/partials.dart (TabController)"?>
```dart
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(),
),
);
```
## 2. Create the tabs
When a tab is selected, it needs to display content.
You can create tabs using the [`TabBar`][] widget.
In this example, create a `TabBar` with three
[`Tab`][] widgets and place it within an [`AppBar`][].
<?code-excerpt "lib/partials.dart (Tabs)"?>
```dart
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
),
),
),
);
```
By default, the `TabBar` looks up the widget tree for the nearest
`DefaultTabController`. If you're manually creating a `TabController`,
pass it to the `TabBar`.
## 3. Create content for each tab
Now that you have tabs, display content when a tab is selected.
For this purpose, use the [`TabBarView`][] widget.
{{site.alert.note}}
Order is important and must correspond to the order of the tabs in the
`TabBar`.
{{site.alert.end}}
<?code-excerpt "lib/main.dart (TabBarView)"?>
```dart
body: const TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
```
## Interactive example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
import 'package:flutter/material.dart';
void main() {
runApp(const TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
const TabBarDemo({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/tabs.gif" alt="Tabs Demo" class="site-mobile-screenshot" />
</noscript>
[`AppBar`]: {{site.api}}/flutter/material/AppBar-class.html
[`DefaultTabController`]: {{site.api}}/flutter/material/DefaultTabController-class.html
[material library]: {{site.api}}/flutter/material/material-library.html
[`Tab`]: {{site.api}}/flutter/material/Tab-class.html
[`TabBar`]: {{site.api}}/flutter/material/TabBar-class.html
[`TabBarView`]: {{site.api}}/flutter/material/TabBarView-class.html
[`TabController`]: {{site.api}}/flutter/material/TabController-class.html
| website/src/cookbook/design/tabs.md/0 | {
"file_path": "website/src/cookbook/design/tabs.md",
"repo_id": "website",
"token_count": 1593
} | 1,302 |
---
title: Handle changes to a text field
description: How to detect changes to a text field.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/forms/text_field_changes/"?>
In some cases, it's useful to run a callback function every time the text
in a text field changes. For example, you might want to build a search
screen with autocomplete functionality where you want to update the
results as the user types.
How do you run a callback function every time the text changes?
With Flutter, you have two options:
1. Supply an `onChanged()` callback to a `TextField` or a `TextFormField`.
2. Use a `TextEditingController`.
## 1. Supply an `onChanged()` callback to a `TextField` or a `TextFormField`
The simplest approach is to supply an [`onChanged()`][] callback to a
[`TextField`][] or a [`TextFormField`][].
Whenever the text changes, the callback is invoked.
In this example, print the current value and length of the text field
to the console every time the text changes.
It's important to use [characters][] when dealing with user input,
as text may contain complex characters.
This ensures that every character is counted correctly
as they appear to the user.
<?code-excerpt "lib/main.dart (TextField1)"?>
```dart
TextField(
onChanged: (text) {
print('First text field: $text (${text.characters.length})');
},
),
```
## 2. Use a `TextEditingController`
A more powerful, but more elaborate approach, is to supply a
[`TextEditingController`][] as the [`controller`][]
property of the `TextField` or a `TextFormField`.
To be notified when the text changes, listen to the controller
using the [`addListener()`][] method using the following steps:
1. Create a `TextEditingController`.
2. Connect the `TextEditingController` to a text field.
3. Create a function to print the latest value.
4. Listen to the controller for changes.
### Create a `TextEditingController`
Create a `TextEditingController`:
<?code-excerpt "lib/main_step1.dart (Step1)" remove="return Container();"?>
```dart
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller. Later, use it to retrieve the
// current value of the TextField.
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is removed from the
// widget tree.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Fill this out in the next step.
}
}
```
{{site.alert.note}}
Remember to dispose of the `TextEditingController` when it's no
longer needed. This ensures that you discard any resources used
by the object.
{{site.alert.end}}
### Connect the `TextEditingController` to a text field
Supply the `TextEditingController` to either a `TextField`
or a `TextFormField`. Once you wire these two classes together,
you can begin listening for changes to the text field.
<?code-excerpt "lib/main.dart (TextField2)"?>
```dart
TextField(
controller: myController,
),
```
### Create a function to print the latest value
You need a function to run every time the text changes.
Create a method in the `_MyCustomFormState` class that prints
out the current value of the text field.
<?code-excerpt "lib/main.dart (printLatestValue)"?>
```dart
void _printLatestValue() {
final text = myController.text;
print('Second text field: $text (${text.characters.length})');
}
```
### Listen to the controller for changes
Finally, listen to the `TextEditingController` and call the
`_printLatestValue()` method when the text changes. Use the
[`addListener()`][] method for this purpose.
Begin listening for changes when the
`_MyCustomFormState` class is initialized,
and stop listening when the `_MyCustomFormState` is disposed.
<?code-excerpt "lib/main.dart (initState)"?>
```dart
@override
void initState() {
super.initState();
// Start listening to changes.
myController.addListener(_printLatestValue);
}
```
<?code-excerpt "lib/main.dart (dispose)"?>
```dart
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _printLatestValue listener.
myController.dispose();
super.dispose();
}
```
## Interactive example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void initState() {
super.initState();
// Start listening to changes.
myController.addListener(_printLatestValue);
}
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _printLatestValue listener.
myController.dispose();
super.dispose();
}
void _printLatestValue() {
final text = myController.text;
print('Second text field: $text (${text.characters.length})');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
onChanged: (text) {
print('First text field: $text (${text.characters.length})');
},
),
TextField(
controller: myController,
),
],
),
),
);
}
}
```
[`addListener()`]: {{site.api}}/flutter/foundation/ChangeNotifier/addListener.html
[`controller`]: {{site.api}}/flutter/material/TextField/controller.html
[`onChanged()`]: {{site.api}}/flutter/material/TextField/onChanged.html
[`TextField`]: {{site.api}}/flutter/material/TextField-class.html
[`TextEditingController`]: {{site.api}}/flutter/widgets/TextEditingController-class.html
[`TextFormField`]: {{site.api}}/flutter/material/TextFormField-class.html
[characters]: {{site.pub}}/packages/characters
| website/src/cookbook/forms/text-field-changes.md/0 | {
"file_path": "website/src/cookbook/forms/text-field-changes.md",
"repo_id": "website",
"token_count": 2291
} | 1,303 |
---
title: Use lists
description: How to implement a list.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/lists/basic_list"?>
Displaying lists of data is a fundamental pattern for mobile apps.
Flutter includes the [`ListView`][]
widget to make working with lists a breeze.
## Create a ListView
Using the standard `ListView` constructor is
perfect for lists that contain only a few items.
The built-in [`ListTile`][]
widget is a way to give items a visual structure.
<?code-excerpt "lib/main.dart (ListView)" replace="/^body\: //g"?>
```dart
ListView(
children: const <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone'),
),
],
),
```
## Interactive example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Basic List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: ListView(
children: const <Widget>[
ListTile(
leading: Icon(Icons.map),
title: Text('Map'),
),
ListTile(
leading: Icon(Icons.photo_album),
title: Text('Album'),
),
ListTile(
leading: Icon(Icons.phone),
title: Text('Phone'),
),
],
),
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/basic-list.png" alt="Basic List Demo" class="site-mobile-screenshot" />
</noscript>
[`ListTile`]: {{site.api}}/flutter/material/ListTile-class.html
[`ListView`]: {{site.api}}/flutter/widgets/ListView-class.html
| website/src/cookbook/lists/basic-list.md/0 | {
"file_path": "website/src/cookbook/lists/basic-list.md",
"repo_id": "website",
"token_count": 934
} | 1,304 |
---
title: Return data from a screen
description: How to return data from a new screen.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/navigation/returning_data/"?>
In some cases, you might want to return data from a new screen.
For example, say you push a new screen that presents two options to a user.
When the user taps an option, you want to inform the first screen
of the user's selection so that it can act on that information.
You can do this with the [`Navigator.pop()`][]
method using the following steps:
1. Define the home screen
2. Add a button that launches the selection screen
3. Show the selection screen with two buttons
4. When a button is tapped, close the selection screen
5. Show a snackbar on the home screen with the selection
## 1. Define the home screen
The home screen displays a button. When tapped,
it launches the selection screen.
<?code-excerpt "lib/main_step2.dart (HomeScreen)"?>
```dart
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Returning Data Demo'),
),
// Create the SelectionButton widget in the next step.
body: const Center(
child: SelectionButton(),
),
);
}
}
```
## 2. Add a button that launches the selection screen
Now, create the SelectionButton, which does the following:
* Launches the SelectionScreen when it's tapped.
* Waits for the SelectionScreen to return a result.
<?code-excerpt "lib/main_step2.dart (SelectionButton)"?>
```dart
class SelectionButton extends StatefulWidget {
const SelectionButton({super.key});
@override
State<SelectionButton> createState() => _SelectionButtonState();
}
class _SelectionButtonState extends State<SelectionButton> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
_navigateAndDisplaySelection(context);
},
child: const Text('Pick an option, any option!'),
);
}
Future<void> _navigateAndDisplaySelection(BuildContext context) async {
// Navigator.push returns a Future that completes after calling
// Navigator.pop on the Selection Screen.
final result = await Navigator.push(
context,
// Create the SelectionScreen in the next step.
MaterialPageRoute(builder: (context) => const SelectionScreen()),
);
}
}
```
## 3. Show the selection screen with two buttons
Now, build a selection screen that contains two buttons.
When a user taps a button,
that app closes the selection screen and lets the home
screen know which button was tapped.
This step defines the UI.
The next step adds code to return data.
<?code-excerpt "lib/main_step2.dart (SelectionScreen)"?>
```dart
class SelectionScreen extends StatelessWidget {
const SelectionScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Pick an option'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () {
// Pop here with "Yep"...
},
child: const Text('Yep!'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () {
// Pop here with "Nope"...
},
child: const Text('Nope.'),
),
)
],
),
),
);
}
}
```
## 4. When a button is tapped, close the selection screen
Now, update the `onPressed()` callback for both of the buttons.
To return data to the first screen,
use the [`Navigator.pop()`][] method,
which accepts an optional second argument called `result`.
Any result is returned to the `Future` in the SelectionButton.
### Yep button
<?code-excerpt "lib/main.dart (Yep)" replace="/^child: //g;/,$//g"?>
```dart
ElevatedButton(
onPressed: () {
// Close the screen and return "Yep!" as the result.
Navigator.pop(context, 'Yep!');
},
child: const Text('Yep!'),
)
```
### Nope button
<?code-excerpt "lib/main.dart (Nope)" replace="/^child: //g;/,$//g"?>
```dart
ElevatedButton(
onPressed: () {
// Close the screen and return "Nope." as the result.
Navigator.pop(context, 'Nope.');
},
child: const Text('Nope.'),
)
```
## 5. Show a snackbar on the home screen with the selection
Now that you're launching a selection screen and awaiting the result,
you'll want to do something with the information that's returned.
In this case, show a snackbar displaying the result by using the
`_navigateAndDisplaySelection()` method in `SelectionButton`:
<?code-excerpt "lib/main.dart (navigateAndDisplay)"?>
```dart
// A method that launches the SelectionScreen and awaits the result from
// Navigator.pop.
Future<void> _navigateAndDisplaySelection(BuildContext context) async {
// Navigator.push returns a Future that completes after calling
// Navigator.pop on the Selection Screen.
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SelectionScreen()),
);
// When a BuildContext is used from a StatefulWidget, the mounted property
// must be checked after an asynchronous gap.
if (!context.mounted) return;
// After the Selection Screen returns a result, hide any previous snackbars
// and show the new result.
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$result')));
}
```
## Interactive example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
title: 'Returning Data',
home: HomeScreen(),
),
);
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Returning Data Demo'),
),
body: const Center(
child: SelectionButton(),
),
);
}
}
class SelectionButton extends StatefulWidget {
const SelectionButton({super.key});
@override
State<SelectionButton> createState() => _SelectionButtonState();
}
class _SelectionButtonState extends State<SelectionButton> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
_navigateAndDisplaySelection(context);
},
child: const Text('Pick an option, any option!'),
);
}
// A method that launches the SelectionScreen and awaits the result from
// Navigator.pop.
Future<void> _navigateAndDisplaySelection(BuildContext context) async {
// Navigator.push returns a Future that completes after calling
// Navigator.pop on the Selection Screen.
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SelectionScreen()),
);
// When a BuildContext is used from a StatefulWidget, the mounted property
// must be checked after an asynchronous gap.
if (!context.mounted) return;
// After the Selection Screen returns a result, hide any previous snackbars
// and show the new result.
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(SnackBar(content: Text('$result')));
}
}
class SelectionScreen extends StatelessWidget {
const SelectionScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Pick an option'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () {
// Close the screen and return "Yep!" as the result.
Navigator.pop(context, 'Yep!');
},
child: const Text('Yep!'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () {
// Close the screen and return "Nope." as the result.
Navigator.pop(context, 'Nope.');
},
child: const Text('Nope.'),
),
)
],
),
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/returning-data.gif" alt="Returning data demo" class="site-mobile-screenshot" />
</noscript>
[`Navigator.pop()`]: {{site.api}}/flutter/widgets/Navigator/pop.html
| website/src/cookbook/navigation/returning-data.md/0 | {
"file_path": "website/src/cookbook/navigation/returning-data.md",
"repo_id": "website",
"token_count": 3389
} | 1,305 |
---
title: Plugins
description: A catalog of recipes showcasing using plugins in your Flutter app.
---
{% include docs/cookbook-group-index.md %}
| website/src/cookbook/plugins/index.md/0 | {
"file_path": "website/src/cookbook/plugins/index.md",
"repo_id": "website",
"token_count": 42
} | 1,306 |
---
title: Firebase
description: How to use Firebase and Firestore with Flutter.
---
## Introduction
Firebase is a Backend-as-a-Service (BaaS) app development platform
that provides hosted backend services such as a realtime database,
cloud storage, authentication, crash reporting, machine learning,
remote configuration, and hosting for your static files.
## Flutter and Firebase resources
Firebase supports Flutter. To learn more,
check out the following resources.
### Documentation
* [Getting started with Firebase and Flutter][started]
* [Firebase plugins][]
### Blog Posts
[Use Firebase to host your Flutter app on the web][article]
### Tutorials
Get to know Firebase for Flutter
* [tutorial][codelab1]
* [video workshop][workshop]
## Flutter and Firebase community resources
The Flutter community created the following useful resources.
### Blog Posts
[Building chat app with Flutter and Firebase][chat app]
### Videos
* [Using Firestore as a backend to your Flutter app][video]
* [Live Coding Firebase Authentication with Flutter][video2]
* [Flutter & Firebase Auth 01][video3]
* [Flutter: Firebase Tutorial Part 1 - Auth and Sign in][video4]
[article]: {{site.flutter-medium}}/must-try-use-firebase-to-host-your-flutter-app-on-the-web-852ee533a469
[chat app]: {{site.medium}}/flutter-community/building-a-chat-app-with-flutter-and-firebase-from-scratch-9eaa7f41782e
[codelab1]: {{site.codelabs}}/codelabs/firebase-get-to-know-flutter
[Firebase plugins]: {{site.firebase}}/docs/flutter/setup#available-plugins
[started]: {{site.firebase}}/docs/flutter/setup
[video]: {{site.yt.watch}}/DqJ_KjFzL9I&t#38s
[video2]: {{site.yt.watch}}/OlcYP6UXlm8
[video3]: {{site.yt.watch}}/u_Lyx8KJWpg
[video4]: {{site.yt.watch}}/13-jNF984C0
[workshop]: {{site.yt.watch}}/4wunbF29Kkg
| website/src/data-and-backend/firebase.md/0 | {
"file_path": "website/src/data-and-backend/firebase.md",
"repo_id": "website",
"token_count": 588
} | 1,307 |
---
layout: toc
title: Deployment
description: Content covering deployment of Flutter apps.
---
| website/src/deployment/index.md/0 | {
"file_path": "website/src/deployment/index.md",
"repo_id": "website",
"token_count": 25
} | 1,308 |
---
title: Flutter for React Native developers
description: Learn how to apply React Native developer knowledge when building Flutter apps.
---
<?code-excerpt path-base="get-started/flutter-for/react_native_devs"?>
This document is for React Native (RN) developers looking to apply their
existing RN knowledge to build mobile apps with Flutter. If you understand
the fundamentals of the RN framework then you can use this document as a
way to get started learning Flutter development.
This document can be used as a cookbook by jumping around and finding
questions that are most relevant to your needs.
## Introduction to Dart for JavaScript Developers (ES6)
Like React Native, Flutter uses reactive-style views. However, while RN
transpiles to native widgets, Flutter compiles all the way to native code.
Flutter controls each pixel on the screen, which avoids performance problems
caused by the need for a JavaScript bridge.
Dart is an easy language to learn and offers the following features:
* Provides an open-source, scalable programming language for building web,
server, and mobile apps.
* Provides an object-oriented, single inheritance language that uses a C-style
syntax that is AOT-compiled into native.
* Transcompiles optionally into JavaScript.
* Supports interfaces and abstract classes.
A few examples of the differences between JavaScript and Dart are described
below.
### Entry point
JavaScript doesn't have a pre-defined entry
function—you define the entry point.
```js
// JavaScript
function startHere() {
// Can be used as entry point
}
```
In Dart, every app must have a top-level `main()` function that serves as the
entry point to the app.
<?code-excerpt "lib/main.dart (Main)"?>
```dart
/// Dart
void main() {}
```
Try it out in [DartPad][DartPadA].
### Printing to the console
To print to the console in Dart, use `print()`.
```js
// JavaScript
console.log('Hello world!');
```
<?code-excerpt "lib/main.dart (Print)"?>
```dart
/// Dart
print('Hello world!');
```
Try it out in [DartPad][DartPadB].
### Variables
Dart is type safe—it uses a combination of static type checking
and runtime checks to ensure that a variable's value always matches
the variable's static type. Although types are mandatory,
some type annotations are optional because
Dart performs type inference.
#### Creating and assigning variables
In JavaScript, variables cannot be typed.
In [Dart][], variables must either be explicitly
typed or the type system must infer the proper type automatically.
```js
// JavaScript
let name = 'JavaScript';
```
<?code-excerpt "lib/main.dart (Variables)"?>
```dart
/// Dart
/// Both variables are acceptable.
String name = 'dart'; // Explicitly typed as a [String].
var otherName = 'Dart'; // Inferred [String] type.
```
Try it out in [DartPad][DartPadC].
For more information, see [Dart's Type System][].
#### Default value
In JavaScript, uninitialized variables are `undefined`.
In Dart, uninitialized variables have an initial value of `null`.
Because numbers are objects in Dart, even uninitialized variables with
numeric types have the value `null`.
{{site.alert.note}}
As of 2.12, Dart supports [Sound Null Safety][],
all underlying types are non-nullable by default,
which must be initialized as a non-nullable value.
{{site.alert.end}}
```js
// JavaScript
let name; // == undefined
```
<?code-excerpt "lib/main.dart (Null)"?>
```dart
// Dart
var name; // == null; raises a linter warning
int? x; // == null
```
Try it out in [DartPad][DartPadD].
For more information, see the documentation on
[variables][].
### Checking for null or zero
In JavaScript, values of 1 or any non-null objects
are treated as `true` when using the `==` comparison operator.
```js
// JavaScript
let myNull = null;
if (!myNull) {
console.log('null is treated as false');
}
let zero = 0;
if (!zero) {
console.log('0 is treated as false');
}
```
In Dart, only the boolean value `true` is treated as true.
<?code-excerpt "lib/main.dart (True)"?>
```dart
/// Dart
var myNull;
var zero = 0;
if (zero == 0) {
print('use "== 0" to check zero');
}
```
Try it out in [DartPad][DartPadE].
### Functions
Dart and JavaScript functions are generally similar.
The primary difference is the declaration.
```js
// JavaScript
function fn() {
return true;
}
```
<?code-excerpt "lib/main.dart (Function)"?>
```dart
/// Dart
/// You can explicitly define the return type.
bool fn() {
return true;
}
```
Try it out in [DartPad][DartPadF].
For more information, see the documentation on
[functions][].
### Asynchronous programming
#### Futures
Like JavaScript, Dart supports single-threaded execution. In JavaScript,
the Promise object represents the eventual completion (or failure)
of an asynchronous operation and its resulting value.
Dart uses [`Future`][] objects to handle this.
```js
// JavaScript
class Example {
_getIPAddress() {
const url = 'https://httpbin.org/ip';
return fetch(url)
.then(response => response.json())
.then(responseJson => {
const ip = responseJson.origin;
return ip;
});
}
}
function main() {
const example = new Example();
example
._getIPAddress()
.then(ip => console.log(ip))
.catch(error => console.error(error));
}
main();
```
<?code-excerpt "lib/futures.dart"?>
```dart
// Dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class Example {
Future<String> _getIPAddress() {
final url = Uri.https('httpbin.org', '/ip');
return http.get(url).then((response) {
final ip = jsonDecode(response.body)['origin'] as String;
return ip;
});
}
}
void main() {
final example = Example();
example
._getIPAddress()
.then((ip) => print(ip))
.catchError((error) => print(error));
}
```
For more information, see the documentation on
[`Future`][] objects.
#### `async` and `await`
The `async` function declaration defines an asynchronous function.
In JavaScript, the `async` function returns a `Promise`.
The `await` operator is used to wait for a `Promise`.
```js
// JavaScript
class Example {
async function _getIPAddress() {
const url = 'https://httpbin.org/ip';
const response = await fetch(url);
const json = await response.json();
const data = json.origin;
return data;
}
}
async function main() {
const example = new Example();
try {
const ip = await example._getIPAddress();
console.log(ip);
} catch (error) {
console.error(error);
}
}
main();
```
In Dart, an `async` function returns a `Future`,
and the body of the function is scheduled for execution later.
The `await` operator is used to wait for a `Future`.
<?code-excerpt "lib/async.dart"?>
```dart
// Dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class Example {
Future<String> _getIPAddress() async {
final url = Uri.https('httpbin.org', '/ip');
final response = await http.get(url);
final ip = jsonDecode(response.body)['origin'] as String;
return ip;
}
}
/// An async function returns a `Future`.
/// It can also return `void`, unless you use
/// the `avoid_void_async` lint. In that case,
/// return `Future<void>`.
void main() async {
final example = Example();
try {
final ip = await example._getIPAddress();
print(ip);
} catch (error) {
print(error);
}
}
```
For more information, see the documentation for [async and await][].
## The basics
### How do I create a Flutter app?
To create an app using React Native,
you would run `create-react-native-app` from the command line.
```terminal
$ create-react-native-app <projectname>
```
To create an app in Flutter, do one of the following:
* Use an IDE with the Flutter and Dart plugins installed.
* Use the `flutter create` command from the command line. Make sure that the
Flutter SDK is in your PATH.
```terminal
$ flutter create <projectname>
```
For more information, see [Getting started][], which
walks you through creating a button-click counter app.
Creating a Flutter project builds all the files that you
need to run a sample app on both Android and iOS devices.
### How do I run my app?
In React Native, you would run `npm run` or `yarn run` from the project
directory.
You can run Flutter apps in a couple of ways:
* Use the "run" option in an IDE with the Flutter and Dart plugins.
* Use `flutter run` from the project's root directory.
Your app runs on a connected device, the iOS simulator,
or the Android emulator.
For more information, see the Flutter [Getting started][]
documentation.
### How do I import widgets?
In React Native, you need to import each required component.
```js
// React Native
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
```
In Flutter, to use widgets from the Material Design library,
import the `material.dart` package. To use iOS style widgets,
import the Cupertino library. To use a more basic widget set,
import the Widgets library.
Or, you can write your own widget library and import that.
<?code-excerpt "lib/imports.dart (Imports)"?>
```dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:my_widgets/my_widgets.dart';
```
Whichever widget package you import,
Dart pulls in only the widgets that are used in your app.
For more information, see the [Flutter Widget Catalog][].
### What is the equivalent of the React Native "Hello world!" app in Flutter?
In React Native, the `HelloWorldApp` class extends `React.Component` and
implements the render method by returning a view component.
```js
// React Native
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text>Hello world!</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});
export default App;
```
In Flutter, you can create an identical "Hello world!" app using the
`Center` and `Text` widgets from the core widget library.
The `Center` widget becomes the root of the widget tree and has one child,
the `Text` widget.
<?code-excerpt "lib/hello_world.dart"?>
```dart
// Flutter
import 'package:flutter/material.dart';
void main() {
runApp(
const Center(
child: Text(
'Hello, world!',
textDirection: TextDirection.ltr,
),
),
);
}
```
The following images show the Android and iOS UI for the basic Flutter
"Hello world!" app.
{% include docs/android-ios-figure-pair.md image="react-native/hello-world-basic.png" alt="Hello world app" class="border" %}
Now that you've seen the most basic Flutter app, the next section shows how to
take advantage of Flutter's rich widget libraries to create a modern, polished
app.
### How do I use widgets and nest them to form a widget tree?
In Flutter, almost everything is a widget.
Widgets are the basic building blocks of an app's user interface.
You compose widgets into a hierarchy, called a widget tree.
Each widget nests inside a parent widget
and inherits properties from its parent.
Even the application object itself is a widget.
There is no separate "application" object.
Instead, the root widget serves this role.
A widget can define:
* A structural element—like a button or menu
* A stylistic element—like a font or color scheme
* An aspect of layout—like padding or alignment
The following example shows the "Hello world!" app using widgets from the
Material library. In this example, the widget tree is nested inside the
`MaterialApp` root widget.
<?code-excerpt "lib/widget_tree.dart"?>
```dart
// Flutter
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: const Center(
child: Text('Hello world'),
),
),
);
}
}
```
The following images show "Hello world!" built from Material Design widgets.
You get more functionality for free than in the basic "Hello world!" app.
{% include docs/android-ios-figure-pair.md image="react-native/hello-world.png" alt="Hello world app" %}
When writing an app, you'll use two types of widgets:
[`StatelessWidget`][] or [`StatefulWidget`][].
A `StatelessWidget` is just what it sounds like—a
widget with no state. A `StatelessWidget` is created once,
and never changes its appearance.
A `StatefulWidget` dynamically changes state based on data
received, or user input.
The important difference between stateless and stateful
widgets is that `StatefulWidget`s have a `State` object
that stores state data and carries it over
across tree rebuilds, so it's not lost.
In simple or basic apps it's easy to nest widgets,
but as the code base gets larger and the app becomes complex,
you should break deeply nested widgets into
functions that return the widget or smaller classes.
Creating separate functions
and widgets allows you to reuse the components within the app.
### How do I create reusable components?
In React Native, you would define a class to create a
reusable component and then use `props` methods to set
or return properties and values of the selected elements.
In the example below, the `CustomCard` class is defined
and then used inside a parent class.
```js
// React Native
const CustomCard = ({ index, onPress }) => {
return (
<View>
<Text> Card {index} </Text>
<Button
title="Press"
onPress={() => onPress(index)}
/>
</View>
);
};
// Usage
<CustomCard onPress={this.onPress} index={item.key} />
```
In Flutter, define a class to create a custom widget and then reuse the
widget. You can also define and call a function that returns a
reusable widget as shown in the `build` function in the following example.
<?code-excerpt "lib/components.dart (Components)"?>
```dart
/// Flutter
class CustomCard extends StatelessWidget {
const CustomCard({
super.key,
required this.index,
required this.onPress,
});
final int index;
final void Function() onPress;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: <Widget>[
Text('Card $index'),
TextButton(
onPressed: onPress,
child: const Text('Press'),
),
],
),
);
}
}
class UseCard extends StatelessWidget {
const UseCard({super.key, required this.index});
final int index;
@override
Widget build(BuildContext context) {
/// Usage
return CustomCard(
index: index,
onPress: () {
print('Card $index');
},
);
}
}
```
In the previous example, the constructor for the `CustomCard`
class uses Dart's curly brace syntax `{ }` to indicate [named parameters][].
To require these fields, either remove the curly braces from
the constructor, or add `required` to the constructor.
The following screenshots show an example of the reusable
`CustomCard` class.
{% include docs/android-ios-figure-pair.md image="react-native/custom-cards.png" alt="Custom cards" class="border" %}
## Project structure and resources
### Where do I start writing the code?
Start with the `lib/main.dart` file.
It's autogenerated when you create a Flutter app.
<?code-excerpt "lib/examples.dart (Main)"?>
```dart
// Dart
void main() {
print('Hello, this is the main function.');
}
```
In Flutter, the entry point file is
`{project_name}/lib/main.dart` and execution
starts from the `main` function.
### How are files structured in a Flutter app?
When you create a new Flutter project,
it builds the following directory structure.
You can customize it later, but this is where you start.
```
┬
└ project_name
┬
├ android - Contains Android-specific files.
├ build - Stores iOS and Android build files.
├ ios - Contains iOS-specific files.
├ lib - Contains externally accessible Dart source files.
┬
└ src - Contains additional source files.
└ main.dart - The Flutter entry point and the start of a new app.
This is generated automatically when you create a Flutter
project.
It's where you start writing your Dart code.
├ test - Contains automated test files.
└ pubspec.yaml - Contains the metadata for the Flutter app.
This is equivalent to the package.json file in React Native.
```
### Where do I put my resources and assets and how do I use them?
A Flutter resource or asset is a file that is bundled and deployed
with your app and is accessible at runtime.
Flutter apps can include the following asset types:
* Static data such as JSON files
* Configuration files
* Icons and images (JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP,
and WBMP)
Flutter uses the `pubspec.yaml` file,
located at the root of your project, to
identify assets required by an app.
```yaml
flutter:
assets:
- assets/my_icon.png
- assets/background.png
```
The `assets` subsection specifies files that should be included with the app.
Each asset is identified by an explicit path
relative to the `pubspec.yaml` file, where the asset file is located.
The order in which the assets are declared does not matter.
The actual directory used (`assets` in this case) does not matter.
However, while assets can be placed in any app directory, it's a
best practice to place them in the `assets` directory.
During a build, Flutter places assets into a special archive
called the *asset bundle*, which apps read from at runtime.
When an asset's path is specified in the assets' section of `pubspec.yaml`,
the build process looks for any files
with the same name in adjacent subdirectories.
These files are also included in the asset bundle
along with the specified asset. Flutter uses asset variants
when choosing resolution-appropriate images for your app.
In React Native, you would add a static image by placing the image file
in a source code directory and referencing it.
```js
<Image source={require('./my-icon.png')} />
// OR
<Image
source={%raw%}{{
url: 'https://reactnative.dev/img/tiny_logo.png'
}}{%endraw%}
/>
```
In Flutter, add a static image to your app
using the `Image.asset` constructor in a widget's build method.
<?code-excerpt "lib/examples.dart (ImageAsset)" replace="/return //g"?>
```dart
Image.asset('assets/background.png');
```
For more information, see [Adding Assets and Images in Flutter][].
### How do I load images over a network?
In React Native, you would specify the `uri` in the
`source` prop of the `Image` component and also provide the
size if needed.
In Flutter, use the `Image.network` constructor to include
an image from a URL.
<?code-excerpt "lib/examples.dart (ImageNetwork)" replace="/return //g"?>
```dart
Image.network('https://docs.flutter.dev/assets/images/docs/owl.jpg');
```
### How do I install packages and package plugins?
Flutter supports using shared packages contributed by other developers to the
Flutter and Dart ecosystems. This allows you to quickly build your app without
having to develop everything from scratch. Packages that contain
platform-specific code are known as package plugins.
In React Native, you would use `yarn add {package-name}` or
`npm install --save {package-name}` to install packages
from the command line.
In Flutter, install a package using the following instructions:
1. To add the `google_sign_in` package as a dependency, run `flutter pub add`:
```terminal
$ flutter pub add google_sign_in
```
2. Install the package from the command line by using `flutter pub get`.
If using an IDE, it often runs `flutter pub get` for you, or it might
prompt you to do so.
3. Import the package into your app code as shown below:
<?code-excerpt "lib/examples.dart (PackageImport)"?>
```dart
import 'package:flutter/material.dart';
```
For more information, see [Using Packages][] and
[Developing Packages & Plugins][].
You can find many packages shared by Flutter developers in the
[Flutter packages][] section of [pub.dev][].
## Flutter widgets
In Flutter, you build your UI out of widgets that describe what their view
should look like given their current configuration and state.
Widgets are often composed of many small,
single-purpose widgets that are nested to produce powerful effects.
For example, the `Container` widget consists of
several widgets responsible for layout, painting, positioning, and sizing.
Specifically, the `Container` widget includes the `LimitedBox`,
`ConstrainedBox`, `Align`, `Padding`, `DecoratedBox`, and `Transform` widgets.
Rather than subclassing `Container` to produce a customized effect, you can
compose these and other simple widgets in new and unique ways.
The `Center` widget is another example of how you can control the layout.
To center a widget, wrap it in a `Center` widget and then use layout
widgets for alignment, row, columns, and grids.
These layout widgets do not have a visual representation of their own.
Instead, their sole purpose is to control some aspect of another
widget's layout. To understand why a widget renders in a
certain way, it's often helpful to inspect the neighboring widgets.
For more information, see the [Flutter Technical Overview][].
For more information about the core widgets from the `Widgets` package,
see [Flutter Basic Widgets][],
the [Flutter Widget Catalog][],
or the [Flutter Widget Index][].
## Views
### What is the equivalent of the `View` container?
In React Native, `View` is a container that supports layout with `Flexbox`,
style, touch handling, and accessibility controls.
In Flutter, you can use the core layout widgets in the `Widgets`
library, such as [`Container`][], [`Column`][],
[`Row`][], and [`Center`][].
For more information, see the [Layout Widgets][] catalog.
### What is the equivalent of `FlatList` or `SectionList`?
A `List` is a scrollable list of components arranged vertically.
In React Native, `FlatList` or `SectionList` are used to render simple or
sectioned lists.
```js
// React Native
<FlatList
data={[ ... ]}
renderItem={({ item }) => <Text>{item.key}</Text>}
/>
```
[`ListView`][] is Flutter's most commonly used scrolling widget.
The default constructor takes an explicit list of children.
[`ListView`][] is most appropriate for a small number of widgets.
For a large or infinite list, use `ListView.builder`,
which builds its children on demand and only builds
those children that are visible.
<?code-excerpt "lib/examples.dart (ListView)"?>
```dart
var data = [
'Hello',
'World',
];
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Text(data[index]);
},
);
```
{% include docs/android-ios-figure-pair.md image="react-native/flatlist.gif" alt="Flat list" class="border" %}
To learn how to implement an infinite scrolling list, see the official
[`infinite_list`][infinite_list] sample.
### How do I use a Canvas to draw or paint?
In React Native, canvas components aren't present
so third party libraries like `react-native-canvas` are used.
```js
// React Native
const CanvasComp = () => {
const handleCanvas = (canvas) => {
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'skyblue';
ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI);
ctx.fillRect(150, 100, 300, 300);
ctx.stroke();
};
return (
<View>
<Canvas ref={this.handleCanvas} />
</View>
);
}
```
In Flutter, you can use the [`CustomPaint`][]
and [`CustomPainter`][] classes to draw to the canvas.
The following example shows how to draw during the paint phase using the
`CustomPaint` widget. It implements the abstract class, `CustomPainter`,
and passes it to `CustomPaint`'s painter property.
`CustomPaint` subclasses must implement the `paint()`
and `shouldRepaint()` methods.
<?code-excerpt "lib/examples.dart (CustomPaint)"?>
```dart
class MyCanvasPainter extends CustomPainter {
const MyCanvasPainter();
@override
void paint(Canvas canvas, Size size) {
final Paint paint = Paint()..color = Colors.amber;
canvas.drawCircle(const Offset(100, 200), 40, paint);
final Paint paintRect = Paint()..color = Colors.lightBlue;
final Rect rect = Rect.fromPoints(
const Offset(150, 300),
const Offset(300, 400),
);
canvas.drawRect(rect, paintRect);
}
@override
bool shouldRepaint(MyCanvasPainter oldDelegate) => false;
}
class MyCanvasWidget extends StatelessWidget {
const MyCanvasWidget({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: CustomPaint(painter: MyCanvasPainter()),
);
}
}
```
{% include docs/android-ios-figure-pair.md image="react-native/canvas.png" alt="Canvas" class="border" %}
## Layouts
### How do I use widgets to define layout properties?
In React Native, most of the layout can be done with the props
that are passed to a specific component.
For example, you could use the `style` prop on the `View` component
in order to specify the flexbox properties.
To arrange your components in a column, you would specify a prop such as:
`flexDirection: 'column'`.
```js
// React Native
<View
style={%raw%}{{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center'
}}{%endraw%}
>
```
In Flutter, the layout is primarily defined by widgets
specifically designed to provide layout,
combined with control widgets and their style properties.
For example, the [`Column`][] and [`Row`][] widgets
take an array of children and align them
vertically and horizontally respectively.
A [`Container`][] widget takes a combination of
layout and styling properties, and a
[`Center`][] widget centers its child widgets.
<?code-excerpt "lib/layouts.dart (Column)"?>
```dart
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Container(
color: Colors.red,
width: 100,
height: 100,
),
Container(
color: Colors.blue,
width: 100,
height: 100,
),
Container(
color: Colors.green,
width: 100,
height: 100,
),
],
),
);
```
Flutter provides a variety of layout widgets in its core widget library.
For example, [`Padding`][], [`Align`][], and [`Stack`][].
For a complete list, see [Layout Widgets][].
{% include docs/android-ios-figure-pair.md image="react-native/basic-layout.gif" alt="Layout" class="border" %}
### How do I layer widgets?
In React Native, components can be layered using `absolute` positioning.
Flutter uses the [`Stack`][]
widget to arrange children widgets in layers.
The widgets can entirely or partially overlap the base widget.
The `Stack` widget positions its children relative to the edges of its box.
This class is useful if you simply want to overlap several children widgets.
<?code-excerpt "lib/layouts.dart (Stack)"?>
```dart
@override
Widget build(BuildContext context) {
return Stack(
alignment: const Alignment(0.6, 0.6),
children: <Widget>[
const CircleAvatar(
backgroundImage: NetworkImage(
'https://avatars3.githubusercontent.com/u/14101776?v=4',
),
),
Container(
color: Colors.black45,
child: const Text('Flutter'),
),
],
);
```
The previous example uses `Stack` to overlay a Container
(that displays its `Text` on a translucent black background)
on top of a `CircleAvatar`.
The Stack offsets the text using the alignment property
and `Alignment` coordinates.
{% include docs/android-ios-figure-pair.md image="react-native/stack.png" alt="Stack" class="border" %}
For more information, see the [`Stack`][] class documentation.
## Styling
### How do I style my components?
In React Native, inline styling and `stylesheets.create`
are used to style components.
```js
// React Native
<View style={styles.container}>
<Text style={%raw%}{{ fontSize: 32, color: 'cyan', fontWeight: '600' }}{%endraw%}>
This is a sample text
</Text>
</View>
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});
```
In Flutter, a `Text` widget can take a `TextStyle` class
for its style property. If you want to use the same text
style in multiple places, you can create a
[`TextStyle`][] class and use it for multiple `Text` widgets.
<?code-excerpt "lib/examples.dart (TextStyle)"?>
```dart
const TextStyle textStyle = TextStyle(
color: Colors.cyan,
fontSize: 32,
fontWeight: FontWeight.w600,
);
return const Center(
child: Column(
children: <Widget>[
Text('Sample text', style: textStyle),
Padding(
padding: EdgeInsets.all(20),
child: Icon(
Icons.lightbulb_outline,
size: 48,
color: Colors.redAccent,
),
),
],
),
);
```
{% include docs/android-ios-figure-pair.md image="react-native/flutterstyling.gif" alt="Styling" class="border" %}
### How do I use `Icons` and `Colors`?
React Native doesn't include support for icons
so third party libraries are used.
In Flutter, importing the Material library also pulls in the
rich set of [Material icons][] and [colors][].
<?code-excerpt "lib/examples.dart (Icon)"?>
```dart
return const Icon(Icons.lightbulb_outline, color: Colors.redAccent);
```
When using the `Icons` class,
make sure to set `uses-material-design: true` in
the project's `pubspec.yaml` file.
This ensures that the `MaterialIcons` font,
which displays the icons, is included in your app.
In general, if you intend to use the Material library,
you should include this line.
```yaml
name: my_awesome_application
flutter:
uses-material-design: true
```
Flutter's [Cupertino (iOS-style)][] package provides high
fidelity widgets for the current iOS design language.
To use the `CupertinoIcons` font,
add a dependency for `cupertino_icons` in your project's
`pubspec.yaml` file.
```yaml
name: my_awesome_application
dependencies:
cupertino_icons: ^1.0.6
```
To globally customize the colors and styles of components,
use `ThemeData` to specify default colors
for various aspects of the theme.
Set the theme property in `MaterialApp` to the `ThemeData` object.
The [`Colors`][] class provides colors
from the Material Design [color palette][].
The following example sets the color scheme from seed to `deepPurple`
and the text selection to `red`.
<?code-excerpt "lib/examples.dart (Swatch)"?>
```dart
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sample App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
textSelectionTheme:
const TextSelectionThemeData(selectionColor: Colors.red)),
home: const SampleAppPage(),
);
}
}
```
### How do I add style themes?
In React Native, common themes are defined for
components in stylesheets and then used in components.
In Flutter, create uniform styling for almost everything
by defining the styling in the [`ThemeData`][]
class and passing it to the theme property in the
[`MaterialApp`][] widget.
<?code-excerpt "lib/examples.dart (Theme)"?>
```dart
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primaryColor: Colors.cyan,
brightness: Brightness.dark,
),
home: const StylingPage(),
);
}
```
A `Theme` can be applied even without using the `MaterialApp` widget.
The [`Theme`][] widget takes a `ThemeData` in its `data` parameter
and applies the `ThemeData` to all of its children widgets.
<?code-excerpt "lib/examples.dart (ThemeData)"?>
```dart
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
primaryColor: Colors.cyan,
brightness: brightness,
),
child: Scaffold(
backgroundColor: Theme.of(context).primaryColor,
//...
),
);
}
```
## State management
State is information that can be read synchronously
when a widget is built or information
that might change during the lifetime of a widget.
To manage app state in Flutter,
use a [`StatefulWidget`][] paired with a State object.
For more information on ways to approach managing state in Flutter,
see [State management][].
### The StatelessWidget
A `StatelessWidget` in Flutter is a widget
that doesn't require a state change—
it has no internal state to manage.
Stateless widgets are useful when the part of the user interface
you are describing does not depend on anything other than the
configuration information in the object itself and the
[`BuildContext`][] in which the widget is inflated.
[`AboutDialog`][], [`CircleAvatar`][], and [`Text`][] are examples
of stateless widgets that subclass [`StatelessWidget`][].
<?code-excerpt "lib/stateless.dart"?>
```dart
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,
),
);
}
}
```
The previous example uses the constructor of the `MyStatelessWidget`
class to pass the `text`, which is marked as `final`.
This class extends `StatelessWidget`—it contains immutable data.
The `build` method of a stateless widget is typically called
in only three situations:
* When the widget is inserted into a tree
* When the widget's parent changes its configuration
* When an [`InheritedWidget`][] it depends on, changes
### The StatefulWidget
A [`StatefulWidget`][] is a widget that changes state.
Use the `setState` method to manage the
state changes for a `StatefulWidget`.
A call to `setState()` tells the Flutter
framework that something has changed in a state,
which causes an app to rerun the `build()` method
so that the app can reflect the change.
_State_ is information that can be read synchronously when a widget
is built and might change during the lifetime of the widget.
It's the responsibility of the widget implementer to ensure that
the state object is promptly notified when the state changes.
Use `StatefulWidget` when a widget can change dynamically.
For example, the state of the widget changes by typing into a form,
or moving a slider.
Or, it can change over time—perhaps a data feed updates the UI.
[`Checkbox`][], [`Radio`][], [`Slider`][], [`InkWell`][],
[`Form`][], and [`TextField`][]
are examples of stateful widgets that subclass
[`StatefulWidget`][].
The following example declares a `StatefulWidget`
that requires a `createState()` method.
This method creates the state object that manages the widget's state,
`_MyStatefulWidgetState`.
<?code-excerpt "lib/stateful.dart (StatefulWidget)"?>
```dart
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({
super.key,
required this.title,
});
final String title;
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
```
The following state class, `_MyStatefulWidgetState`,
implements the `build()` method for the widget.
When the state changes, for example, when the user toggles
the button, `setState()` is called with the new toggle value.
This causes the framework to rebuild this widget in the UI.
<?code-excerpt "lib/stateful.dart (StatefulWidgetState)"?>
```dart
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool showText = true;
bool toggleState = true;
Timer? t2;
void toggleBlinkState() {
setState(() {
toggleState = !toggleState;
});
if (!toggleState) {
t2 = Timer.periodic(const Duration(milliseconds: 1000), (t) {
toggleShowText();
});
} else {
t2?.cancel();
}
}
void toggleShowText() {
setState(() {
showText = !showText;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
if (showText)
const Text(
'This execution will be done before you can blink.',
),
Padding(
padding: const EdgeInsets.only(top: 70),
child: ElevatedButton(
onPressed: toggleBlinkState,
child: toggleState
? const Text('Blink')
: const Text('Stop Blinking'),
),
),
],
),
),
);
}
}
```
### What are the StatefulWidget and StatelessWidget best practices?
Here are a few things to consider when designing your widget.
1. Determine whether a widget should be
a `StatefulWidget` or a `StatelessWidget`.
In Flutter, widgets are either Stateful or Stateless—depending on whether
they depend on a state change.
* If a widget changes—the user interacts with it or
a data feed interrupts the UI, then it's *Stateful*.
* If a widget is final or immutable, then it's *Stateless*.
2. Determine which object manages the widget's state (for a `StatefulWidget`).
In Flutter, there are three primary ways to manage state:
* The widget manages its own state
* The parent widget manages the widget's state
* A mix-and-match approach
When deciding which approach to use, consider the following principles:
* If the state in question is user data,
for example the checked or unchecked mode of a checkbox,
or the position of a slider, then the state is best managed
by the parent widget.
* If the state in question is aesthetic, for example an animation,
then the widget itself best manages the state.
* When in doubt, let the parent widget manage the child widget's state.
3. Subclass StatefulWidget and State.
The `MyStatefulWidget` class manages its own state—it extends
`StatefulWidget`, it overrides the `createState()`
method to create the `State` object,
and the framework calls `createState()` to build the widget.
In this example, `createState()` creates an instance of
`_MyStatefulWidgetState`, which
is implemented in the next best practice.
<?code-excerpt "lib/best_practices.dart (CreateState)" replace="/return const Text\('Hello World!'\);/\/\/.../g"?>
```dart
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({
super.key,
required this.title,
});
final String title;
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
//...
}
}
```
4. Add the StatefulWidget into the widget tree.
Add your custom `StatefulWidget` to the widget tree
in the app's build method.
<?code-excerpt "lib/best_practices.dart (UseStatefulWidget)"?>
```dart
class MyStatelessWidget extends StatelessWidget {
// This widget is the root of your application.
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyStatefulWidget(title: 'State Change Demo'),
);
}
}
```
{% include docs/android-ios-figure-pair.md image="react-native/state-change.gif" alt="State change" class="border" %}
## Props
In React Native, most components can be customized when they are
created with different parameters or properties, called `props`.
These parameters can be used in a child component using `this.props`.
```js
// React Native
const CustomCard = ({ index, onPress }) => {
return (
<View>
<Text> Card {index} </Text>
<Button
title='Press'
onPress={() => onPress(index)}
/>
</View>
);
};
const App = () => {
const onPress = (index) => {
console.log('Card ', index);
};
return (
<View>
<FlatList
data={[ /* ... */ ]}
renderItem={({ item }) => (
<CustomCard onPress={onPress} index={item.key} />
)}
/>
</View>
);
};
```
In Flutter, you assign a local variable or function marked
`final` with the property received in the parameterized constructor.
<?code-excerpt "lib/components.dart (Components)"?>
```dart
/// Flutter
class CustomCard extends StatelessWidget {
const CustomCard({
super.key,
required this.index,
required this.onPress,
});
final int index;
final void Function() onPress;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: <Widget>[
Text('Card $index'),
TextButton(
onPressed: onPress,
child: const Text('Press'),
),
],
),
);
}
}
class UseCard extends StatelessWidget {
const UseCard({super.key, required this.index});
final int index;
@override
Widget build(BuildContext context) {
/// Usage
return CustomCard(
index: index,
onPress: () {
print('Card $index');
},
);
}
}
```
{% include docs/android-ios-figure-pair.md image="react-native/modular.png" alt="Cards" class="border" %}
## Local storage
If you don't need to store a lot of data, and it doesn't require
structure, you can use `shared_preferences` which allows you to
read and write persistent key-value pairs of primitive data
types: booleans, floats, ints, longs, and strings.
### How do I store persistent key-value pairs that are global to the app?
In React Native, you use the `setItem` and `getItem` functions
of the `AsyncStorage` component to store and retrieve data
that is persistent and global to the app.
```js
// React Native
const [counter, setCounter] = useState(0)
...
await AsyncStorage.setItem( 'counterkey', json.stringify(++this.state.counter));
AsyncStorage.getItem('counterkey').then(value => {
if (value != null) {
setCounter(value);
}
});
```
In Flutter, use the [`shared_preferences`][] plugin to
store and retrieve key-value data that is persistent and global
to the app. The `shared_preferences` plugin wraps
`NSUserDefaults` on iOS and `SharedPreferences` on Android,
providing a persistent store for simple data.
To add the `shared_preferences` package as a dependency, run `flutter pub add`:
```terminal
$ flutter pub add shared_preferences
```
<?code-excerpt "lib/examples.dart (SharedPrefs)"?>
```dart
import 'package:shared_preferences/shared_preferences.dart';
```
To implement persistent data, use the setter methods
provided by the `SharedPreferences` class.
Setter methods are available for various primitive
types, such as `setInt`, `setBool`, and `setString`.
To read data, use the appropriate getter method provided
by the `SharedPreferences` class. For each
setter there is a corresponding getter method,
for example, `getInt`, `getBool`, and `getString`.
<?code-excerpt "lib/examples.dart (SharedPrefsUpdate)"?>
```dart
Future<void> updateCounter() async {
final prefs = await SharedPreferences.getInstance();
int? counter = prefs.getInt('counter');
if (counter is int) {
await prefs.setInt('counter', ++counter);
}
setState(() {
_counter = counter;
});
}
```
## Routing
Most apps contain several screens for displaying different
types of information. For example, you might have a product
screen that displays images where users could tap on a product
image to get more information about the product on a new screen.
In Android, new screens are new Activities.
In iOS, new screens are new ViewControllers. In Flutter,
screens are just Widgets! And to navigate to new
screens in Flutter, use the Navigator widget.
### How do I navigate between screens?
In React Native, there are three main navigators:
StackNavigator, TabNavigator, and DrawerNavigator.
Each provides a way to configure and define the screens.
```js
// React Native
const MyApp = TabNavigator(
{ Home: { screen: HomeScreen }, Notifications: { screen: tabNavScreen } },
{ tabBarOptions: { activeTintColor: '#e91e63' } }
);
const SimpleApp = StackNavigator({
Home: { screen: MyApp },
stackScreen: { screen: StackScreen }
});
export default (MyApp1 = DrawerNavigator({
Home: {
screen: SimpleApp
},
Screen2: {
screen: drawerScreen
}
}));
```
In Flutter, there are two main widgets used to navigate between screens:
* A [`Route`][] is an abstraction for an app screen or page.
* A [`Navigator`][] is a widget that manages routes.
A `Navigator` is defined as a widget that manages a set of child
widgets with a stack discipline. The navigator manages a stack
of `Route` objects and provides methods for managing the stack,
like [`Navigator.push`][] and [`Navigator.pop`][].
A list of routes might be specified in the [`MaterialApp`][] widget,
or they might be built on the fly, for example, in hero animations.
The following example specifies named routes in the `MaterialApp` widget.
{{site.alert.note}}
Named routes are no longer recommended for most
applications. For more information, see
[Limitations][] in the [navigation overview][] page.
{{site.alert.end}}
[Limitations]: /ui/navigation#limitations
[navigation overview]: /ui/navigation
<?code-excerpt "lib/navigation.dart (Navigator)"?>
```dart
class NavigationApp extends StatelessWidget {
// This widget is the root of your application.
const NavigationApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
//...
routes: <String, WidgetBuilder>{
'/a': (context) => const UsualNavScreen(),
'/b': (context) => const DrawerNavScreen(),
},
//...
);
}
}
```
To navigate to a named route, the [`Navigator.of()`][]
method is used to specify the `BuildContext`
(a handle to the location of a widget in the widget tree).
The name of the route is passed to the `pushNamed` function to
navigate to the specified route.
<?code-excerpt "lib/navigation.dart (PushNamed)"?>
```dart
Navigator.of(context).pushNamed('/a');
```
You can also use the push method of `Navigator` which
adds the given [`Route`][] to the history of the
navigator that most tightly encloses the given [`BuildContext`][],
and transitions to it. In the following example,
the [`MaterialPageRoute`][] widget is a modal route that
replaces the entire screen with a platform-adaptive
transition. It takes a [`WidgetBuilder`][] as a required parameter.
<?code-excerpt "lib/navigation.dart (NavigatorPush)"?>
```dart
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const UsualNavScreen(),
),
);
```
### How do I use tab navigation and drawer navigation?
In Material Design apps, there are two primary options
for Flutter navigation: tabs and drawers.
When there is insufficient space to support tabs, drawers
provide a good alternative.
#### Tab navigation
In React Native, `createBottomTabNavigator`
and `TabNavigation` are used to
show tabs and for tab navigation.
```js
// React Native
import { createBottomTabNavigator } from 'react-navigation';
const MyApp = TabNavigator(
{ Home: { screen: HomeScreen }, Notifications: { screen: tabNavScreen } },
{ tabBarOptions: { activeTintColor: '#e91e63' } }
);
```
Flutter provides several specialized widgets for drawer and
tab navigation:
[`TabController`][]
: Coordinates the tab selection between a `TabBar`
and a `TabBarView`.
[`TabBar`][]
: Displays a horizontal row of tabs.
[`Tab`][]
: Creates a material design TabBar tab.
[`TabBarView`][]
: Displays the widget that corresponds to the currently selected tab.
<?code-excerpt "lib/navigation.dart (TabNav)"?>
```dart
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
late TabController controller = TabController(length: 2, vsync: this);
@override
Widget build(BuildContext context) {
return TabBar(
controller: controller,
tabs: const <Tab>[
Tab(icon: Icon(Icons.person)),
Tab(icon: Icon(Icons.email)),
],
);
}
}
```
A `TabController` is required to coordinate the tab selection
between a `TabBar` and a `TabBarView`.
The `TabController` constructor `length` argument is the total
number of tabs. A `TickerProvider` is required to trigger
the notification whenever a frame triggers a state change.
The `TickerProvider` is `vsync`. Pass the
`vsync: this` argument to the `TabController` constructor
whenever you create a new `TabController`.
The [`TickerProvider`][] is an interface implemented
by classes that can vend [`Ticker`][] objects.
Tickers can be used by any object that must be notified whenever a
frame triggers, but they're most commonly used indirectly via an
[`AnimationController`][]. `AnimationController`s
need a `TickerProvider` to obtain their `Ticker`.
If you are creating an AnimationController from a State,
then you can use the [`TickerProviderStateMixin`][]
or [`SingleTickerProviderStateMixin`][]
classes to obtain a suitable `TickerProvider`.
The [`Scaffold`][] widget wraps a new `TabBar` widget and
creates two tabs. The `TabBarView` widget
is passed as the `body` parameter of the `Scaffold` widget.
All screens corresponding to the `TabBar` widget's tabs are
children to the `TabBarView` widget along with the same `TabController`.
<?code-excerpt "lib/navigation.dart (NavigationHomePageState)"?>
```dart
class _NavigationHomePageState extends State<NavigationHomePage>
with SingleTickerProviderStateMixin {
late TabController controller = TabController(length: 2, vsync: this);
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: Material(
color: Colors.blue,
child: TabBar(
tabs: const <Tab>[
Tab(
icon: Icon(Icons.person),
),
Tab(
icon: Icon(Icons.email),
),
],
controller: controller,
),
),
body: TabBarView(
controller: controller,
children: const <Widget>[HomeScreen(), TabScreen()],
));
}
}
```
#### Drawer navigation
In React Native, import the needed react-navigation packages and then use
`createDrawerNavigator` and `DrawerNavigation`.
```js
// React Native
export default (MyApp1 = DrawerNavigator({
Home: {
screen: SimpleApp
},
Screen2: {
screen: drawerScreen
}
}));
```
In Flutter, we can use the `Drawer` widget in combination with a
`Scaffold` to create a layout with a Material Design drawer.
To add a `Drawer` to an app, wrap it in a `Scaffold` widget.
The `Scaffold` widget provides a consistent
visual structure to apps that follow the
[Material Design][] guidelines. It also supports
special Material Design components,
such as `Drawers`, `AppBars`, and `SnackBars`.
The `Drawer` widget is a Material Design panel that slides
in horizontally from the edge of a `Scaffold` to show navigation
links in an application. You can
provide a [`ElevatedButton`][], a [`Text`][] widget,
or a list of items to display as the child to the `Drawer` widget.
In the following example, the [`ListTile`][]
widget provides the navigation on tap.
<?code-excerpt "lib/examples.dart (Drawer)"?>
```dart
@override
Widget build(BuildContext context) {
return Drawer(
elevation: 20,
child: ListTile(
leading: const Icon(Icons.change_history),
title: const Text('Screen2'),
onTap: () {
Navigator.of(context).pushNamed('/b');
},
),
);
}
```
The `Scaffold` widget also includes an `AppBar` widget that automatically
displays an appropriate IconButton to show the `Drawer` when a Drawer is
available in the `Scaffold`. The `Scaffold` automatically handles the
edge-swipe gesture to show the `Drawer`.
<?code-excerpt "lib/examples.dart (Scaffold)"?>
```dart
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
elevation: 20,
child: ListTile(
leading: const Icon(Icons.change_history),
title: const Text('Screen2'),
onTap: () {
Navigator.of(context).pushNamed('/b');
},
),
),
appBar: AppBar(title: const Text('Home')),
body: Container(),
);
}
```
{% include docs/android-ios-figure-pair.md image="react-native/navigation.gif" alt="Navigation" class="border" %}
## Gesture detection and touch event handling
To listen for and respond to gestures,
Flutter supports taps, drags, and scaling.
The gesture system in Flutter has two separate layers.
The first layer includes raw pointer events,
which describe the location and movement of pointers,
(such as touches, mice, and styli movements), across the screen.
The second layer includes gestures,
which describe semantic actions
that consist of one or more pointer movements.
### How do I add a click or press listeners to a widget?
In React Native, listeners are added to components
using `PanResponder` or the `Touchable` components.
```js
// React Native
<TouchableOpacity
onPress={() => {
console.log('Press');
}}
onLongPress={() => {
console.log('Long Press');
}}
>
<Text>Tap or Long Press</Text>
</TouchableOpacity>
```
For more complex gestures and combining several touches into
a single gesture, [`PanResponder`][] is used.
```js
// React Native
const App = () => {
const panResponderRef = useRef(null);
useEffect(() => {
panResponderRef.current = PanResponder.create({
onMoveShouldSetPanResponder: (event, gestureState) =>
!!getDirection(gestureState),
onPanResponderMove: (event, gestureState) => true,
onPanResponderRelease: (event, gestureState) => {
const drag = getDirection(gestureState);
},
onPanResponderTerminationRequest: (event, gestureState) => true
});
}, []);
return (
<View style={styles.container} {...panResponderRef.current.panHandlers}>
<View style={styles.center}>
<Text>Swipe Horizontally or Vertically</Text>
</View>
</View>
);
};
```
In Flutter, to add a click (or press) listener to a widget,
use a button or a touchable widget that has an `onPress: field`.
Or, add gesture detection to any widget by wrapping it
in a [`GestureDetector`][].
<?code-excerpt "lib/examples.dart (GestureDetector)"?>
```dart
@override
Widget build(BuildContext context) {
return GestureDetector(
child: Scaffold(
appBar: AppBar(title: const Text('Gestures')),
body: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Tap, Long Press, Swipe Horizontally or Vertically'),
],
)),
),
onTap: () {
print('Tapped');
},
onLongPress: () {
print('Long Pressed');
},
onVerticalDragEnd: (value) {
print('Swiped Vertically');
},
onHorizontalDragEnd: (value) {
print('Swiped Horizontally');
},
);
}
```
For more information, including a list of
Flutter `GestureDetector` callbacks,
see the [GestureDetector class][].
[GestureDetector class]: {{site.api}}/flutter/widgets/GestureDetector-class.html#instance-properties
{% include docs/android-ios-figure-pair.md image="react-native/flutter-gestures.gif" alt="Gestures" class="border" %}
## Making HTTP network requests
Fetching data from the internet is common for most apps. And in Flutter,
the `http` package provides the simplest way to fetch data from the internet.
### How do I fetch data from API calls?
React Native provides the Fetch API for networking—you make a fetch request
and then receive the response to get the data.
```js
// React Native
const [ipAddress, setIpAddress] = useState('')
const _getIPAddress = () => {
fetch('https://httpbin.org/ip')
.then(response => response.json())
.then(responseJson => {
setIpAddress(responseJson.origin);
})
.catch(error => {
console.error(error);
});
};
```
Flutter uses the `http` package.
To add the `http` package as a dependency, run `flutter pub add`:
```terminal
$ flutter pub add http
```
Flutter uses the [`dart:io`][] core HTTP support client.
To create an HTTP Client, import `dart:io`.
<?code-excerpt "lib/examples.dart (ImportDartIO)"?>
```dart
import 'dart:io';
```
The client supports the following HTTP operations:
GET, POST, PUT, and DELETE.
<?code-excerpt "lib/examples.dart (HTTP)"?>
```dart
final url = Uri.parse('https://httpbin.org/ip');
final httpClient = HttpClient();
Future<void> getIPAddress() async {
final request = await httpClient.getUrl(url);
final response = await request.close();
final responseBody = await response.transform(utf8.decoder).join();
final ip = jsonDecode(responseBody)['origin'] as String;
setState(() {
_ipAddress = ip;
});
}
```
{% include docs/android-ios-figure-pair.md image="react-native/api-calls.gif" alt="API calls" class="border" %}
## Form input
Text fields allow users to type text into your app so they can be
used to build forms, messaging apps, search experiences, and more.
Flutter provides two core text field widgets:
[`TextField`][] and [`TextFormField`][].
### How do I use text field widgets?
In React Native, to enter text you use a `TextInput` component to show a text
input box and then use the callback to store the value in a variable.
```js
// React Native
const [password, setPassword] = useState('')
...
<TextInput
placeholder="Enter your Password"
onChangeText={password => setPassword(password)}
/>
<Button title="Submit" onPress={this.validate} />
```
In Flutter, use the [`TextEditingController`][]
class to manage a `TextField` widget.
Whenever the text field is modified,
the controller notifies its listeners.
Listeners read the text and selection properties to
learn what the user typed into the field.
You can access the text in `TextField`
by the `text` property of the controller.
<?code-excerpt "lib/examples.dart (TextEditingController)"?>
```dart
final TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Column(children: [
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Type something',
labelText: 'Text Field',
),
),
ElevatedButton(
child: const Text('Submit'),
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Alert'),
content: Text('You typed ${_controller.text}'),
);
});
},
),
]);
}
```
In this example, when a user clicks on the submit button an alert dialog
displays the current text entered in the text field.
This is achieved using an [`AlertDialog`][]
widget that displays the alert message, and the text from
the `TextField` is accessed by the `text` property of the
[`TextEditingController`][].
### How do I use Form widgets?
In Flutter, use the [`Form`][] widget where
[`TextFormField`][] widgets along with the submit
button are passed as children.
The `TextFormField` widget has a parameter called
[`onSaved`][] that takes a callback and executes
when the form is saved. A `FormState`
object is used to save, reset, or validate
each `FormField` that is a descendant of this `Form`.
To obtain the `FormState`, you can use `Form.of()`
with a context whose ancestor is the `Form`,
or pass a `GlobalKey` to the `Form` constructor and call
`GlobalKey.currentState()`.
<?code-excerpt "lib/examples.dart (FormState)"?>
```dart
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Column(
children: <Widget>[
TextFormField(
validator: (value) {
if (value != null && value.contains('@')) {
return null;
}
return 'Not a valid email.';
},
onSaved: (val) {
_email = val;
},
decoration: const InputDecoration(
hintText: 'Enter your email',
labelText: 'Email',
),
),
ElevatedButton(
onPressed: _submit,
child: const Text('Login'),
),
],
),
);
}
```
The following example shows how `Form.save()` and `formKey`
(which is a `GlobalKey`), are used to save the form on submit.
<?code-excerpt "lib/examples.dart (FormSubmit)"?>
```dart
void _submit() {
final form = formKey.currentState;
if (form != null && form.validate()) {
form.save();
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Alert'),
content: Text('Email: $_email, password: $_password'));
},
);
}
}
```
{% include docs/android-ios-figure-pair.md image="react-native/input-fields.gif" alt="Input" class="border" %}
## Platform-specific code
When building a cross-platform app, you want to re-use as much code as
possible across platforms. However, scenarios might arise where it
makes sense for the code to be different depending on the OS.
This requires a separate implementation by declaring a specific platform.
In React Native, the following implementation would be used:
```js
// React Native
if (Platform.OS === 'ios') {
return 'iOS';
} else if (Platform.OS === 'android') {
return 'android';
} else {
return 'not recognised';
}
```
In Flutter, use the following implementation:
<?code-excerpt "lib/examples.dart (Platform)"?>
```dart
final platform = Theme.of(context).platform;
if (platform == TargetPlatform.iOS) {
return 'iOS';
}
if (platform == TargetPlatform.android) {
return 'android';
}
if (platform == TargetPlatform.fuchsia) {
return 'fuchsia';
}
return 'not recognized ';
```
## 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.
If you're using an IDE,
you can debug your application using the IDE's debugger.
### How do I perform a hot reload?
Flutter's Stateful Hot Reload feature helps you quickly and easily experiment,
build UIs, add features, and fix bugs. Instead of recompiling your app
every time you make a change, you can hot reload your app instantly.
The app is updated to reflect your change,
and the current state of the app is preserved.
In React Native,
the shortcut is ⌘R for the iOS Simulator and tapping R twice on
Android emulators.
In Flutter, If you are using IntelliJ IDE or Android Studio,
you can select Save All (⌘s/ctrl-s), or you can click the
Hot Reload button on the toolbar. If you
are running the app at the command line using `flutter run`,
type `r` in the Terminal window.
You can also perform a full restart by typing `R` in the
Terminal window.
### How do I access the in-app developer menu?
In React Native, the developer menu can be accessed by shaking your device: ⌘D
for the iOS Simulator or ⌘M for Android emulator.
In Flutter, if you are using an IDE, you can use the IDE tools. If you start
your application using `flutter run` you can also access the menu by typing `h`
in the terminal window, or type the following shortcuts:
<div class="table-wrapper" markdown="1">
| Action| Terminal Shortcut| Debug functions and properties|
| :------- | :------: | :------ |
| Widget hierarchy of the app| `w`| debugDumpApp()|
| Rendering tree of the app | `t`| debugDumpRenderTree()|
| Layers| `L`| debugDumpLayerTree()|
| Accessibility | `S` (traversal order) or<br>`U` (inverse hit test order)|debugDumpSemantics()|
| To toggle the widget inspector | `i` | WidgetsApp. showWidgetInspectorOverride|
| To toggle the display of construction lines| `p` | debugPaintSizeEnabled|
| To simulate different operating systems| `o` | defaultTargetPlatform|
| To display the performance overlay | `P` | WidgetsApp. showPerformanceOverlay|
| To save a screenshot to flutter. png| `s` ||
| To quit| `q` ||
{:.table.table-striped}
</div>
## Animation
Well-designed animation makes a UI feel intuitive,
contributes to the look and feel of a polished app,
and improves the user experience.
Flutter's animation support makes it easy
to implement simple and complex animations.
The Flutter SDK includes many Material Design widgets
that include standard motion effects,
and you can easily customize these effects
to personalize your app.
In React Native, Animated APIs are used to create animations.
In Flutter, use the [`Animation`][]
class and the [`AnimationController`][] class.
`Animation` is an abstract class that understands its
current value and its state (completed or dismissed).
The `AnimationController` class lets you
play an animation forward or in reverse,
or stop animation and set the animation
to a specific value to customize the motion.
### How do I add a simple fade-in animation?
In the React Native example below, an animated component,
`FadeInView` is created using the Animated API.
The initial opacity state, final state, and the
duration over which the transition occurs are defined.
The animation component is added inside the `Animated` component,
the opacity state `fadeAnim` is mapped
to the opacity of the `Text` component that we want to animate,
and then, `start()` is called to start the animation.
```js
// React Native
const FadeInView = ({ style, children }) => {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 10000
}).start();
}, []);
return (
<Animated.View style={%raw%}{{ ...style, opacity: fadeAnim }}{%endraw%}>
{children}
</Animated.View>
);
};
...
<FadeInView>
<Text> Fading in </Text>
</FadeInView>
...
```
To create the same animation in Flutter, create an
[`AnimationController`][] object named `controller`
and specify the duration. By default, an `AnimationController`
linearly produces values that range from 0.0 to 1.0,
during a given duration. The animation controller generates a new value
whenever the device running your app is ready to display a new frame.
Typically, this rate is around 60 values per second.
When defining an `AnimationController`,
you must pass in a `vsync` object.
The presence of `vsync` prevents offscreen
animations from consuming unnecessary resources.
You can use your stateful object as the `vsync` by adding
`TickerProviderStateMixin` to the class definition.
An `AnimationController` needs a TickerProvider,
which is configured using the `vsync` argument on the constructor.
A [`Tween`][] describes the interpolation between a
beginning and ending value or the mapping from an input
range to an output range. To use a `Tween` object
with an animation, call the `Tween` object's `animate()`
method and pass it the `Animation` object that you want to modify.
For this example, a [`FadeTransition`][]
widget is used and the `opacity` property is
mapped to the `animation` object.
To start the animation, use `controller.forward()`.
Other operations can also be performed using the
controller such as `fling()` or `repeat()`.
For this example, the [`FlutterLogo`][]
widget is used inside the `FadeTransition` widget.
<?code-excerpt "lib/animation.dart"?>
```dart
import 'package:flutter/material.dart';
void main() {
runApp(const Center(child: LogoFade()));
}
class LogoFade extends StatefulWidget {
const LogoFade({super.key});
@override
State<LogoFade> createState() => _LogoFadeState();
}
class _LogoFadeState extends State<LogoFade>
with SingleTickerProviderStateMixin {
late Animation<double> animation;
late AnimationController controller;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 3000),
vsync: this,
);
final CurvedAnimation curve = CurvedAnimation(
parent: controller,
curve: Curves.easeIn,
);
animation = Tween(begin: 0.0, end: 1.0).animate(curve);
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: animation,
child: const SizedBox(
height: 300,
width: 300,
child: FlutterLogo(),
),
);
}
}
```
{% include docs/android-ios-figure-pair.md image="react-native/flutter-fade.gif" alt="Flutter fade" class="border" %}
### How do I add swipe animation to cards?
In React Native, either the `PanResponder` or
third-party libraries are used for swipe animation.
In Flutter, to add a swipe animation, use the
[`Dismissible`][] widget and nest the child widgets.
<?code-excerpt "lib/examples.dart (Dismissable)"?>
```dart
return Dismissible(
key: Key(widget.key.toString()),
onDismissed: (dismissDirection) {
cards.removeLast();
},
child: Container(
//...
),
);
```
{% include docs/android-ios-figure-pair.md image="react-native/card-swipe.gif" alt="Card swipe" class="border" %}
## React Native and Flutter widget equivalent components
The following table lists commonly-used React Native
components mapped to the corresponding Flutter widget
and common widget properties.
<div class="table-wrapper" markdown="1">
| React Native Component | Flutter Widget | Description |
| ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| [`Button`](https://facebook.github.io/react-native/docs/button.html) | [`ElevatedButton`][] | A basic raised button. |
| | onPressed [required] | The callback when the button is tapped or otherwise activated. |
| | Child | The button's label. |
| | | |
| [`Button`](https://facebook.github.io/react-native/docs/button.html) | [`TextButton`][] | A basic flat button. |
| | onPressed [required] | The callback when the button is tapped or otherwise activated. |
| | Child | The button's label. |
| | | |
| [`ScrollView`](https://facebook.github.io/react-native/docs/scrollview.html) | [`ListView`][] | A scrollable list of widgets arranged linearly.|
|| children | ( <Widget\> [ ]) List of child widgets to display.
||controller |[ [`ScrollController`][] ] An object that can be used to control a scrollable widget.
||itemExtent|[ double ] If non-null, forces the children to have the given extent in the scroll direction.
||scroll Direction|[ [`Axis`][] ] The axis along which the scroll view scrolls.
|| | |
| [`FlatList`](https://facebook.github.io/react-native/docs/flatlist.html) | [`ListView.builder`][] | The constructor for a linear array of widgets that are created on demand.
||itemBuilder [required] |[[`IndexedWidgetBuilder`][]] helps in building the children on demand. This callback is called only with indices greater than or equal to zero and less than the itemCount.
||itemCount |[ int ] improves the ability of the `ListView` to estimate the maximum scroll extent.
| | | |
| [`Image`](https://facebook.github.io/react-native/docs/image.html) | [`Image`][] | A widget that displays an image. |
| | image [required] | The image to display. |
| | Image. asset | Several constructors are provided for the various ways that an image can be specified. |
| | width, height, color, alignment | The style and layout for the image. |
| | fit | Inscribing the image into the space allocated during layout. |
| | | |
| [`Modal`](https://facebook.github.io/react-native/docs/modal.html) | [`ModalRoute`][] | A route that blocks interaction with previous routes. |
| | animation | The animation that drives the route's transition and the previous route's forward transition. |
| | | |
| [`ActivityIndicator`](https://facebook.github.io/react-native/docs/activityindicator.html) | [`CircularProgressIndicator`][] | A widget that shows progress along a circle. |
| | strokeWidth | The width of the line used to draw the circle. |
| | backgroundColor | The progress indicator's background color. The current theme's `ThemeData.backgroundColor` by default. |
| | | |
| [`ActivityIndicator`](https://facebook.github.io/react-native/docs/activityindicator.html) | [`LinearProgressIndicator`][] | A widget that shows progress along a line. |
| | value | The value of this progress indicator. |
| | | |
| [`RefreshControl`](https://facebook.github.io/react-native/docs/refreshcontrol.html) | [`RefreshIndicator`][] | A widget that supports the Material "swipe to refresh" idiom. |
| | color | The progress indicator's foreground color. |
| | onRefresh | A function that's called when a user drags the refresh indicator far enough to demonstrate that they want the app to refresh. |
| | | |
| [`View`](https://facebook.github.io/react-native/docs/view.html) | [`Container`][] | A widget that surrounds a child widget. |
| | | |
| [`View`](https://facebook.github.io/react-native/docs/view.html) | [`Column`][] | A widget that displays its children in a vertical array. |
| | | |
| [`View`](https://facebook.github.io/react-native/docs/view.html) | [`Row`][] | A widget that displays its children in a horizontal array. |
| | | |
| [`View`](https://facebook.github.io/react-native/docs/view.html) | [`Center`][] | A widget that centers its child within itself. |
| | | |
| [`View`](https://facebook.github.io/react-native/docs/view.html) | [`Padding`][] | A widget that insets its child by the given padding. |
| | padding [required] | [ EdgeInsets ] The amount of space to inset the child.
|||
| [`TouchableOpacity`](https://facebook.github.io/react-native/docs/touchableopacity.html) | [`GestureDetector`][] | A widget that detects gestures. |
| | onTap | A callback when a tap occurs. |
| | onDoubleTap | A callback when a tap occurs at the same location twice in quick succession.
|||
| [`TextInput`](https://facebook.github.io/react-native/docs/textinput.html) | [`TextInput`][] | The interface to the system's text input control. |
| | controller | [ [`TextEditingController`][] ] used to access and modify text.
|||
| [`Text`](https://facebook.github.io/react-native/docs/text.html) | [`Text`][] | The Text widget that displays a string of text with a single style. |
| | data | [ String ] The text to display. |
| | textDirection | [ [`TextAlign`][] ] The direction in which the text flows. |
| | | |
| [`Switch`](https://facebook.github.io/react-native/docs/switch.html) | [`Switch`][] | A material design switch. |
| | value [required] | [ boolean ] Whether this switch is on or off. |
| | onChanged [required] | [ callback ] Called when the user toggles the switch on or off. |
| | | |
| [`Slider`](https://facebook.github.io/react-native/docs/slider.html) | [`Slider`][] | Used to select from a range of values. |
| | value [required] | [ double ] The current value of the slider. |
| | onChanged [required] | Called when the user selects a new value for the slider. |
{:.table.table-striped}
</div>
[`AboutDialog`]: {{site.api}}/flutter/material/AboutDialog-class.html
[Adding Assets and Images in Flutter]: /ui/assets/assets-and-images
[`AlertDialog`]: {{site.api}}/flutter/material/AlertDialog-class.html
[`Align`]: {{site.api}}/flutter/widgets/Align-class.html
[`Animation`]: {{site.api}}/flutter/animation/Animation-class.html
[`AnimationController`]: {{site.api}}/flutter/animation/AnimationController-class.html
[async and await]: {{site.dart-site}}/language/async
[`Axis`]: {{site.api}}/flutter/painting/Axis.html
[`BuildContext`]: {{site.api}}/flutter/widgets/BuildContext-class.html
[`Center`]: {{site.api}}/flutter/widgets/Center-class.html
[color palette]: {{site.material2}}/design/color/the-color-system.html#color-theme-creation
[colors]: {{site.api}}/flutter/material/Colors-class.html
[`Colors`]: {{site.api}}/flutter/material/Colors-class.html
[`Column`]: {{site.api}}/flutter/widgets/Column-class.html
[`Container`]: {{site.api}}/flutter/widgets/Container-class.html
[`Checkbox`]: {{site.api}}/flutter/material/Checkbox-class.html
[`CircleAvatar`]: {{site.api}}/flutter/material/CircleAvatar-class.html
[`CircularProgressIndicator`]: {{site.api}}/flutter/material/CircularProgressIndicator-class.html
[Cupertino (iOS-style)]: /ui/widgets/cupertino
[`CustomPaint`]: {{site.api}}/flutter/widgets/CustomPaint-class.html
[`CustomPainter`]: {{site.api}}/flutter/rendering/CustomPainter-class.html
[Dart]: {{site.dart-site}}/dart-2
[Dart's Type System]: {{site.dart-site}}/guides/language/sound-dart
[Sound Null Safety]: {{site.dart-site}}/null-safety
[`dart:io`]: {{site.api}}/flutter/dart-io/dart-io-library.html
[DartPadA]: {{site.dartpad}}/?id=0df636e00f348bdec2bc1c8ebc7daeb1
[DartPadB]: {{site.dartpad}}/?id=cf9e652f77636224d3e37d96dcf238e5
[DartPadC]: {{site.dartpad}}/?id=3f4625c16e05eec396d6046883739612
[DartPadD]: {{site.dartpad}}/?id=57ec21faa8b6fe2326ffd74e9781a2c7
[DartPadE]: {{site.dartpad}}/?id=c85038ad677963cb6dc943eb1a0b72e6
[DartPadF]: {{site.dartpad}}/?id=5454e8bfadf3000179d19b9bc6be9918
[Developing Packages & Plugins]: /packages-and-plugins/developing-packages
[DevTools]: /tools/devtools
[`Dismissible`]: {{site.api}}/flutter/widgets/Dismissible-class.html
[`FadeTransition`]: {{site.api}}/flutter/widgets/FadeTransition-class.html
[Flutter packages]: {{site.pub}}/flutter/
[Flutter Architectural Overview]: /resources/architectural-overview
[Flutter Basic Widgets]: /ui/widgets/basics
[Flutter Technical Overview]: /resources/architectural-overview
[Flutter Widget Catalog]: /ui/widgets
[Flutter Widget Index]: /reference/widgets
[`FlutterLogo`]: {{site.api}}/flutter/material/FlutterLogo-class.html
[`Form`]: {{site.api}}/flutter/widgets/Form-class.html
[`TextButton`]: {{site.api}}/flutter/material/TextButton-class.html
[functions]: {{site.dart-site}}/language/functions
[`Future`]: {{site.dart-site}}/tutorials/language/futures
[`GestureDetector`]: {{site.api}}/flutter/widgets/GestureDetector-class.html
[Getting started]: /get-started
[`Image`]: {{site.api}}/flutter/widgets/Image-class.html
[`IndexedWidgetBuilder`]: {{site.api}}/flutter/widgets/IndexedWidgetBuilder.html
[`InheritedWidget`]: {{site.api}}/flutter/widgets/InheritedWidget-class.html
[`InkWell`]: {{site.api}}/flutter/material/InkWell-class.html
[Layout Widgets]: /ui/widgets/layout
[`LinearProgressIndicator`]: {{site.api}}/flutter/material/LinearProgressIndicator-class.html
[`ListTile`]: {{site.api}}/flutter/material/ListTile-class.html
[`ListView`]: {{site.api}}/flutter/widgets/ListView-class.html
[`ListView.builder`]: {{site.api}}/flutter/widgets/ListView/ListView.builder.html
[Material Design]: {{site.material}}/styles
[Material icons]: {{site.api}}/flutter/material/Icons-class.html
[`MaterialApp`]: {{site.api}}/flutter/material/MaterialApp-class.html
[`MaterialPageRoute`]: {{site.api}}/flutter/material/MaterialPageRoute-class.html
[`ModalRoute`]: {{site.api}}/flutter/widgets/ModalRoute-class.html
[`Navigator`]: {{site.api}}/flutter/widgets/Navigator-class.html
[`Navigator.of()`]: {{site.api}}/flutter/widgets/Navigator/of.html
[`Navigator.pop`]: {{site.api}}/flutter/widgets/Navigator/pop.html
[`Navigator.push`]: {{site.api}}/flutter/widgets/Navigator/push.html
[`onSaved`]: {{site.api}}/flutter/widgets/FormField/onSaved.html
[named parameters]: {{site.dart-site}}/language/functions#named-parameters
[`Padding`]: {{site.api}}/flutter/widgets/Padding-class.html
[`PanResponder`]: https://facebook.github.io/react-native/docs/panresponder.html
[pub.dev]: {{site.pub}}
[`Radio`]: {{site.api}}/flutter/material/Radio-class.html
[`ElevatedButton`]: {{site.api}}/flutter/material/ElevatedButton-class.html
[`RefreshIndicator`]: {{site.api}}/flutter/material/RefreshIndicator-class.html
[`Route`]: {{site.api}}/flutter/widgets/Route-class.html
[`Row`]: {{site.api}}/flutter/widgets/Row-class.html
[`Scaffold`]: {{site.api}}/flutter/material/Scaffold-class.html
[`ScrollController`]: {{site.api}}/flutter/widgets/ScrollController-class.html
[`shared_preferences`]: {{site.repo.packages}}/tree/main/packages/shared_preferences/shared_preferences
[`SingleTickerProviderStateMixin`]: {{site.api}}/flutter/widgets/SingleTickerProviderStateMixin-mixin.html
[`Slider`]: {{site.api}}/flutter/material/Slider-class.html
[`Stack`]: {{site.api}}/flutter/widgets/Stack-class.html
[State management]: /data-and-backend/state-mgmt
[`StatefulWidget`]: {{site.api}}/flutter/widgets/StatefulWidget-class.html
[`StatelessWidget`]: {{site.api}}/flutter/widgets/StatelessWidget-class.html
[`Switch`]: {{site.api}}/flutter/material/Switch-class.html
[`Tab`]: {{site.api}}/flutter/material/Tab-class.html
[`TabBar`]: {{site.api}}/flutter/material/TabBar-class.html
[`TabBarView`]: {{site.api}}/flutter/material/TabBarView-class.html
[`TabController`]: {{site.api}}/flutter/material/TabController-class.html
[`Text`]: {{site.api}}/flutter/widgets/Text-class.html
[`TextAlign`]: {{site.api}}/flutter/dart-ui/TextAlign.html
[`TextEditingController`]: {{site.api}}/flutter/widgets/TextEditingController-class.html
[`TextField`]: {{site.api}}/flutter/material/TextField-class.html
[`TextFormField`]: {{site.api}}/flutter/material/TextFormField-class.html
[`TextInput`]: {{site.api}}/flutter/services/TextInput-class.html
[`TextStyle`]: {{site.api}}/flutter/dart-ui/TextStyle-class.html
[`Theme`]: {{site.api}}/flutter/material/Theme-class.html
[`ThemeData`]: {{site.api}}/flutter/material/ThemeData-class.html
[`Ticker`]: {{site.api}}/flutter/scheduler/Ticker-class.html
[`TickerProvider`]: {{site.api}}/flutter/scheduler/TickerProvider-class.html
[`TickerProviderStateMixin`]: {{site.api}}/flutter/widgets/TickerProviderStateMixin-mixin.html
[`Tween`]: {{site.api}}/flutter/animation/Tween-class.html
[Using Packages]: /packages-and-plugins/using-packages
[variables]: {{site.dart-site}}/language/variables
[`WidgetBuilder`]: {{site.api}}/flutter/widgets/WidgetBuilder.html
[infinite_list]: {{site.repo.samples}}/tree/main/infinite_list
| website/src/get-started/flutter-for/react-native-devs.md/0 | {
"file_path": "website/src/get-started/flutter-for/react-native-devs.md",
"repo_id": "website",
"token_count": 41396
} | 1,309 |
## Android setup (without Android Studio)
### Install Java
```terminal
$ sudo apt update
$ sudo apt install default-jre
$ sudo apt install default-jdk
```
### Install the Android SDKs
Download the [Android SDK tools][] and
select the "Command Line Tools only" option.
Drag and drop the downloaded zip into your Linux Files folder through the
ChromeOS Files app. This moves the file to the home directory,
and is referred to as $TOOLS_PATH going forward (`~/`).
Unzip the tools and then add it to your path.
```terminal
$ unzip ~/sdk-tools-linux*
$ export PATH="$PATH:$TOOLS_PATH/tools/bin"
```
Navigate to where you'd like to keep the SDK packages
($PLATFORM_PATH in these snippets) and download the SDK
packages using the sdkmanager tool (version numbers here are
the latest at time of publishing):
```terminal
$ sdkmanager "build-tools;28.0.3" "emulator" "tools" "platform-tools" "platforms;android-28" "extras;google;google_play_services" "extras;google;webdriver" "system-images;android-28;google_apis_playstore;x86_64"
```
Add the Android platform tools to your path (you should find this where you
ran the sdkmanager command: $PLATFORM_PATH):
```terminal
$ export PATH="$PATH:$PLATFORM_PATH/platform-tools"
```
Set the `ANDROID_SDK_ROOT` variable to where you unzipped sdk-tools before (aka
your $TOOLS_PATH):
```terminal
$ export ANDROID_SDK_ROOT="$TOOLS_PATH"
```
Now, run flutter doctor to accept the android-licenses:
```terminal
$ flutter doctor --android-licenses
```
[Android SDK tools]: {{site.android-dev}}/studio/#downloads
| website/src/get-started/install/_deprecated/_chromeos-android-sdk-setup.md/0 | {
"file_path": "website/src/get-started/install/_deprecated/_chromeos-android-sdk-setup.md",
"repo_id": "website",
"token_count": 501
} | 1,310 |
---
title: Start building Flutter Android apps on Linux
description: Configure your system to develop Flutter mobile apps on Linux and Android.
short-title: Make Android apps
target: Android
config: LinuxAndroid
devos: Linux
next:
title: Create a test app
path: /get-started/test-drive
---
{% include docs/install/reqs/linux/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/android.md
devos=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/linux/android.md/0 | {
"file_path": "website/src/get-started/install/linux/android.md",
"repo_id": "website",
"token_count": 304
} | 1,311 |
---
title: Flutter documentation
short-title: Docs
description: Get started with Flutter. Widgets, examples, updates, and API docs to help you write your first Flutter app.
---
{% for card in site.data.docs_cards -%}
{% capture index0Modulo3 -%}{{ forloop.index0 | modulo:3 }}{% endcapture -%}
{% capture indexModulo3 -%}{{ forloop.index | modulo:3 }}{% endcapture -%}
{% if index0Modulo3 == '0' -%}
<div class="card-deck mb-4">
{% endif -%}
<a class="card" href="{{card.url}}">
<div class="card-body">
<header class="card-title">{{card.name}}</header>
<p class="card-text">{{card.description}}</p>
</div>
</a>
{% if indexModulo3 == '0' -%}
</div>
{% endif -%}
{% endfor %}
**To see changes to the site since our last release,
see [What's new][].**
[What's new]: /release/whats-new
## New to Flutter?
Once you've gone through [Get started][],
including [Write your first Flutter app][],
here are some next steps.
[Write your first Flutter app]: /get-started/codelab
### Docs
Coming from another platform? Check out Flutter for:
[Android][], [SwiftUI][], [UIKit][], [React Native][], and
[Xamarin.Forms][] developers.
[Building layouts][]
: Learn how to create layouts in Flutter,
where everything is a widget.
[Understanding constraints][]
: Once you understand that "Constraints
flow down. Sizes flow up. Parents set
positions", then you are well on your
way to understanding Flutter's layout model.
[Adding interactivity to your Flutter app][interactivity]
: Learn how to add a stateful widget to your app.
[FAQ][]
: Get the answers to frequently asked questions.
[Android]: /get-started/flutter-for/android-devs
[Building layouts]: /ui/layout
[FAQ]: /resources/faq
[Get started]: /get-started/install
[interactivity]: /ui/interactivity
[SwiftUI]: /get-started/flutter-for/swiftui-devs
[UIKit]: /get-started/flutter-for/uikit-devs
[React Native]: /get-started/flutter-for/react-native-devs
[Understanding constraints]: /ui/layout/constraints
[Xamarin.Forms]: /get-started/flutter-for/xamarin-forms-devs
### Videos
Check out the Introducing Flutter series.
Learn Flutter basics like
[how do I make my first Flutter app?][first-app]
In Flutter, "everything is a widget"!
Learn more about `Stateless` and `Stateful`
widgets in [What is State?][]
<div class="card-deck card-deck--responsive">
<div class="video-card">
<div class="card-body">
<iframe style="max-width: 100%; width: 100%; height: 230px;" src="{{site.yt.embed}}/xWV71C2kp38" title="Create your first Flutter app" {{site.yt.set}}></iframe>
</div>
</div>
<div class="video-card">
<div class="card-body">
<iframe style="max-width: 100%; width: 100%; height: 230px;" src="{{site.yt.embed}}/QlwiL_yLh6E" title="What is state?" {{site.yt.set}}></iframe>
</div>
</div>
</div>
[first-app]: {{site.yt.watch}}?v=xWV71C2kp38
[What is State?]: {{site.yt.watch}}?v=QlwiL_yLh6E
{:.text-center}
**Only have 60 seconds? Learn how to build and deploy a Flutter App!**
<div style="display: flex; align-items: center; justify-content: center; flex-direction: column;">
<iframe style="max-width: 100%" width="560" height="315" src="{{site.yt.embed}}/ZnufaryH43s" title="Learn how to build and deploy a Flutter app in 60 seconds" {{site.yt.set}}></iframe>
</div>
## Want to skill up?
Dive deeper into how Flutter works under the hood!
Learn [why you write standalone widgets instead of
using helper methods][standalone-widgets] or
[what is "BuildContext" and how is it used][buildcontext]?
<div class="card-deck card-deck--responsive">
<div class="video-card">
<div class="card-body">
<iframe style="max-width: 100%; width: 100%; height: 230px;" src="{{site.yt.embed}}/IOyq-eTRhvo" title="Learn the difference between Widgets and Helper Methods" {{site.yt.set}}></iframe>
</div>
</div>
<div class="video-card">
<div class="card-body">
<iframe style="max-width: 100%; width: 100%; height: 230px;" src="{{site.yt.embed}}/rIaaH87z1-g" title="Learn how to demystify BuildContext" {{site.yt.set}}></iframe>
</div>
</div>
</div>
[standalone-widgets]: {{site.yt.watch}}?v=IOyq-eTRhvo
[buildcontext]: {{site.yt.watch}}?v=rIaaH87z1-g
To learn about all of the Flutter video series,
see our [videos][] page.
We release new videos almost every week on the Flutter YouTube channel:
<a class="btn btn-primary" target="_blank" href="https://www.youtube.com/@flutterdev">Explore more Flutter videos</a>
**The documentation on this site reflects the
latest stable release of Flutter.**
[videos]: /resources/videos
| website/src/index.md/0 | {
"file_path": "website/src/index.md",
"repo_id": "website",
"token_count": 1704
} | 1,312 |
---
title: Performance metrics
description: Flutter metrics, and which tools and APIs are used to get them
---
* Startup time to the first frame
* Check the time when
[WidgetsBinding.instance.firstFrameRasterized][firstFrameRasterized]
is true.
* See the
[perf dashboard](https://flutter-flutter-perf.skia.org/e/?queries=sub_result%3DtimeToFirstFrameRasterizedMicros).
* Frame buildDuration, rasterDuration, and totalSpan
* See [`FrameTiming`]({{site.api}}/flutter/dart-ui/FrameTiming-class.html)
in the API docs.
* Statistics of frame `buildDuration` (`*_frame_build_time_millis`)
* We recommend monitoring four stats: average, 90th percentile, 99th
percentile, and worst frame build time.
* See, for example, [metrics][transition_build] for the
`flutter_gallery__transition_perf` test.
* Statistics of frame `rasterDuration` (`*_frame_build_time_millis`)
* We recommend monitoring four stats: average, 90th percentile, 99th
percentile, and worst frame build time.
* See, for example, [metrics][transition_raster] for the
`flutter_gallery__transition_perf` test.
* CPU/GPU usage (a good approximation for energy use)
* The usage is currently only available through trace events. See
[profiling_summarizer.dart][profiling_summarizer].
* See [metrics][cpu_gpu] for the `simple_animation_perf_ios` test.
* release_size_bytes to approximately measure the size of a Flutter app
* See the [basic_material_app_android][], [basic_material_app_ios][],
[hello_world_android][], [hello_world_ios][], [flutter_gallery_android][],
and [flutter_gallery_ios][] tests.
* See [metrics][size_perf] in the dashboard.
* For info on how to measure the size more accurately,
see the [app size](/perf/app-size) page.
For a complete list of performance metrics Flutter measures per commit, visit
the following sites, click **Query**, and filter the **test** and
**sub_result** fields:
* [https://flutter-flutter-perf.skia.org/e/](https://flutter-flutter-perf.skia.org/e/)
* [https://flutter-engine-perf.skia.org/e/](https://flutter-engine-perf.skia.org/e/)
[firstFrameRasterized]: {{site.api}}/flutter/widgets/WidgetsBinding/firstFrameRasterized.html
[transition_build]: https://flutter-flutter-perf.skia.org/e/?queries=sub_result%3D90th_percentile_frame_build_time_millis%26sub_result%3D99th_percentile_frame_build_time_millis%26sub_result%3Daverage_frame_build_time_millis%26sub_result%3Dworst_frame_build_time_millis%26test%3Dflutter_gallery__transition_perf
[transition_raster]: https://flutter-flutter-perf.skia.org/e/?queries=sub_result%3D90th_percentile_frame_rasterizer_time_millis%26sub_result%3D99th_percentile_frame_rasterizer_time_millis%26sub_result%3Daverage_frame_rasterizer_time_millis%26sub_result%3Dworst_frame_rasterizer_time_millis%26test%3Dflutter_gallery__transition_perf
[profiling_summarizer]: {{site.repo.flutter}}/blob/master/packages/flutter_driver/lib/src/driver/profiling_summarizer.dart
[cpu_gpu]: https://flutter-flutter-perf.skia.org/e/?queries=sub_result%3Daverage_cpu_usage%26sub_result%3Daverage_gpu_usage%26test%3Dsimple_animation_perf_ios
[basic_material_app_android]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/basic_material_app_android__compile.dart
[basic_material_app_ios]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/basic_material_app_ios__compile.dart
[hello_world_android]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/hello_world_android__compile.dart
[hello_world_ios]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/hello_world_ios__compile.dart
[flutter_gallery_android]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/flutter_gallery_android__compile.dart
[flutter_gallery_ios]: {{site.repo.flutter}}/blob/master/dev/devicelab/bin/tasks/flutter_gallery_ios__compile.dart
[size_perf]: https://flutter-flutter-perf.skia.org/e/?queries=sub_result%3Drelease_size_bytes%26test%3Dbasic_material_app_android__compile%26test%3Dbasic_material_app_ios__compile%26test%3Dhello_world_android__compile%26test%3Dhello_world_ios__compile%26test%3Dflutter_gallery_ios__compile%26test%3Dflutter_gallery_android__compile
| website/src/perf/metrics.md/0 | {
"file_path": "website/src/perf/metrics.md",
"repo_id": "website",
"token_count": 1535
} | 1,313 |
---
title: Adding a launch screen to your iOS app
short-title: Launch screen
description: Learn how to add a launch screen to your iOS app.
toc: false
---
{% comment %}
Consider introducing an image here similar to the android splash-screen one:
https://github.com/flutter/website/issues/8357
{% endcomment -%}
[Launch screens][] provide a simple initial experience while your iOS app loads.
They set the stage for your application, while allowing time for the app engine
to load and your app to initialize.
[Launch screens]: {{site.apple-dev}}/design/human-interface-guidelines/launching#Launch-screens
All apps submitted to the Apple App Store
[must provide a launch screen][apple-requirement]
with an Xcode storyboard.
## Customize the launch screen
The default Flutter template includes an Xcode
storyboard named `LaunchScreen.storyboard`
that can be customized your own assets.
By default, the storyboard displays a blank image,
but you can change this. To do so,
open the Flutter app's Xcode project
by typing `open ios/Runner.xcworkspace`
from the root of your app directory.
Then select `Runner/Assets.xcassets`
from the Project Navigator and
drop in the desired images to the `LaunchImage` image set.
Apple provides detailed guidance for launch screens as
part of the [Human Interface Guidelines][].
[apple-requirement]: {{site.apple-dev}}/documentation/xcode/specifying-your-apps-launch-screen
[Human Interface Guidelines]: {{site.apple-dev}}/design/human-interface-guidelines/patterns/launching#launch-screens
| website/src/platform-integration/ios/launch-screen.md/0 | {
"file_path": "website/src/platform-integration/ios/launch-screen.md",
"repo_id": "website",
"token_count": 406
} | 1,314 |
---
title: Writing custom platform-specific code
short-title: Platform-specific code
description: Learn how to write custom platform-specific code in your app.
---
<?code-excerpt path-base="development/platform_integration"?>
This guide describes how to write custom platform-specific code.
Some platform-specific functionality is available
through existing packages;
see [using packages][].
[using packages]: /packages-and-plugins/using-packages
{{site.alert.note}}
The information in this page is valid for most platforms,
but platform-specific code for the web generally uses
[JS interoperability][] or the [`dart:html` library][] instead.
{{site.alert.end}}
Flutter uses a flexible system that allows you to call
platform-specific APIs in a language that works directly
with those APIs:
* Kotlin or Java on Android
* Swift or Objective-C on iOS
* C++ on Windows
* Objective-C on macOS
* C on Linux
Flutter's builtin platform-specific API support
doesn't rely on code generation,
but rather on a flexible message passing style.
Alternatively, you can use the [Pigeon][pigeon]
package for [sending structured typesafe messages][]
with code generation:
* The Flutter portion of the app sends messages to its _host_,
the non-Dart portion of the app, over a platform channel.
* The _host_ listens on the platform channel, and receives the message.
It then calls into any number of platform-specific APIs—using
the native programming language—and sends a response back to the
_client_, the Flutter portion of the app.
{{site.alert.note}}
This guide addresses using the platform channel mechanism
if you need to use the platform's APIs in a non-Dart language.
But you can also write platform-specific Dart code
in your Flutter app by inspecting the
[`defaultTargetPlatform`][] property.
[Platform adaptations][] lists some
platform-specific adaptations that Flutter
automatically performs for you in the framework.
{{site.alert.end}}
[`defaultTargetPlatform`]: {{site.api}}/flutter/foundation/defaultTargetPlatform.html
[pigeon]: {{site.pub-pkg}}/pigeon
## Architectural overview: platform channels {#architecture}
Messages are passed between the client (UI)
and host (platform) using platform
channels as illustrated in this diagram:
{:width="100%"}
Messages and responses are passed asynchronously,
to ensure the user interface remains responsive.
{{site.alert.note}}
Even though Flutter sends messages to and from Dart asynchronously,
whenever you invoke a channel method, you must invoke that method on the
platform's main thread. See the [section on threading][]
for more information.
{{site.alert.end}}
On the client side, [`MethodChannel`][] enables sending
messages that correspond to method calls. On the platform side,
`MethodChannel` on Android ([`MethodChannelAndroid`][]) and
`FlutterMethodChannel` on iOS ([`MethodChanneliOS`][])
enable receiving method calls and sending back a
result. These classes allow you to develop a platform plugin
with very little 'boilerplate' code.
{{site.alert.note}}
If desired, method calls can also be sent in the reverse direction,
with the platform acting as client to methods implemented in Dart.
For a concrete example, check out the [`quick_actions`][] plugin.
{{site.alert.end}}
### Platform channel data types support and codecs {#codec}
The standard platform channels use a standard message codec that supports
efficient binary serialization of simple JSON-like values, such as booleans,
numbers, Strings, byte buffers, and Lists and Maps of these
(see [`StandardMessageCodec`][] for details).
The serialization and deserialization of these values to and from
messages happens automatically when you send and receive values.
The following table shows how Dart values are received on the
platform side and vice versa:
{% samplecode type-mappings %}
{% sample Java %}
| Dart | Java |
| -------------------------- | ------------------- |
| null | null |
| bool | java.lang.Boolean |
| int | java.lang.Integer |
| int, if 32 bits not enough | java.lang.Long |
| double | java.lang.Double |
| String | java.lang.String |
| Uint8List | byte[] |
| Int32List | int[] |
| Int64List | long[] |
| Float32List | float[] |
| Float64List | double[] |
| List | java.util.ArrayList |
| Map | java.util.HashMap |
{% sample Kotlin %}
| Dart | Kotlin |
| -------------------------- | ----------- |
| null | null |
| bool | Boolean |
| int | Int |
| int, if 32 bits not enough | Long |
| double | Double |
| String | String |
| Uint8List | ByteArray |
| Int32List | IntArray |
| Int64List | LongArray |
| Float32List | FloatArray |
| Float64List | DoubleArray |
| List | List |
| Map | HashMap |
{% sample Obj-C %}
| Dart | Objective-C |
| -------------------------- | ---------------------------------------------- |
| null | nil (NSNull when nested) |
| bool | NSNumber numberWithBool: |
| int | NSNumber numberWithInt: |
| int, if 32 bits not enough | NSNumber numberWithLong: |
| double | NSNumber numberWithDouble: |
| String | NSString |
| Uint8List | FlutterStandardTypedData typedDataWithBytes: |
| Int32List | FlutterStandardTypedData typedDataWithInt32: |
| Int64List | FlutterStandardTypedData typedDataWithInt64: |
| Float32List | FlutterStandardTypedData typedDataWithFloat32: |
| Float64List | FlutterStandardTypedData typedDataWithFloat64: |
| List | NSArray |
| Map | NSDictionary |
{% sample Swift %}
| Dart | Swift |
| -------------------------- | --------------------------------------- |
| null | nil |
| bool | NSNumber(value: Bool) |
| int | NSNumber(value: Int32) |
| int, if 32 bits not enough | NSNumber(value: Int) |
| double | NSNumber(value: Double) |
| String | String |
| Uint8List | FlutterStandardTypedData(bytes: Data) |
| Int32List | FlutterStandardTypedData(int32: Data) |
| Int64List | FlutterStandardTypedData(int64: Data) |
| Float32List | FlutterStandardTypedData(float32: Data) |
| Float64List | FlutterStandardTypedData(float64: Data) |
| List | Array |
| Map | Dictionary |
{% sample C++ %}
| Dart | C++ |
| -------------------------- | -------------------------------------------------------- |
| null | EncodableValue() |
| bool | EncodableValue(bool) |
| int | EncodableValue(int32_t) |
| int, if 32 bits not enough | EncodableValue(int64_t) |
| double | EncodableValue(double) |
| String | EncodableValue(std::string) |
| Uint8List | EncodableValue(std::vector<uint8_t>) |
| Int32List | EncodableValue(std::vector<int32_t>) |
| Int64List | EncodableValue(std::vector<int64_t>) |
| Float32List | EncodableValue(std::vector<float>) |
| Float64List | EncodableValue(std::vector<double>) |
| List | EncodableValue(std::vector<EncodableValue>) |
| Map | EncodableValue(std::map<EncodableValue, EncodableValue>) |
{% sample C %}
| Dart | C (GObject) |
| -------------------------- | ------------------------- |
| null | FlValue() |
| bool | FlValue(bool) |
| int | FlValue(int64_t) |
| double | FlValue(double) |
| String | FlValue(gchar*) |
| Uint8List | FlValue(uint8_t*) |
| Int32List | FlValue(int32_t*) |
| Int64List | FlValue(int64_t*) |
| Float32List | FlValue(float*) |
| Float64List | FlValue(double*) |
| List | FlValue(FlValue) |
| Map | FlValue(FlValue, FlValue) |
{% endsamplecode %}
## Example: Calling platform-specific code using platform channels {#example}
The following code demonstrates how to call
a platform-specific API to retrieve and display
the current battery level. It uses
the Android `BatteryManager` API,
the iOS `device.batteryLevel` API,
the Windows `GetSystemPowerStatus` API,
and the Linux `UPower` API with a single
platform message, `getBatteryLevel()`.
The example adds the platform-specific code inside
the main app itself. If you want to reuse the
platform-specific code for multiple apps,
the project creation step is slightly different
(see [developing packages][plugins]),
but the platform channel code
is still written in the same way.
{{site.alert.note}}
The full, runnable source-code for this example is
available in [`/examples/platform_channel/`][]
for Android with Java, iOS with Objective-C,
Windows with C++, and Linux with C.
For iOS with Swift,
see [`/examples/platform_channel_swift/`][].
{{site.alert.end}}
### Step 1: Create a new app project {#example-project}
Start by creating a new app:
* In a terminal run: `flutter create batterylevel`
By default, our template supports writing Android code using Kotlin,
or iOS code using Swift. To use Java or Objective-C,
use the `-i` and/or `-a` flags:
* In a terminal run: `flutter create -i objc -a java batterylevel`
### Step 2: Create the Flutter platform client {#example-client}
The app's `State` class holds the current app state.
Extend that to hold the current battery state.
First, construct the channel. Use a `MethodChannel` with a single
platform method that returns the battery level.
The client and host sides of a channel are connected through
a channel name passed in the channel constructor.
All channel names used in a single app must
be unique; prefix the channel name with a unique 'domain
prefix', for example: `samples.flutter.dev/battery`.
<?code-excerpt "lib/platform_channels.dart (Import)"?>
```dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
```
<?code-excerpt "lib/platform_channels.dart (MyHomePageState)"?>
```dart
class _MyHomePageState extends State<MyHomePage> {
static const platform = MethodChannel('samples.flutter.dev/battery');
// Get battery level.
```
Next, invoke a method on the method channel,
specifying the concrete method to call using
the `String` identifier `getBatteryLevel`.
The call might fail—for example,
if the platform doesn't support the
platform API (such as when running in a simulator),
so wrap the `invokeMethod` call in a try-catch statement.
Use the returned result to update the user interface state in `_batteryLevel`
inside `setState`.
<?code-excerpt "lib/platform_channels.dart (GetBattery)"?>
```dart
// Get battery level.
String _batteryLevel = 'Unknown battery level.';
Future<void> _getBatteryLevel() async {
String batteryLevel;
try {
final result = await platform.invokeMethod<int>('getBatteryLevel');
batteryLevel = 'Battery level at $result % .';
} on PlatformException catch (e) {
batteryLevel = "Failed to get battery level: '${e.message}'.";
}
setState(() {
_batteryLevel = batteryLevel;
});
}
```
Finally, replace the `build` method from the template to
contain a small user interface that displays the battery
state in a string, and a button for refreshing the value.
<?code-excerpt "lib/platform_channels.dart (Build)"?>
```dart
@override
Widget build(BuildContext context) {
return Material(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _getBatteryLevel,
child: const Text('Get Battery Level'),
),
Text(_batteryLevel),
],
),
),
);
}
```
### Step 3: Add an Android platform-specific implementation
{% samplecode android-channel %}
{% sample Kotlin %}
Start by opening the Android host portion of your Flutter app
in Android Studio:
1. Start Android Studio
1. Select the menu item **File > Open...**
1. Navigate to the directory holding your Flutter app,
and select the **android** folder inside it. Click **OK**.
1. Open the file `MainActivity.kt` located in the **kotlin** folder in the
Project view.
Inside the `configureFlutterEngine()` method, create a `MethodChannel` and call
`setMethodCallHandler()`. Make sure to use the same channel name as
was used on the Flutter client side.
<?code-excerpt title="MainActivity.kt"?>
```kotlin
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity: FlutterActivity() {
private val CHANNEL = "samples.flutter.dev/battery"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
// This method is invoked on the main thread.
// TODO
}
}
}
```
Add the Android Kotlin code that uses the Android battery APIs to
retrieve the battery level. This code is exactly the same as you
would write in a native Android app.
First, add the needed imports at the top of the file:
<?code-excerpt title="MainActivity.kt"?>
```kotlin
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
```
Next, add the following method in the `MainActivity` class,
below the `configureFlutterEngine()` method:
<?code-excerpt title="MainActivity.kt"?>
```kotlin
private fun getBatteryLevel(): Int {
val batteryLevel: Int
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
} else {
val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
}
return batteryLevel
}
```
Finally, complete the `setMethodCallHandler()` method added earlier.
You need to handle a single platform method, `getBatteryLevel()`,
so test for that in the `call` argument.
The implementation of this platform method calls the
Android code written in the previous step, and returns a response for both
the success and error cases using the `result` argument.
If an unknown method is called, report that instead.
Remove the following code:
<?code-excerpt title="MainActivity.kt"?>
```kotlin
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
call, result ->
// This method is invoked on the main thread.
// TODO
}
```
And replace with the following:
<?code-excerpt title="MainActivity.kt"?>
```kotlin
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
// This method is invoked on the main thread.
call, result ->
if (call.method == "getBatteryLevel") {
val batteryLevel = getBatteryLevel()
if (batteryLevel != -1) {
result.success(batteryLevel)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} else {
result.notImplemented()
}
}
```
{% sample Java %}
Start by opening the Android host portion of your Flutter app
in Android Studio:
1. Start Android Studio
1. Select the menu item **File > Open...**
1. Navigate to the directory holding your Flutter app,
and select the **android** folder inside it. Click **OK**.
1. Open the `MainActivity.java` file located in the **java** folder in the
Project view.
Next, create a `MethodChannel` and set a `MethodCallHandler`
inside the `configureFlutterEngine()` method.
Make sure to use the same channel name as was used on the
Flutter client side.
<?code-excerpt title="MainActivity.java"?>
```java
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
public class MainActivity extends FlutterActivity {
private static final String CHANNEL = "samples.flutter.dev/battery";
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
// This method is invoked on the main thread.
// TODO
}
);
}
}
```
Add the Android Java code that uses the Android battery APIs to
retrieve the battery level. This code is exactly the same as you
would write in a native Android app.
First, add the needed imports at the top of the file:
<?code-excerpt title="MainActivity.java"?>
```java
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
```
Then add the following as a new method in the activity class,
below the `configureFlutterEngine()` method:
<?code-excerpt title="MainActivity.java"?>
```java
private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
```
Finally, complete the `setMethodCallHandler()` method added earlier.
You need to handle a single platform method, `getBatteryLevel()`,
so test for that in the `call` argument. The implementation of
this platform method calls the Android code written
in the previous step, and returns a response for both
the success and error cases using the `result` argument.
If an unknown method is called, report that instead.
Remove the following code:
<?code-excerpt title="MainActivity.java"?>
```java
(call, result) -> {
// This method is invoked on the main thread.
// TODO
}
```
And replace with the following:
<?code-excerpt title="MainActivity.java"?>
```java
(call, result) -> {
// This method is invoked on the main thread.
if (call.method.equals("getBatteryLevel")) {
int batteryLevel = getBatteryLevel();
if (batteryLevel != -1) {
result.success(batteryLevel);
} else {
result.error("UNAVAILABLE", "Battery level not available.", null);
}
} else {
result.notImplemented();
}
}
```
{% endsamplecode %}
You should now be able to run the app on Android. If using the Android
Emulator, set the battery level in the Extended Controls panel
accessible from the **...** button in the toolbar.
### Step 4: Add an iOS platform-specific implementation
{% samplecode ios-channel %}
{% sample Swift %}
Start by opening the iOS host portion of your Flutter app in Xcode:
1. Start Xcode.
1. Select the menu item **File > Open...**.
1. Navigate to the directory holding your Flutter app, and select the **ios**
folder inside it. Click **OK**.
Add support for Swift in the standard template setup that uses Objective-C:
1. **Expand Runner > Runner** in the Project navigator.
1. Open the file `AppDelegate.swift` located under **Runner > Runner**
in the Project navigator.
Override the `application:didFinishLaunchingWithOptions:` function and create
a `FlutterMethodChannel` tied to the channel name
`samples.flutter.dev/battery`:
<?code-excerpt title="AppDelegate.swift"?>
```swift
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let batteryChannel = FlutterMethodChannel(name: "samples.flutter.dev/battery",
binaryMessenger: controller.binaryMessenger)
batteryChannel.setMethodCallHandler({
(call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
// This method is invoked on the UI thread.
// Handle battery messages.
})
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
```
Next, add the iOS Swift code that uses the iOS battery APIs to retrieve
the battery level. This code is exactly the same as you
would write in a native iOS app.
Add the following as a new method at the bottom of `AppDelegate.swift`:
<?code-excerpt title="AppDelegate.swift"?>
```swift
private func receiveBatteryLevel(result: FlutterResult) {
let device = UIDevice.current
device.isBatteryMonitoringEnabled = true
if device.batteryState == UIDevice.BatteryState.unknown {
result(FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil))
} else {
result(Int(device.batteryLevel * 100))
}
}
```
Finally, complete the `setMethodCallHandler()` method added earlier.
You need to handle a single platform method, `getBatteryLevel()`,
so test for that in the `call` argument.
The implementation of this platform method calls
the iOS code written in the previous step. If an unknown method
is called, report that instead.
<?code-excerpt title="AppDelegate.swift"?>
```swift
batteryChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
// This method is invoked on the UI thread.
guard call.method == "getBatteryLevel" else {
result(FlutterMethodNotImplemented)
return
}
self?.receiveBatteryLevel(result: result)
})
```
{% sample Objective-C %}
Start by opening the iOS host portion of the Flutter app in Xcode:
1. Start Xcode.
1. Select the menu item **File > Open...**.
1. Navigate to the directory holding your Flutter app,
and select the **ios** folder inside it. Click **OK**.
1. Make sure the Xcode projects builds without errors.
1. Open the file `AppDelegate.m`, located under **Runner > Runner**
in the Project navigator.
Create a `FlutterMethodChannel` and add a handler inside the `application
didFinishLaunchingWithOptions:` method.
Make sure to use the same channel name
as was used on the Flutter client side.
<?code-excerpt title="AppDelegate.m"?>
```objectivec
#import <Flutter/Flutter.h>
#import "GeneratedPluginRegistrant.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
FlutterMethodChannel* batteryChannel = [FlutterMethodChannel
methodChannelWithName:@"samples.flutter.dev/battery"
binaryMessenger:controller.binaryMessenger];
[batteryChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
// This method is invoked on the UI thread.
// TODO
}];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
```
Next, add the iOS ObjectiveC code that uses the iOS battery APIs to
retrieve the battery level. This code is exactly the same as you
would write in a native iOS app.
Add the following method in the `AppDelegate` class, just before `@end`:
<?code-excerpt title="AppDelegate.m"?>
```objectivec
- (int)getBatteryLevel {
UIDevice* device = UIDevice.currentDevice;
device.batteryMonitoringEnabled = YES;
if (device.batteryState == UIDeviceBatteryStateUnknown) {
return -1;
} else {
return (int)(device.batteryLevel * 100);
}
}
```
Finally, complete the `setMethodCallHandler()` method added earlier.
You need to handle a single platform method, `getBatteryLevel()`,
so test for that in the `call` argument. The implementation of
this platform method calls the iOS code written in the previous step,
and returns a response for both the success and error cases using
the `result` argument. If an unknown method is called, report that instead.
<?code-excerpt title="AppDelegate.m"?>
```objectivec
__weak typeof(self) weakSelf = self;
[batteryChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
// This method is invoked on the UI thread.
if ([@"getBatteryLevel" isEqualToString:call.method]) {
int batteryLevel = [weakSelf getBatteryLevel];
if (batteryLevel == -1) {
result([FlutterError errorWithCode:@"UNAVAILABLE"
message:@"Battery level not available."
details:nil]);
} else {
result(@(batteryLevel));
}
} else {
result(FlutterMethodNotImplemented);
}
}];
```
{% endsamplecode %}
You should now be able to run the app on iOS.
If using the iOS Simulator,
note that it doesn't support battery APIs,
and the app displays 'Battery level not available'.
### Step 5: Add a Windows platform-specific implementation
Start by opening the Windows host portion of your Flutter app in Visual Studio:
1. Run `flutter build windows` in your project directory once to generate
the Visual Studio solution file.
1. Start Visual Studio.
1. Select **Open a project or solution**.
1. Navigate to the directory holding your Flutter app, then into the **build**
folder, then the **windows** folder, then select the `batterylevel.sln` file.
Click **Open**.
Add the C++ implementation of the platform channel method:
1. Expand **batterylevel > Source Files** in the Solution Explorer.
1. Open the file `flutter_window.cpp`.
First, add the necessary includes to the top of the file, just
after `#include "flutter_window.h"`:
<?code-excerpt title="flutter_window.cpp"?>
```cpp
#include <flutter/event_channel.h>
#include <flutter/event_sink.h>
#include <flutter/event_stream_handler_functions.h>
#include <flutter/method_channel.h>
#include <flutter/standard_method_codec.h>
#include <windows.h>
#include <memory>
```
Edit the `FlutterWindow::OnCreate` method and create
a `flutter::MethodChannel` tied to the channel name
`samples.flutter.dev/battery`:
<?code-excerpt title="flutter_window.cpp"?>
```cpp
bool FlutterWindow::OnCreate() {
// ...
RegisterPlugins(flutter_controller_->engine());
flutter::MethodChannel<> channel(
flutter_controller_->engine()->messenger(), "samples.flutter.dev/battery",
&flutter::StandardMethodCodec::GetInstance());
channel.SetMethodCallHandler(
[](const flutter::MethodCall<>& call,
std::unique_ptr<flutter::MethodResult<>> result) {
// TODO
});
SetChildContent(flutter_controller_->view()->GetNativeWindow());
return true;
}
```
Next, add the C++ code that uses the Windows battery APIs to
retrieve the battery level. This code is exactly the same as
you would write in a native Windows application.
Add the following as a new function at the top of
`flutter_window.cpp` just after the `#include` section:
<?code-excerpt title="flutter_window.cpp"?>
```cpp
static int GetBatteryLevel() {
SYSTEM_POWER_STATUS status;
if (GetSystemPowerStatus(&status) == 0 || status.BatteryLifePercent == 255) {
return -1;
}
return status.BatteryLifePercent;
}
```
Finally, complete the `setMethodCallHandler()` method added earlier.
You need to handle a single platform method, `getBatteryLevel()`,
so test for that in the `call` argument.
The implementation of this platform method calls
the Windows code written in the previous step. If an unknown method
is called, report that instead.
Remove the following code:
<?code-excerpt title="flutter_window.cpp"?>
```cpp
channel.SetMethodCallHandler(
[](const flutter::MethodCall<>& call,
std::unique_ptr<flutter::MethodResult<>> result) {
// TODO
});
```
And replace with the following:
<?code-excerpt title="flutter_window.cpp"?>
```cpp
channel.SetMethodCallHandler(
[](const flutter::MethodCall<>& call,
std::unique_ptr<flutter::MethodResult<>> result) {
if (call.method_name() == "getBatteryLevel") {
int battery_level = GetBatteryLevel();
if (battery_level != -1) {
result->Success(battery_level);
} else {
result->Error("UNAVAILABLE", "Battery level not available.");
}
} else {
result->NotImplemented();
}
});
```
You should now be able to run the application on Windows.
If your device doesn't have a battery,
it displays 'Battery level not available'.
### Step 6: Add a macOS platform-specific implementation
Start by opening the macOS host portion of your Flutter app in Xcode:
1. Start Xcode.
1. Select the menu item **File > Open...**.
1. Navigate to the directory holding your Flutter app, and select the **macos**
folder inside it. Click **OK**.
Add the Swift implementation of the platform channel method:
1. **Expand Runner > Runner** in the Project navigator.
1. Open the file `MainFlutterWindow.swift` located under **Runner > Runner**
in the Project navigator.
First, add the necessary import to the top of the file, just after
`import FlutterMacOS`:
<?code-excerpt title="MainFlutterWindow.swift"?>
```swift
import IOKit.ps
```
Create a `FlutterMethodChannel` tied to the channel name
`samples.flutter.dev/battery` in the `awakeFromNib` method:
<?code-excerpt title="MainFlutterWindow.swift"?>
```swift
override func awakeFromNib() {
// ...
self.setFrame(windowFrame, display: true)
let batteryChannel = FlutterMethodChannel(
name: "samples.flutter.dev/battery",
binaryMessenger: flutterViewController.engine.binaryMessenger)
batteryChannel.setMethodCallHandler { (call, result) in
// This method is invoked on the UI thread.
// Handle battery messages.
}
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
}
```
Next, add the macOS Swift code that uses the IOKit battery APIs to retrieve
the battery level. This code is exactly the same as you
would write in a native macOS app.
Add the following as a new method at the bottom of `MainFlutterWindow.swift`:
<?code-excerpt title="MainFlutterWindow.swift"?>
```swift
private func getBatteryLevel() -> Int? {
let info = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources: Array<CFTypeRef> = IOPSCopyPowerSourcesList(info).takeRetainedValue() as Array
if let source = sources.first {
let description =
IOPSGetPowerSourceDescription(info, source).takeUnretainedValue() as! [String: AnyObject]
if let level = description[kIOPSCurrentCapacityKey] as? Int {
return level
}
}
return nil
}
```
Finally, complete the `setMethodCallHandler` method added earlier.
You need to handle a single platform method, `getBatteryLevel()`,
so test for that in the `call` argument.
The implementation of this platform method calls
the macOS code written in the previous step. If an unknown method
is called, report that instead.
<?code-excerpt title="MainFlutterWindow.swift"?>
```swift
batteryChannel.setMethodCallHandler { (call, result) in
switch call.method {
case "getBatteryLevel":
guard let level = getBatteryLevel() else {
result(
FlutterError(
code: "UNAVAILABLE",
message: "Battery level not available",
details: nil))
return
}
result(level)
default:
result(FlutterMethodNotImplemented)
}
}
```
You should now be able to run the application on macOS.
If your device doesn't have a battery,
it displays 'Battery level not available'.
### Step 7: Add a Linux platform-specific implementation
For this example you need to install the `upower` developer headers.
This is likely available from your distribution, for example with:
```sh
sudo apt install libupower-glib-dev
```
Start by opening the Linux host portion of your Flutter app in the editor
of your choice. The instructions below are for Visual Studio Code with the
"C/C++" and "CMake" extensions installed, but can be adjusted for other IDEs.
1. Launch Visual Studio Code.
1. Open the **linux** directory inside your project.
1. Choose **Yes** in the prompt asking: `Would you like to configure project "linux"?`.
This enables C++ autocomplete.
1. Open the file `my_application.cc`.
First, add the necessary includes to the top of the file, just
after `#include <flutter_linux/flutter_linux.h`:
<?code-excerpt title="my_application.cc"?>
```c
#include <math.h>
#include <upower.h>
```
Add an `FlMethodChannel` to the `_MyApplication` struct:
<?code-excerpt title="my_application.cc"?>
```c
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
FlMethodChannel* battery_channel;
};
```
Make sure to clean it up in `my_application_dispose`:
<?code-excerpt title="my_application.cc"?>
```c
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
g_clear_object(&self->battery_channel);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
```
Edit the `my_application_activate` method and initialize
`battery_channel` using the channel name
`samples.flutter.dev/battery`, just after the call to
`fl_register_plugins`:
<?code-excerpt title="my_application.cc"?>
```c
static void my_application_activate(GApplication* application) {
// ...
fl_register_plugins(FL_PLUGIN_REGISTRY(self->view));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
self->battery_channel = fl_method_channel_new(
fl_engine_get_binary_messenger(fl_view_get_engine(view)),
"samples.flutter.dev/battery", FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(
self->battery_channel, battery_method_call_handler, self, nullptr);
gtk_widget_grab_focus(GTK_WIDGET(self->view));
}
```
Next, add the C code that uses the Linux battery APIs to
retrieve the battery level. This code is exactly the same as
you would write in a native Linux application.
Add the following as a new function at the top of
`my_application.cc` just after the `G_DEFINE_TYPE` line:
<?code-excerpt title="my_application.cc"?>
```c
static FlMethodResponse* get_battery_level() {
// Find the first available battery and report that.
g_autoptr(UpClient) up_client = up_client_new();
g_autoptr(GPtrArray) devices = up_client_get_devices2(up_client);
if (devices->len == 0) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
"UNAVAILABLE", "Device does not have a battery.", nullptr));
}
UpDevice* device = (UpDevice*)(g_ptr_array_index(devices, 0));
double percentage = 0;
g_object_get(device, "percentage", &percentage, nullptr);
g_autoptr(FlValue) result =
fl_value_new_int(static_cast<int64_t>(round(percentage)));
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
}
```
Finally, add the `battery_method_call_handler` function referenced
in the earlier call to `fl_method_channel_set_method_call_handler`.
You need to handle a single platform method, `getBatteryLevel`,
so test for that in the `method_call` argument.
The implementation of this function calls
the Linux code written in the previous step. If an unknown method
is called, report that instead.
Add the following code after the `get_battery_level` function:
<?code-excerpt title="flutter_window.cpp"?>
```c
static void battery_method_call_handler(FlMethodChannel* channel,
FlMethodCall* method_call,
gpointer user_data) {
g_autoptr(FlMethodResponse) response = nullptr;
if (strcmp(fl_method_call_get_name(method_call), "getBatteryLevel") == 0) {
response = get_battery_level();
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
g_autoptr(GError) error = nullptr;
if (!fl_method_call_respond(method_call, response, &error)) {
g_warning("Failed to send response: %s", error->message);
}
}
```
You should now be able to run the application on Linux.
If your device doesn't have a battery,
it displays 'Battery level not available'.
## Typesafe platform channels using Pigeon {#pigeon}
The previous example uses `MethodChannel`
to communicate between the host and client,
which isn't typesafe. Calling and receiving
messages depends on the host and client declaring
the same arguments and datatypes in order for messages to work.
You can use the [Pigeon][pigeon] package as
an alternative to `MethodChannel`
to generate code that sends messages in a
structured, typesafe manner.
With [Pigeon][pigeon], the messaging protocol is defined
in a subset of Dart that then generates messaging
code for Android, iOS, macOS, or Windows. You can find a more complete
example and more information on the [`pigeon`][pigeon]
page on pub.dev.
Using [Pigeon][pigeon] eliminates the need to match
strings between host and client
for the names and datatypes of messages.
It supports: nested classes, grouping
messages into APIs, generation of
asynchronous wrapper code and sending messages
in either direction. The generated code is readable
and guarantees there are no conflicts between
multiple clients of different versions.
Supported languages are Objective-C, Java, Kotlin, C++,
and Swift (with Objective-C interop).
### Pigeon example
**Pigeon file:**
<?code-excerpt "lib/pigeon_source.dart (Search)"?>
```dart
import 'package:pigeon/pigeon.dart';
class SearchRequest {
final String query;
SearchRequest({required this.query});
}
class SearchReply {
final String result;
SearchReply({required this.result});
}
@HostApi()
abstract class Api {
@async
SearchReply search(SearchRequest request);
}
```
**Dart usage:**
<?code-excerpt "lib/use_pigeon.dart (UseApi)"?>
```dart
import 'generated_pigeon.dart';
Future<void> onClick() async {
SearchRequest request = SearchRequest(query: 'test');
Api api = SomeApi();
SearchReply reply = await api.search(request);
print('reply: ${reply.result}');
}
```
## Separate platform-specific code from UI code {#separate}
If you expect to use your platform-specific code
in multiple Flutter apps, you might consider
separating the code into a platform plugin located
in a directory outside your main application.
See [developing packages][] for details.
## Publish platform-specific code as a package {#publish}
To share your platform-specific code with other developers
in the Flutter ecosystem, see [publishing packages][].
## Custom channels and codecs
Besides the above mentioned `MethodChannel`,
you can also use the more basic
[`BasicMessageChannel`][], which supports basic,
asynchronous message passing using a custom message codec.
You can also use the specialized [`BinaryCodec`][],
[`StringCodec`][], and [`JSONMessageCodec`][]
classes, or create your own codec.
You might also check out an example of a custom codec
in the [`cloud_firestore`][] plugin,
which is able to serialize and deserialize many more
types than the default types.
## Channels and platform threading
When invoking channels on the platform side destined for Flutter,
invoke them on the platform's main thread.
When invoking channels in Flutter destined for the platform side,
either invoke them from any `Isolate` that is the root
`Isolate`, _or_ that is registered as a background `Isolate`.
The handlers for the platform side can execute on the platform's main thread
or they can execute on a background thread if using a Task Queue.
You can invoke the platform side handlers asynchronously
and on any thread.
{{site.alert.note}}
On Android, the platform's main thread is sometimes
called the "main thread", but it is technically defined
as [the UI thread][]. Annotate methods that need
to be run on the UI thread with `@UiThread`.
On iOS, this thread is officially
referred to as [the main thread][].
{{site.alert.end}}
### Using plugins and channels from background isolates
Plugins and channels can be used by any `Isolate`, but that `Isolate` has to be
a root `Isolate` (the one created by Flutter) or registered as a background
`Isolate` for a root `Isolate`.
The following example shows how to register a background `Isolate` in order to
use a plugin from a background `Isolate`.
```dart
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
void _isolateMain(RootIsolateToken rootIsolateToken) async {
BackgroundIsolateBinaryMessenger.ensureInitialized(rootIsolateToken);
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
print(sharedPreferences.getBool('isDebug'));
}
void main() {
RootIsolateToken rootIsolateToken = RootIsolateToken.instance!;
Isolate.spawn(_isolateMain, rootIsolateToken);
}
```
### Executing channel handlers on background threads
In order for a channel's platform side handler to
execute on a background thread, you must use the
Task Queue API. Currently this feature is only
supported on iOS and Android.
In Java:
```java
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
BinaryMessenger messenger = binding.getBinaryMessenger();
BinaryMessenger.TaskQueue taskQueue =
messenger.makeBackgroundTaskQueue();
channel =
new MethodChannel(
messenger,
"com.example.foo",
StandardMethodCodec.INSTANCE,
taskQueue);
channel.setMethodCallHandler(this);
}
```
In Kotlin:
```kotlin
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
val taskQueue =
flutterPluginBinding.binaryMessenger.makeBackgroundTaskQueue()
channel = MethodChannel(flutterPluginBinding.binaryMessenger,
"com.example.foo",
StandardMethodCodec.INSTANCE,
taskQueue)
channel.setMethodCallHandler(this)
}
```
In Swift:
{{site.alert.note}}
In release 2.10, the Task Queue API is only available on the `master` channel
for iOS.
{{site.alert.end}}
```swift
public static func register(with registrar: FlutterPluginRegistrar) {
let taskQueue = registrar.messenger.makeBackgroundTaskQueue()
let channel = FlutterMethodChannel(name: "com.example.foo",
binaryMessenger: registrar.messenger(),
codec: FlutterStandardMethodCodec.sharedInstance,
taskQueue: taskQueue)
let instance = MyPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
```
In Objective-C:
{{site.alert.note}}
In release 2.10, the Task Queue API is only available on the `master` channel
for iOS.
{{site.alert.end}}
```objc
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
NSObject<FlutterTaskQueue>* taskQueue =
[[registrar messenger] makeBackgroundTaskQueue];
FlutterMethodChannel* channel =
[FlutterMethodChannel methodChannelWithName:@"com.example.foo"
binaryMessenger:[registrar messenger]
codec:[FlutterStandardMethodCodec sharedInstance]
taskQueue:taskQueue];
MyPlugin* instance = [[MyPlugin alloc] init];
[registrar addMethodCallDelegate:instance channel:channel];
}
```
### Jumping to the UI thread in Android
To comply with channels' UI thread requirement,
you might need to jump from a background thread
to Android's UI thread to execute a channel method.
In Android, you can accomplish this by `post()`ing a
`Runnable` to Android's UI thread `Looper`,
which causes the `Runnable` to execute on the
main thread at the next opportunity.
In Java:
```java
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// Call the desired channel message here.
}
});
```
In Kotlin:
```kotlin
Handler(Looper.getMainLooper()).post {
// Call the desired channel message here.
}
```
### Jumping to the main thread in iOS
To comply with channel's main thread requirement,
you might need to jump from a background thread to
iOS's main thread to execute a channel method.
You can accomplish this in iOS by executing a
[block][] on the main [dispatch queue][]:
In Objective-C:
```objectivec
dispatch_async(dispatch_get_main_queue(), ^{
// Call the desired channel message here.
});
```
In Swift:
```swift
DispatchQueue.main.async {
// Call the desired channel message here.
}
```
[`BasicMessageChannel`]: {{site.api}}/flutter/services/BasicMessageChannel-class.html
[`BinaryCodec`]: {{site.api}}/flutter/services/BinaryCodec-class.html
[block]: {{site.apple-dev}}/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html
[`cloud_firestore`]: {{site.github}}/firebase/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore_platform_interface/lib/src/method_channel/utils/firestore_message_codec.dart
[`dart:html` library]: {{site.dart.api}}/dart-html/dart-html-library.html
[developing packages]: /packages-and-plugins/developing-packages
[plugins]: /packages-and-plugins/developing-packages#plugin
[dispatch queue]: {{site.apple-dev}}/documentation/dispatch/dispatchqueue
[`/examples/platform_channel/`]: {{site.repo.flutter}}/tree/main/examples/platform_channel
[`/examples/platform_channel_swift/`]: {{site.repo.flutter}}/tree/main/examples/platform_channel_swift
[JS interoperability]: {{site.dart-site}}/web/js-interop
[`JSONMessageCodec`]: {{site.api}}/flutter/services/JSONMessageCodec-class.html
[`MethodChannel`]: {{site.api}}/flutter/services/MethodChannel-class.html
[`MethodChannelAndroid`]: {{site.api}}/javadoc/io/flutter/plugin/common/MethodChannel.html
[`MethodChanneliOS`]: {{site.api}}/ios-embedder/interface_flutter_method_channel.html
[Platform adaptations]: /platform-integration/platform-adaptations
[publishing packages]: /packages-and-plugins/developing-packages#publish
[`quick_actions`]: {{site.pub}}/packages/quick_actions
[section on threading]: #channels-and-platform-threading
[`StandardMessageCodec`]: {{site.api}}/flutter/services/StandardMessageCodec-class.html
[`StringCodec`]: {{site.api}}/flutter/services/StringCodec-class.html
[the main thread]: {{site.apple-dev}}/documentation/uikit?language=objc
[the UI thread]: {{site.android-dev}}/guide/components/processes-and-threads#Threads
[sending structured typesafe messages]: #pigeon
| website/src/platform-integration/platform-channels.md/0 | {
"file_path": "website/src/platform-integration/platform-channels.md",
"repo_id": "website",
"token_count": 17760
} | 1,315 |
---
title: Displaying images on the web
short-title: Web images
description: Learn how to load and display images on the web.
---
The web supports the standard [`Image`][1] widget to display images.
However, because web browsers are built to run untrusted code safely,
there are certain limitations in what you can do with images compared
to mobile and desktop platforms. This page explains these limitations
and offers ways to work around them.
# Background
This section summarizes the technologies available
across Flutter and the web,
on which the solutions below are based on.
## Images in Flutter
Flutter offers the [`Image`][1] widget as well as the low-level
[`dart:ui/Image`][11] class for rendering images.
The `Image` widget has enough functionality for most use-cases.
The `dart:ui/Image` class can be used in
advanced situations where fine-grained control
of the image is needed.
## Images on the web
The web offers several methods for displaying images.
Below are some of the common ones:
- The built-in [`<img>`][2] and [`<picture>`][3] HTML elements.
- The [`drawImage`][4] method on the [`<canvas>`][5] element.
- Custom image codec that renders to a WebGL canvas.
Each option has its own benefits and drawbacks.
For example, the built-in elements fit nicely among
other HTML elements, and they automatically take
advantage of browser caching, and built-in image
optimization and memory management.
They allow you to safely display images from arbitrary sources
(more on than in the CORS section below).
`drawImage` is great when the image must fit within
other content rendered using the `<canvas>` element.
You also gain control over image sizing and,
when the CORS policy allows it, read the pixels
of the image back for further processing.
Finally, WebGL gives you the highest degree of
control over the image. Not only can you read the pixels and
apply custom image algorithms, but you can also use GLSL for
hardware-acceleration.
## Cross-Origin Resource Sharing (CORS)
[CORS][6] is a mechanism that browsers use to control
how one site accesses the resources of another site.
It is designed such that, by default, one web-site
is not allowed to make HTTP requests to another site
using [XHR][21] or [`fetch`][22].
This prevents scripts on another site from acting on behalf
of the user and from gaining access to another
site's resources without permission.
When using `<img>`, `<picture>`, or `<canvas>`,
the browser automatically blocks access to pixels
when it knows that an image is coming from another site
and the CORS policy disallows access to data.
WebGL requires access to the image data in order
to be able to render the image. Therefore,
images to be rendered using WebGL must only come from servers
that have a CORS policy configured to work with
the domain that serves your application.
## Flutter renderers on the web
Flutter offers a choice of two renderers on the web:
* **HTML**: this renderer uses a combination of HTML,
CSS, Canvas 2D, and SVG to render UI.
It uses the `<img>` element to render images.
* **CanvasKit**: this renderer uses WebGL to render UI,
and therefore requires
access to the pixels of the image.
Because the HTML renderer uses the `<img>`
element it can display images from
arbitrary sources. However,
this places the following limitations on what you
can do with them:
* Limited support for [`Image.toByteData`][7].
* No support for [`OffsetLayer.toImage`][8] and
[`Scene.toImage`][10].
* No access to frame data in animated images
([`Codec.getNextFrame`][9],
`frameCount` is always 1, `repetitionCount` is always 0).
* No support for `ImageShader`.
* Limited support for shader effects that can be applied to images.
* No control over image memory (`Image.dispose` has no effect).
The memory is managed by the browser behind-the-scenes.
The CanvasKit renderer implements Flutter's image API fully.
However, it requires access to image pixels to do so,
and is therefore subject to the CORS policy.
# Solutions
## In-memory, asset, and same-origin network images
If the app has the bytes of the encoded image in memory,
provided as an [asset][12], or stored on the
same server that serves the application
(also known as _same-origin_), no extra effort is necessary.
The image can be displayed using
[`Image.memory`][13], [`Image.asset`][14], and [`Image.network`][15]
in both HTML and CanvasKit modes.
## Cross-origin images
The HTML renderer can load cross-origin images
without extra configuration.
CanvasKit requires that the app gets the bytes of the encoded image.
There are several ways to do this, discussed below.
### Host your images in a CORS-enabled CDN.
Typically, content delivery networks (CDN)
can be configured to customize what domains
are allowed to access your content.
For example, Firebase site hosting allows
[specifying a custom][16] `Access-Control-Allow-Origin`
header in the `firebase.json` file.
### Lack control over the image server? Use a CORS proxy.
If the image server cannot be configured to allow CORS
requests from your application,
you might still be able to load images by proxying
the requests through another server. This requires that the
intermediate server has sufficient access to load the images.
This method can be used in situations when the original
image server serves images publicly,
but is not configured with the correct CORS headers.
Examples:
* Using [CloudFlare Workers][18].
* Using [Firebase Functions][19].
### Use `<img>` in a platform view.
Flutter supports embedding HTML inside the app using
[`HtmlElementView`][17]. Use it to create an `<img>`
element to render the image from another domain.
However, do keep in mind that this comes with the
limitations explained in the section
"Flutter renderers on the web" above.
[As of today][20], using too many HTML elements
with the CanvasKit renderer might hurt performance.
If images interleave non-image content Flutter needs to
create extra WebGL contexts between the `<img>` elements.
If your application needs to display a lot of images
on the same screen all at once, consider using
the HTML renderer instead of CanvasKit.
[1]: {{site.api}}/flutter/widgets/Image-class.html
[2]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
[3]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture
[4]: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
[5]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas
[6]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
[7]: {{site.api}}/flutter/dart-ui/Image/toByteData.html
[8]: {{site.api}}/flutter/rendering/OffsetLayer/toImage.html
[9]: {{site.api}}/flutter/dart-ui/Codec/getNextFrame.html
[10]: {{site.api}}/flutter/dart-ui/Scene/toImage.html
[11]: {{site.api}}/flutter/dart-ui/Image-class.html
[12]: /ui/assets/assets-and-images
[13]: {{site.api}}/flutter/widgets/Image/Image.memory.html
[14]: {{site.api}}/flutter/widgets/Image/Image.asset.html
[15]: {{site.api}}/flutter/widgets/Image/Image.network.html
[16]: {{site.firebase}}/docs/hosting/full-config#headers
[17]: {{site.api}}/flutter/widgets/HtmlElementView-class.html
[18]: https://developers.cloudflare.com/workers/examples/cors-header-proxy
[19]: {{site.github}}/7kfpun/cors-proxy
[20]: {{site.repo.flutter}}/issues/71884
[21]: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
[22]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
| website/src/platform-integration/web/web-images.md/0 | {
"file_path": "website/src/platform-integration/web/web-images.md",
"repo_id": "website",
"token_count": 2151
} | 1,316 |
---
title: Flutter SDK archive
short-title: Archive
description: "All current Flutter SDK releases: stable, beta, and master."
toc: false
---
<style>
.scrollable-table {
overflow-y: scroll;
max-height: 20rem;
}
</style>
The {{site.sdk.channel | capitalize }} channel contains the
most stable Flutter builds.
To learn more, check out [Flutter's channels][].
{% include docs/china-notice.md %}
To learn what's new in the major Flutter releases,
check out the [release notes][] page.
{{site.alert.secondary}}
**A note on provenance**: [provenance](https://slsa.dev/provenance)
describes how software artifacts are built, including
what the download contains and who created it.
To view provenance in a more readable format
and where nothing is downloaded, run the following
command using the provenance file URL from a release (you might need to
download [jq](https://stedolan.github.io/jq/) to easily parse the JSON).
```terminal
curl [provenance URL] | jq -r .payload | base64 -d | jq
```
{{site.alert.end}}
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="os-archive-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="windows-tab" href="#windows" role="tab" aria-controls="windows" aria-selected="true">Windows</a>
</li>
<li class="nav-item">
<a class="nav-link" id="macos-tab" href="#macos" role="tab" aria-controls="macos" aria-selected="false">macOS</a>
</li>
<li class="nav-item">
<a class="nav-link" id="linux-tab" href="#linux" role="tab" aria-controls="linux" aria-selected="false">Linux</a>
</li>
</ul>
{% comment %} Tab panes {% endcomment -%}
<div id="sdk-archives" class="tab-content">
{% include_relative _release_os.md os="Windows" %}
{% include_relative _release_os.md os="macOS" %}
{% include_relative _release_os.md os="Linux" %}
</div>
## Master channel
Installation bundles are not available for master.
However, you can get the SDK directly from
[GitHub repo][] by cloning the master channel,
and then triggering a download of the SDK dependencies:
```terminal
$ git clone -b master https://github.com/flutter/flutter.git
$ ./flutter/bin/flutter --version
```
For additional details on how our installation bundles are structured,
see [Installation bundles][].
[Flutter's channels]: {{site.repo.flutter}}/wiki/Flutter-build-release-channels
[release notes]: /release/release-notes
[GitHub repo]: {{site.repo.flutter}}
[Installation bundles]: {{site.repo.flutter}}/wiki/Flutter-Installation-Bundles
| website/src/release/archive.md/0 | {
"file_path": "website/src/release/archive.md",
"repo_id": "website",
"token_count": 826
} | 1,317 |
---
title: Android Java Gradle migration guide
description: >
How to migrate your Android app if you experience
a run or build error from Gradle.
---
## Summary
If you've recently upgraded Android Studio to the Flamingo
release and have either run or built an existing Android app,
you might have run into an error similar to the following:
{:width="80%"}
The terminal output for this error is
similar to the following:
```sh
FAILURE: Build failed with an exception.
* Where:
Build file '…/example/android/build.gradle'
* What went wrong:
Could not compile build file '…/example/android/build.gradle'.
> startup failed:
General error during conversion: Unsupported class file major version 61
java.lang.IllegalArgumentException: Unsupported class file major version 61
at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:189)
at groovyjarjarasm.asm.ClassReader.<init>(ClassReader.java:170)
[…
…
… 209 more lines of Groovy and Gradle stack trace …
…
…]
at java.base/java.lang.Thread.run(Thread.java:833)
```
This error occurs because Android Studio Flamingo
updates its bundled Java SDK from 11 to 17.
Flutter uses the version of Java bundled with
Android Studio to build Android apps.
Gradle versions [prior to 7.3][] can't run
when using Java 17.
**You can fix this error by upgrading your Gradle project
to a compatible version (7.3 through 7.6.1, inclusive)
using one of the following approaches.**
[prior to 7.3]: https://docs.gradle.org/current/userguide/compatibility.html#java
## Solution #1: Guided fix using Android Studio
Upgrade the Gradle version in Android Studio Flamingo
as follows:
1. In Android Studio, open the `android` folder.
This should bring up the following dialog:
{:width="50%"}
Update to a Gradle release between 7.3 through 7.6.1, inclusive.
1. Follow the guided workflow to update Gradle.
{:width="85%"}
## Solution #2: Manual fix at the command line
Do the following from the top of your Flutter project.
1. Go to the Android directory for your project.
```terminal
$ cd android
```
1. Update Gradle to the preferred version. Choose between 7.3 through 7.6.1, inclusive.
```terminal
$ ./gradlew wrapper --gradle-version=7.6.1
```
## Notes
A few notes to be aware of:
* Repeat this step for each affected Android app.
* This issue can be experienced by those who
_don't_ download Java and the Android SDK through
Android studio.
If you've manually upgraded your Java SDK to
version 17 but haven't upgraded Gradle, you can
also encounter this issue. The fix is the same:
upgrade Gradle to a release between 7.3 and 7.6.1.
* Your development machine _might_ contain more
than one copy of the Java SDK:
* The Android Studio app includes a version of Java,
which Flutter uses by default.
* If you don't have Android Studio installed,
Flutter relies on the version defined by your
shell script's `JAVA_HOME` environment variable.
* If `JAVA_HOME` isn't defined, Flutter looks
for any `java` executable in your path.
Once [issue 122609][] lands, the `flutter doctor`
command reports which version of Java is used.
* If you upgrade Gradle to a release _newer_ than 7.6.1,
you might (though it's unlikely) encounter issues
that result from changes to Gradle, such as
[deprecated Gradle classes][], or changes to the
Android file structure, such as
[splitting out ApplicationId from PackageName][].
If this occurs, downgrade to a release of Gradle
between 7.3 and 7.6.1, inclusive.
* Upgrading to Flutter 3.10 won't fix this issue.
[deprecated Gradle classes]: https://docs.gradle.org/7.6/javadoc/deprecated-list.html
[issue 122609]: {{site.repo.flutter}}/issues/122609
[splitting out ApplicationId from PackageName]: http://tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename
| website/src/release/breaking-changes/android-java-gradle-migration-guide.md/0 | {
"file_path": "website/src/release/breaking-changes/android-java-gradle-migration-guide.md",
"repo_id": "website",
"token_count": 1266
} | 1,318 |
---
title: Migration guide for describeEnum and EnumProperty
description: Learn about the removal of describeEnum and how to migrate.
---
## Summary
The global method `describeEnum` has been deprecated. Previous uses
of `describeEnum(Enum.something)` should use
`Enum.something.name` instead.
The class `EnumProperty` was modified to
extend `<T extends Enum?>` instead of `<T>`.
Existing uses of `EnumProperty<NotAnEnum>` should
use `DiagnosticsProperty<NotAnEnum>` instead.
## Context
Dart 2.17 introduced [enhanced enums][], which added `Enum` as a type.
As a result, all enums got a `name` getter, which made `describeEnum`
redundant. Before that, enum classes were often analyzed using an
`EnumProperty`.
The `describeEnum` method was used to convert an enum value to a string,
since `Enum.something.toString()` would produce `Enum.something` instead
of `something`, which a lot of users wanted. Now, the `name` getter does this.
The `describeEnum` function is being deprecated,
so the `EnumProperty` class is updated to only accept `Enum` objects.
[enhanced enums]: {{site.dart-site}}/language/enums#declaring-enhanced-enums
## Description of change
Remove `describeEnum`.
- Replace `describeEnum(Enum.something)` with `Enum.something.name`.
The `EnumProperty` now expects null or an `Enum`;
you can no longer pass it a non-`Enum` class.
## Migration guide
If you previously used `describeEnum(Enum.field)` to access the
string value from an enum, you can now call `Enum.field.name`.
If you previously used `EnumProperty<NotAnEnum>`, you can
now use the generic `DiagnosticsProperty<NotAnEnum>`.
Code before migration:
```dart
enum MyEnum { paper, rock }
print(describeEnum(MyEnum.paper)); // output: paper
// TextInputType is not an Enum
properties.add(EnumProperty<TextInputType>( ... ));
```
Code after migration:
```dart
enum MyEnum { paper, rock }
print(MyEnum.paper.name); // output: paper
// TextInputType is not an Enum
properties.add(DiagnosticsProperty<TextInputType>( ... ));
```
## Timeline
Landed in version: 3.14.0-2.0.pre<br>
In stable release: 3.16
## References
API documentation:
* [`describeEnum`][]
* [`EnumProperty`][]
Relevant issues:
* [Cleanup SemanticsFlag and SemanticsAction issue][]
Relevant PRs:
* [Deprecate `describeEnum` PR][]
[`describeEnum`]: {{site.api}}/flutter/lib/src/foundation/describeEnum.html
[`EnumProperty`]: {{site.api}}/flutter/lib/src/foundation/EnumProperty.html
[Cleanup SemanticsFlag and SemanticsAction issue]: {{site.repo.flutter}}/issues/123346
[Deprecate `describeEnum` PR]: {{site.repo.flutter}}/pull/125016
| website/src/release/breaking-changes/describe-enum.md/0 | {
"file_path": "website/src/release/breaking-changes/describe-enum.md",
"repo_id": "website",
"token_count": 866
} | 1,319 |
---
title: Migration guide for ignoringSemantics in IgnorePointer and related classes
description: Removal of ignoringSemantics in IgnorePointer and related classes.
---
## Summary
The `IgnoringPointer` widget allows you to designate an area of the UI
where you don't want to accept pointer events, for example, when
you don't want to allow the user to enter text in a text field.
Previously, the `IgnorePointer` not only blocked pointer events but also
dropped its subtree from the semantics tree. The `ignoreSemantics` parameter
was introduced as a workaround to preserve the semantics tree when using
`IgnorePointer`s.
The `IgnorePointer` behavior has changed in that it no longer drops
the entire semantics subtree but merely blocks semantics actions in the
subtree. The `ignoringSemantics` workaround is no longer needed and is
deprecated.
This change also applies to the `AbsorbPointer` and
`SliverIgnorePointer` widgets.
## Description of change
`ignoringSemantics` was removed.
## Migration guide
If you set this parameter to true in these widgets, consider using
`ExcludeSemantics` instead.
Code before migration:
```dart
IgnorePointer(
ignoringSemantics: true,
child: const PlaceHolder(),
);
AbsorbPointer(
ignoringSemantics: true,
child: const PlaceHolder(),
);
SliverIgnorePointer(
ignoringSemantics: true,
child: const PlaceHolder(),
);
```
Code after migration:
```dart
ExcludeSemantics(
child: IgnorePointer(
child: const PlaceHolder(),
),
);
ExcludeSemantics(
child: AbsorbPointer(
child: const PlaceHolder(),
),
);
SliverIgnorePointer(
child: ExcludeSemantics(
child: const PlaceHolder(),
),
);
```
If you are previously using `IgnorePointer`s with `ignoringSemantics` set to `false`,
you can achieve the same behavior by copying the follow widgets directly into your
code and use.
```dart
/// A widget ignores pointer events without modifying the semantics tree.
class _IgnorePointerWithSemantics extends SingleChildRenderObjectWidget {
const _IgnorePointerWithSemantics({
super.child,
});
@override
_RenderIgnorePointerWithSemantics createRenderObject(BuildContext context) {
return _RenderIgnorePointerWithSemantics();
}
}
class _RenderIgnorePointerWithSemantics extends RenderProxyBox {
_RenderIgnorePointerWithSemantics();
@override
bool hitTest(BoxHitTestResult result, { required Offset position }) => false;
}
/// A widget absorbs pointer events without modifying the semantics tree.
class _AbsorbPointerWithSemantics extends SingleChildRenderObjectWidget {
const _AbsorbPointerWithSemantics({
super.child,
});
@override
_RenderAbsorbPointerWithSemantics createRenderObject(BuildContext context) {
return _RenderAbsorbPointerWithSemantics();
}
}
class _RenderAbsorbPointerWithSemantics extends RenderProxyBox {
_RenderAbsorbPointerWithSemantics();
@override
bool hitTest(BoxHitTestResult result, { required Offset position }) {
return size.contains(position);
}
}
/// A sliver ignores pointer events without modifying the semantics tree.
class _SliverIgnorePointerWithSemantics extends SingleChildRenderObjectWidget {
const _SliverIgnorePointerWithSemantics({
super.child,
});
@override
_RenderSliverIgnorePointerWithSemantics createRenderObject(BuildContext context) {
return _RenderSliverIgnorePointerWithSemantics();
}
}
class _RenderSliverIgnorePointerWithSemantics extends RenderProxySliver {
_RenderSliverIgnorePointerWithSemantics();
@override
bool hitTest(BoxHitTestResult result, { required Offset position }) => false;
}
```
## Timeline
Landed in version: 3.10.0-2.0.pre<br>
In stable release: 3.13.0
## References
Relevant PRs:
* [PR 120619][]: Fixes IgnorePointer and AbsorbPointer to only block user
interactions in a11y.
[PR 120619]: {{site.repo.flutter}}/pull/120619
[`IgnorePointer`]: {{site.api}}/flutter/widgets/IgnorePointer-class.html
[`AbsorbPointer`]: {{site.api}}/flutter/widgets/AbsorbPointer-class.html
[`SliverIgnorePointer`]: {{site.api}}/flutter/widgets/SliverIgnorePointer-class.html
[`RenderSliverIgnorePointer`]: {{site.api}}/flutter/rendering/RenderSliverIgnorePointer-class.html
[`RenderIgnorePointer`]: {{site.api}}/flutter/rendering/RenderIgnorePointer-class.html
[`RenderAbsorbPointer`]: {{site.api}}/flutter/rendering/RenderAbsorbPointer-class.html
| website/src/release/breaking-changes/ignoringsemantics-migration.md/0 | {
"file_path": "website/src/release/breaking-changes/ignoringsemantics-migration.md",
"repo_id": "website",
"token_count": 1317
} | 1,320 |
---
title: Semantics Order of the Overlay Entries in Modal Routes
description: >
The scope of the modal route has a higher semantics
traverse order than its modal barrier.
---
## Summary
We changed the semantics traverse order of the overlay entries in modal routes.
Accessibility talk back or voice over now focuses the scope of a modal route
first instead of its modal barrier.
## Context
The modal route has two overlay entries, the scope and the modal barrier. The
scope is the actual content of the modal route, and the modal barrier is the
background of the route if its scope does not cover the entire screen. If the
modal route returns true for `barrierDismissible`, the modal barrier becomes
accessibility focusable because users can tap the modal barrier to pop the
modal route. This change specifically made the accessibility to focus the scope
first before the modal barrier.
## Description of change
We added additional semantics node above both
the overlay entries of modal routes.
Those semantics nodes denote the semantics
traverse order of these two overlay entries.
This also changed the structure of semantics tree.
## Migration guide
If your tests start failing due to semantics tree changes after the update,
you can migrate your code by expecting a new node on above of the modal route
overlay entries.
Code before migration:
```dart
import 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/material.dart';
void main() {
testWidgets('example test', (WidgetTester tester) async {
final SemanticsHandle handle =
tester.binding.pipelineOwner.ensureSemantics();
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(home: Scaffold(body: Text('test'))));
final SemanticsNode root =
tester.binding.pipelineOwner.semanticsOwner.rootSemanticsNode;
final SemanticsNode firstNode = getChild(root);
expect(firstNode.rect, Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
// Fixes the test by expecting an additional node above the scope route.
final SemanticsNode secondNode = getChild(firstNode);
expect(secondNode.rect, Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
final SemanticsNode thirdNode = getChild(secondNode);
expect(thirdNode.rect, Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
expect(thirdNode.hasFlag(SemanticsFlag.scopesRoute), true);
final SemanticsNode forthNode = getChild(thirdNode);
expect(forthNode.rect, Rect.fromLTRB(0.0, 0.0, 56.0, 14.0));
expect(forthNode.label, 'test');
handle.dispose();
});
}
SemanticsNode getChild(SemanticsNode node) {
SemanticsNode child;
bool visiter(SemanticsNode target) {
child = target;
return false;
}
node.visitChildren(visiter);
return child;
}
```
Code after migration:
```dart
import 'dart:ui';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/material.dart';
void main() {
testWidgets('example test', (WidgetTester tester) async {
final SemanticsHandle handle =
tester.binding.pipelineOwner.ensureSemantics();
// Build our app and trigger a frame.
await tester.pumpWidget(MaterialApp(home: Scaffold(body: Text('test'))));
final SemanticsNode root =
tester.binding.pipelineOwner.semanticsOwner.rootSemanticsNode;
final SemanticsNode firstNode = getChild(root);
expect(firstNode.rect, Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
// Fixes the test by expecting an additional node above the scope route.
final SemanticsNode secondNode = getChild(firstNode);
expect(secondNode.rect, Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
final SemanticsNode thirdNode = getChild(secondNode);
expect(thirdNode.rect, Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
expect(thirdNode.hasFlag(SemanticsFlag.scopesRoute), true);
final SemanticsNode forthNode = getChild(thirdNode);
expect(forthNode.rect, Rect.fromLTRB(0.0, 0.0, 56.0, 14.0));
expect(forthNode.label, 'test');
handle.dispose();
});
}
SemanticsNode getChild(SemanticsNode node) {
SemanticsNode child;
bool visiter(SemanticsNode target) {
child = target;
return false;
}
node.visitChildren(visiter);
return child;
}
```
## Timeline
Landed in version: 1.19.0<br>
In stable release: 1.20
## References
API documentation:
* [`ModalRoute`][]
* [`OverlayEntry`][]
Relevant issue:
* [Issue 46625][]
Relevant PR:
* [PR 59290][]
[`ModalRoute`]: {{site.api}}/flutter/widgets/ModalRoute-class.html
[`OverlayEntry`]: {{site.api}}/flutter/widgets/OverlayEntry-class.html
[Issue 46625]: {{site.repo.flutter}}/issues/46625
[PR 59290]: {{site.repo.flutter}}/pull/59290
| website/src/release/breaking-changes/modal-router-semantics-order.md/0 | {
"file_path": "website/src/release/breaking-changes/modal-router-semantics-order.md",
"repo_id": "website",
"token_count": 1585
} | 1,321 |
---
title: Dry layout support for RenderBox
description: >
The method "computeDryLayout" was added to the RenderBox protocol to
correctly calculate its intrinsic size in certain situations.
---
## Summary
A new method named `computeDryLayout` was added to the `RenderBox` protocol.
Subclasses of `RenderBox` are expected to implement it to correctly report
their desired size given a set of `BoxConstraints` during intrinsic
calculations. Subclasses that implement `computeDryLayout` no longer need to
override `performResize`.
## Context
A new method, `computeDryLayout`, was added to the `RenderBox` protocol to
correctly calculate the intrinsic sizes of a `RenderParagraph` with `WidgetSpan`
children and a `RenderWrap`. The method receives a set of `BoxConstraints` and
is expected to calculate the resulting size of the `RenderBox` without changing
any internal state. It's essentially a dry run of `performLayout` that only
calculates the resulting size and doesn't place the children. The
`computeDryLayout` method is part of the intrinsics protocol (see also
[`RenderBox.computeMinIntrinsicWidth`][] and friends).
## Description of change
Subclasses of `RenderBox` need to override the new `computeDryLayout` method
if they are used as a descendant of a `RenderObject` that may query the intrinsic
size of its children. Examples of widgets that do this are `IntrinsicHeight`
and `IntrinsicWidth`.
The default implementation of `RenderBox.performResize` also uses the size
computed by `computeDryLayout` to perform the resize. Overriding `performResize`
is therefore no longer necessary.
## Migration guide
Subclasses that already override `performResize` can be migrated by simply
changing the function signature from `void performResize()` to
`Size computeDryLayout(BoxConstraints constraints)` and by returning the
calculated size instead of assigning it to the `size` setter. The old
implementation of `performResize` can be removed.
Code before migration:
```dart
@override
void performResize() {
size = constraints.biggest;
}
```
Code after migration:
```dart
// This replaces the old performResize method.
@override
Size computeDryLayout(BoxConstraints constraints) {
return constraints.biggest;
}
```
If the subclass doesn't override `performResize`, the implementation of
`computeDryLayout` has to be extracted from the `performLayout` method.
Basically, `computeDryLayout` needs to do all the work `performLayout` is doing
to figure out the size of the `RenderBox`. However, instead of assigning it
to the `size` setter, it returns the computed size. If `computeDryLayout`
needs to know the size of its children, it must obtain that size by calling
`getDryLayout` on the child instead of calling `layout`.
If for some reason it is impossible to calculate the dry layout, `computeDryLayout`
must call `debugCannotComputeDryLayout` from within an assert and return a dummy
size of `const Size(0, 0)`. Calculating a dry layout is, for example, impossible
if the size of a `RenderBox` depends on the baseline metrics of its children.
```dart
@override
Size computeDryLayout(BoxConstraints constraints) {
assert(debugCannotComputeDryLayout(
reason: 'Layout requires baseline metrics, which are only available after a full layout.'
));
return const Size(0, 0);
}
```
## Timeline
Landed in version: 1.25.0-4.0.pre<br>
In stable release: 2.0.0
## References
API documentation:
* [`RenderBox`][]
* [`computeMinInstrinsicWidth`][]
* [`computeDryLayout`][]
* [`getDryLayout`][]
* [`performResize`][]
* [`RenderWrap`][]
* [`RenderParagraph`][]
Relevant issues:
* [Issue 48679][]
Relevant PRs:
* [Fixes Intrinsics for RenderParagraph and RenderWrap][]
[`RenderBox`]: {{site.api}}/flutter/rendering/RenderBox-class.html
[`RenderBox.computeMinIntrinsicWidth`]: {{site.api}}/flutter/rendering/RenderBox/computeMinIntrinsicWidth.html
[`computeMinInstrinsicWidth`]: {{site.api}}/flutter/rendering/RenderBox/computeMinIntrinsicWidth.html
[`computeDryLayout`]: {{site.api}}/flutter/rendering/RenderBox/computeDryLayout.html
[`getDryLayout`]: {{site.api}}/flutter/rendering/RenderBox/getDryLayout.html
[`performResize`]: {{site.api}}/flutter/rendering/RenderBox/performResize.html
[`RenderWrap`]: {{site.api}}/flutter/rendering/RenderWrap-class.html
[`RenderParagraph`]: {{site.api}}/flutter/rendering/RenderParagraph-class.html
[Issue 48679]: {{site.repo.flutter}}/issues/48679
[Fixes Intrinsics for RenderParagraph and RenderWrap]: {{site.repo.flutter}}/pull/70656
| website/src/release/breaking-changes/renderbox-dry-layout.md/0 | {
"file_path": "website/src/release/breaking-changes/renderbox-dry-layout.md",
"repo_id": "website",
"token_count": 1387
} | 1,322 |
---
title: Replace with title of breaking change
description: >-
Brief description similar to the "context" section below.
Text should break at 80 chars or less.
---
{% comment %}
PLEASE READ THESE GENERAL INSTRUCTIONS:
* All lines of text should be 80 chars OR LESS.
The writers strongly prefer semantic line breaks:
https://github.com/dart-lang/site-shared/blob/main/doc/writing-for-dart-and-flutter-websites.md#semantic-line-breaks
* DON'T SUBMIT a PR weeks and weeks in advance.
Doing this causes it to get stanky in the website
repo and usually develops conflicts in the index file.
Ideally, submit a PR once you have confirmed
info on the version number where the breaking
change landed.
* One of the most important things to fill out
in this template is the *Timeline* section.
I won't approve/merge the PR until the "landed in"
release info is provided. For example:
`Landed in version: 1.21.0-5.0.pre<br>`.
Do NOT list the PR in this section. Also, don't
fill in the "stable" release info unless it's
already in a published stable release.
After a stable release, I go through and confirm
that updates have made it to stable and I then
update the breaking change and the index file.
* The text in this page should be backwards looking,
so write about previous behavior in past tense,
not future tense. People are reading this months
from now when the change is likely in the stable
release, not today. Don't say "in a month" or
talk about your plan to do something next week.
Assume you've done it, and that they're looking
back to figure out how to migrate their code.
* Use sentence case for headings and titles.
(`## Migration guide`, NOT `Migration Guide`)
* DON'T use the abbreviation `i.e.` or `e.g.`.
Use "for example" or "such as", and similar.
* For links, use the macros where possible.
See the examples at the end of this template,
but don't use "github.com" or "api.flutter.dev" or
"pub.dev" in your URLs. Use the {{site.github}},
{{site.api}}, or {{site.pub}} macros.
* AVOID "will" when possible, in other words,
stay in the present tense. For example:
Bad: "When encountering an xxx value,
the code will throw an exception."
Good: "When encountering an xxx value,
the code throws an exception."
Good use of "will": "In release 2.0, the xxx API
will be deprecated."
* Finally, delete the comment tags and text from the
final PR.
{% endcomment %}
## Summary
{% comment %}
A brief (one- to three-line) summary that gives
context as to what changed so that someone can
find it when browsing through an index of
breaking changes, ideally using keywords from
the symptoms you would see if you had not yet
migrated (for example, the text from probable
error messages).
{% endcomment %}
## Background
{% comment %}
High-level description of what API changed and why.
Should be clear enough to be understandable to someone
who has no context about this breaking change,
such as someone who doesn't know the underlying API.
This section should also answer the question
"what is the problem that led to considering making
a breaking change?"
Include a technical description of the actual change,
with code samples showing how the API changed.
Include examples of the error messages that are produced
in code that has not been migrated. This helps the search
engine find the migration guide when people search for those
error messages. THIS IS VERY IMPORTANT FOR DISCOVERY!
{% endcomment %}
## Migration guide
{% comment %}
A description of how to make the change.
If a migration tool is available,
discuss it here. Even if there is a tool,
a description of how to make the change manually
must be provided. This section needs before and
after code examples that are relevant to the
developer.
{% endcomment %}
Code before migration:
```dart
// Example of code before the change.
```
Code after migration:
```dart
// Example of code after the change.
```
{% comment %}
Make sure you have looked for old tutorials online that
use the old API. Contact their authors and point out how
they should be updated. Leave a comment pointing out that
the API has changed and linking to this guide.
{% endcomment %}
## Timeline
{% comment %}
The version # of the SDK where this change was
introduced. If there is a deprecation window,
the version # to which we guarantee to maintain
the old API. Use the following template:
If a breaking change has been reverted in a
subsequent release, move that item to the
"Reverted" section of the index.md file.
Also add the "Reverted in version" line,
shown as optional below. Otherwise, delete
that line.
{% endcomment %}
Landed in version: xxx<br>
In stable release: not yet
Reverted in version: xxx (OPTIONAL, delete if not used)
## References
{% comment %}
These links are commented out because they
cause the GitHubActions (GHA) linkcheck to fail.
Remove the comment tags once you fill this in with
real links. Only use the "main-api" include if
you link to "main-api.flutter.dev"; prefer our
stable documentation if possible.
{% include docs/main-api.md %}
API documentation:
* [`ClassName`][]
Relevant issues:
* [Issue xxxx][]
* [Issue yyyy][]
Relevant PRs:
* [PR title #1][]
* [PR title #2][]
{% endcomment %}
{% comment %}
Add the links to the end of the file in alphabetical order.
The following links are commented out because they make
the GitHubActions (GHA) link checker believe they are broken links,
but please remove the comment tags before you commit!
If you are sharing new API that hasn't landed in
the stable channel yet, use the main channel link.
To link to docs on the main channel,
include the following note and make sure that
the URL includes the main link (as shown below).
Here's an example of defining a stable (site.api) link
and a main channel (main-api) link.
<!-- Stable channel link: -->
[`ClassName`]: {{site.api}}/flutter/[link_to_relevant_page].html
<!-- Master channel link: -->
{% include docs/main-api.md %}
[`ClassName`]: {{site.main-api}}/flutter/[link_to_relevant_page].html
[Issue xxxx]: {{site.repo.flutter}}/issues/[link_to_actual_issue]
[Issue yyyy]: {{site.repo.flutter}}/issues/[link_to_actual_issue]
[PR title #1]: {{site.repo.flutter}}/pull/[link_to_actual_pr]
[PR title #2]: {{site.repo.flutter}}/pull/[link_to_actual_pr]
{% endcomment %}
| website/src/release/breaking-changes/template.md/0 | {
"file_path": "website/src/release/breaking-changes/template.md",
"repo_id": "website",
"token_count": 1972
} | 1,323 |
---
title: Migrate a Windows project to ensure the window is shown
description: How to update a Windows project to ensure the window is shown
---
Flutter 3.13 fixed a [bug][] that could result in the window not being shown.
Windows projects created using Flutter 3.7 or Flutter 3.10 need to be migrated
to fix this issue.
[bug]: {{site.repo.flutter}}/issues/119415
## Migration steps
Verify you are on Flutter version 3.13 or newer using `flutter --version`.
If needed, use `flutter upgrade` to update to the latest version of the
Flutter SDK.
Projects that have not modified their `windows/runner/flutter_window.cpp` file
will be migrated automatically by `flutter run` or `flutter build windows`.
Projects that have modified their `windows/runner/flutter_window.cpp` file might
need to migrate manually.
Code before migration:
```cpp
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
```
Code after migration:
```cpp
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
```
## Example
[PR 995][] shows the migration work for the
[Flutter Gallery][] app.
[PR 995]: {{site.repo.gallery-archive}}/pull/995/files
[Flutter Gallery]: {{site.gallery-archive}} | website/src/release/breaking-changes/windows-show-window-migration.md/0 | {
"file_path": "website/src/release/breaking-changes/windows-show-window-migration.md",
"repo_id": "website",
"token_count": 428
} | 1,324 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.