text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.example.androidfullscreen
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| samples/add_to_app/fullscreen/android_fullscreen/app/src/test/java/dev/flutter/example/androidfullscreen/ExampleUnitTest.kt/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/test/java/dev/flutter/example/androidfullscreen/ExampleUnitTest.kt",
"repo_id": "samples",
"token_count": 165
} | 1,286 |
package dev.flutter.multipleflutters
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
/**
* The activity that uses standard platform UI APIs.
*
* This doesn't talk directly to or render Flutter content and represents a part of your app that
* would potentially already be written that wants to interface with Flutter.
*/
class MainActivity : AppCompatActivity(), DataModelObserver {
private lateinit var countView: TextView
private val mainActivityIdentifier: Int
private companion object {
/** A count that makes every other MainActivity have 1 or 2 Flutter instances. */
var mainActivityCount = 0
}
init {
mainActivityIdentifier = mainActivityCount
mainActivityCount += 1
}
/** Implemented from AppCompactActivity. */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
DataModel.instance.addObserver(this)
countView = findViewById(R.id.count)
countView.text = DataModel.instance.counter.toString()
}
/** Implemented from AppCompactActivity. */
override fun onDestroy() {
super.onDestroy()
DataModel.instance.removeObserver(this)
}
/** Event from `activity_main.xml`. */
fun onClickNext(view: View) {
val nextClass =
if (mainActivityIdentifier % 2 == 0) SingleFlutterActivity::class.java else DoubleFlutterActivity::class.java
val flutterIntent = Intent(this, nextClass)
startActivity(flutterIntent)
}
/** Event from `activity_main.xml`. */
fun onClickAdd(view: View) {
DataModel.instance.counter = DataModel.instance.counter + 1
}
/** Implemented from DataModelObserver. */
override fun onCountUpdate(newCount: Int) {
countView.text = newCount.toString()
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/MainActivity.kt/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/MainActivity.kt",
"repo_id": "samples",
"token_count": 679
} | 1,287 |
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:MultipleFluttersIos.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos.xcworkspace/contents.xcworkspacedata/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/MultipleFluttersIos.xcworkspace/contents.xcworkspacedata",
"repo_id": "samples",
"token_count": 107
} | 1,288 |
package dev.flutter.example.androidusingprebuiltmodule
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| samples/add_to_app/prebuilt_module/android_using_prebuilt_module/app/src/test/java/dev/flutter/example/androidusingprebuiltmodule/ExampleUnitTest.kt/0 | {
"file_path": "samples/add_to_app/prebuilt_module/android_using_prebuilt_module/app/src/test/java/dev/flutter/example/androidusingprebuiltmodule/ExampleUnitTest.kt",
"repo_id": "samples",
"token_count": 125
} | 1,289 |
// 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:math';
import 'package:flutter/material.dart';
class AnimatedPositionedDemo extends StatefulWidget {
const AnimatedPositionedDemo({super.key});
static String routeName = 'misc/animated_positioned';
@override
State<AnimatedPositionedDemo> createState() => _AnimatedPositionedDemoState();
}
class _AnimatedPositionedDemoState extends State<AnimatedPositionedDemo> {
late double topPosition;
late double leftPosition;
double generateTopPosition(double top) => Random().nextDouble() * top;
double generateLeftPosition(double left) => Random().nextDouble() * left;
@override
void initState() {
super.initState();
topPosition = generateTopPosition(30);
leftPosition = generateLeftPosition(30);
}
void changePosition(double top, double left) {
setState(() {
topPosition = generateTopPosition(top);
leftPosition = generateLeftPosition(left);
});
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final appBar = AppBar(title: const Text('AnimatedPositioned'));
final topPadding = MediaQuery.of(context).padding.top;
// AnimatedPositioned animates changes to a widget's position within a Stack
return Scaffold(
appBar: appBar,
body: SizedBox(
height: size.height,
width: size.width,
child: Stack(
children: [
AnimatedPositioned(
top: topPosition,
left: leftPosition,
duration: const Duration(seconds: 1),
child: InkWell(
onTap: () => changePosition(
size.height -
(appBar.preferredSize.height + topPadding + 50),
size.width - 150),
child: Container(
alignment: Alignment.center,
width: 150,
height: 50,
color: Theme.of(context).primaryColor,
child: Text(
'Click Me',
style: TextStyle(
color:
Theme.of(context).buttonTheme.colorScheme!.onPrimary,
),
),
),
),
),
],
),
),
);
}
}
| samples/animations/lib/src/misc/animated_positioned.dart/0 | {
"file_path": "samples/animations/lib/src/misc/animated_positioned.dart",
"repo_id": "samples",
"token_count": 1087
} | 1,290 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/code_sharing/client/android/gradle.properties/0 | {
"file_path": "samples/code_sharing/client/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,291 |
name: client
description: A Flutter app which communicates with a Dart backend using shared business logic.
publish_to: "none"
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
cupertino_icons: ^1.0.2
flutter:
sdk: flutter
http: ^1.0.0
shared:
path: ../shared
dev_dependencies:
flutter_lints: ^3.0.0
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| samples/code_sharing/client/pubspec.yaml/0 | {
"file_path": "samples/code_sharing/client/pubspec.yaml",
"repo_id": "samples",
"token_count": 163
} | 1,292 |
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.
include: package:lints/recommended.yaml
# Uncomment the following section to specify additional rules.
# linter:
# rules:
# - camel_case_types
# analyzer:
# exclude:
# - path/to/excluded/files/**
# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options
| samples/code_sharing/server/analysis_options.yaml/0 | {
"file_path": "samples/code_sharing/server/analysis_options.yaml",
"repo_id": "samples",
"token_count": 297
} | 1,293 |
# Custom Context Menus
This sample shows how to create and customize cross-platform context menus,
such as the text selection toolbar on mobile or the right click menu on desktop.
|  |  |  |  |
| --- | --- | --- | --- |
## Running the sample
Just run `flutter run` in the same directory as this README file.
## The examples
### [Anywhere](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/anywhere_page.dart)
Shows how to create a context menu in the parts of an app that don't related to
text selection. For example, a menu in a desktop app that shows when the
background of the app is right clicked.
### [Cascading menus](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/cascading_menu_page.dart)
Shows how to create a context menu with cascading submenus using
[SubmenuButton](https://master-api.flutter.dev/flutter/material/SubmenuButton-class.html).
### [Custom buttons](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/custom_buttons_page.dart)
Shows how to customize the default buttons in the existing context menus.
### [Custom menu](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/custom_menu_page.dart)
Shows how to use any custom widgets as the menu itself, including the option to
keep the default buttons.
### [Default values](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/default_values_page.dart)
Demonstrates how the
[contextMenuBuilder](https://master-api.flutter.dev/flutter/material/TextField/contextMenuBuilder.html)
property works with various possible values.
### [Email button](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/email_button_page.dart)
Shows how to create an "email" button in the default context menu that shows
only when an email address is selected.
### [Field types](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/field_types_page.dart)
Shows how context menus work in the various different field widgets:
EditableText, TextField, and CupertinoTextField.
### [Global selection](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/global_selection_page.dart)
Shows how to create a custom context menu in non-editable selection with
[SelectionArea](https://master-api.flutter.dev/flutter/material/SelectionArea-class.html).
### [On a widget](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/image_page.dart)
Shows how to make a widget show a context menu on right click or long press, in
this case an Image widget.
### [Modified action](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/modified_action_page.dart)
Shows how to modify an existing button so that a custom action is performed when
it is tapped.
### [Reordered buttons](https://github.com/flutter/samples/blob/main/experimental/context_menus/lib/reordered_buttons_page.dart)
Shows how to change the order of the default buttons.
| samples/context_menus/README.md/0 | {
"file_path": "samples/context_menus/README.md",
"repo_id": "samples",
"token_count": 1065
} | 1,294 |
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
typedef ContextMenuBuilder = Widget Function(
BuildContext context, Offset offset);
/// Shows and hides the context menu based on user gestures.
///
/// By default, shows the menu on right clicks and long presses.
class ContextMenuRegion extends StatefulWidget {
/// Creates an instance of [ContextMenuRegion].
const ContextMenuRegion({
super.key,
required this.child,
required this.contextMenuBuilder,
});
/// Builds the context menu.
final ContextMenuBuilder contextMenuBuilder;
/// The child widget that will be listened to for gestures.
final Widget child;
@override
State<ContextMenuRegion> createState() => _ContextMenuRegionState();
}
class _ContextMenuRegionState extends State<ContextMenuRegion> {
Offset? _longPressOffset;
final ContextMenuController _contextMenuController = ContextMenuController();
static bool get _longPressEnabled {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
return true;
case TargetPlatform.macOS:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return false;
}
}
void _onSecondaryTapUp(TapUpDetails details) {
_show(details.globalPosition);
}
void _onTap() {
if (!_contextMenuController.isShown) {
return;
}
_hide();
}
void _onLongPressStart(LongPressStartDetails details) {
_longPressOffset = details.globalPosition;
}
void _onLongPress() {
assert(_longPressOffset != null);
_show(_longPressOffset!);
_longPressOffset = null;
}
void _show(Offset position) {
_contextMenuController.show(
context: context,
contextMenuBuilder: (context) {
return widget.contextMenuBuilder(context, position);
},
);
}
void _hide() {
_contextMenuController.remove();
}
@override
void dispose() {
_hide();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onSecondaryTapUp: _onSecondaryTapUp,
onTap: _onTap,
onLongPress: _longPressEnabled ? _onLongPress : null,
onLongPressStart: _longPressEnabled ? _onLongPressStart : null,
child: widget.child,
);
}
}
| samples/context_menus/lib/context_menu_region.dart/0 | {
"file_path": "samples/context_menus/lib/context_menu_region.dart",
"repo_id": "samples",
"token_count": 805
} | 1,295 |
import 'package:context_menus/global_selection_page.dart';
import 'package:context_menus/main.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Gives correct behavior for all values of contextMenuBuilder',
(tester) async {
await tester.pumpWidget(const MyApp());
// Navigate to the GlobalSelectionPage example.
await tester.dragUntilVisible(
find.text(GlobalSelectionPage.title),
find.byType(ListView),
const Offset(0.0, -100.0),
);
await tester.pumpAndSettle();
await tester.tap(find.text(GlobalSelectionPage.title));
await tester.pumpAndSettle();
expect(
find.descendant(
of: find.byType(AppBar),
matching: find.text(GlobalSelectionPage.title),
),
findsOneWidget,
);
// Right click on the plain Text widget.
TestGesture gesture = await tester.startGesture(
tester.getCenter(find.descendant(
of: find.byType(ListView),
matching: find.byType(Text),
)),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture.up();
await gesture.removePointer();
await tester.pumpAndSettle();
// The default context menu is shown with a custom button.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
expect(find.text('Back'), findsOneWidget);
});
}
| samples/context_menus/test/global_selection_page_test.dart/0 | {
"file_path": "samples/context_menus/test/global_selection_page_test.dart",
"repo_id": "samples",
"token_count": 574
} | 1,296 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/deeplink_store_example/android/gradle.properties/0 | {
"file_path": "samples/deeplink_store_example/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,297 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/deeplink_store_example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/deeplink_store_example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,298 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import '../serializers.dart';
part 'current_user_collections.g.dart';
abstract class CurrentUserCollections
implements Built<CurrentUserCollections, CurrentUserCollectionsBuilder> {
factory CurrentUserCollections(
[void Function(CurrentUserCollectionsBuilder)? updates]) =
_$CurrentUserCollections;
CurrentUserCollections._();
@BuiltValueField(wireName: 'id')
int get id;
@BuiltValueField(wireName: 'title')
String? get title;
@BuiltValueField(wireName: 'published_at')
String? get publishedAt;
@BuiltValueField(wireName: 'updated_at')
String? get updatedAt;
String toJson() {
return json.encode(
serializers.serializeWith(CurrentUserCollections.serializer, this));
}
static CurrentUserCollections? fromJson(String jsonString) {
return serializers.deserializeWith(
CurrentUserCollections.serializer, json.decode(jsonString));
}
static Serializer<CurrentUserCollections> get serializer =>
_$currentUserCollectionsSerializer;
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/current_user_collections.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/current_user_collections.dart",
"repo_id": "samples",
"token_count": 410
} | 1,299 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
import 'api_error.dart';
import 'photo.dart';
import 'search_photos_response.dart';
final _unsplashBaseUrl = Uri.parse('https://api.unsplash.com/');
/// Unsplash API Client. Requires an
/// [Unsplash API](https://unsplash.com/developers) `accessKey` to make
/// requests to the Unsplash API.
class Unsplash {
Unsplash({
required String accessKey,
http.BaseClient? httpClient,
}) : _accessKey = accessKey,
_client = httpClient ?? http.Client();
final String _accessKey;
final http.Client _client;
final _log = Logger('Unsplash');
Future<SearchPhotosResponse?> searchPhotos({
required String query,
num page = 1,
num perPage = 10,
List<num> collections = const [],
SearchPhotosOrientation? orientation,
}) async {
final searchPhotosUrl = _unsplashBaseUrl
.replace(path: '/search/photos', queryParameters: <String, String>{
'query': query,
if (page != 1) 'page': '$page',
if (perPage != 10) 'per_page': '$perPage',
if (collections.isNotEmpty) 'collections': collections.join(','),
if (orientation == SearchPhotosOrientation.landscape)
'orientation': 'landscape',
if (orientation == SearchPhotosOrientation.portrait)
'orientation': 'portrait',
if (orientation == SearchPhotosOrientation.squarish)
'orientation': 'squarish',
});
_log.info('GET $searchPhotosUrl');
final response = await _client.get(
searchPhotosUrl,
headers: {
'Accept-Version': 'v1',
'Authorization': 'Client-ID $_accessKey',
},
);
dynamic body;
try {
body = json.fuse(utf8).decode(response.bodyBytes);
} catch (e) {
throw UnsplashException('Invalid JSON received');
}
if (body is Map &&
body['errors'] is List &&
body['errors'].isNotEmpty as bool) {
final apiError = ApiError.fromJson(response.body)!;
throw UnsplashException(apiError.errors!.join(', '));
}
return SearchPhotosResponse.fromJson(json.encode(body));
}
Future<Uint8List> download(Photo photo) async {
// For detail on how downloading photos from Unsplash, please see
// https://help.unsplash.com/en/articles/2511258-guideline-triggering-a-download
_log.info('GET ${photo.urls!.full}');
final futureBytes = http.readBytes(Uri.parse(photo.urls!.full!), headers: {
'Accept-Version': 'v1',
'Authorization': 'Client-ID $_accessKey',
});
_log.info('GET ${photo.links!.downloadLocation}');
unawaited(http.get(Uri.parse(photo.links!.downloadLocation!), headers: {
'Accept-Version': 'v1',
'Authorization': 'Client-ID $_accessKey',
}));
return futureBytes;
}
}
enum SearchPhotosOrientation {
landscape,
portrait,
squarish,
}
class UnsplashException implements Exception {
UnsplashException([this.message]);
final String? message;
@override
String toString() {
if (message == null) {
return 'UnsplashException';
}
return 'UnsplashException: $message';
}
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/unsplash.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/unsplash.dart",
"repo_id": "samples",
"token_count": 1244
} | 1,300 |
name: federated_plugin_macos
description: macOS implementation of federated_plugin to retrieve current battery level.
version: 0.0.1
homepage:
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
flutter:
plugin:
platforms:
macos:
pluginClass: FederatedPluginMacosPlugin
| samples/experimental/federated_plugin/federated_plugin_macos/pubspec.yaml/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_macos/pubspec.yaml",
"repo_id": "samples",
"token_count": 157
} | 1,301 |
<!-- This file is necessary just to run the e2e tests on the browser -->
<!DOCTYPE HTML>
<html>
<head>
<title>Browser Tests</title>
</head>
<body>
<script src="main.dart.js"></script>
</body>
</html>
| samples/experimental/federated_plugin/federated_plugin_web/web/index.html/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_web/web/index.html",
"repo_id": "samples",
"token_count": 85
} | 1,302 |
// Copyright 2021 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:adaptive_breakpoints/adaptive_breakpoints.dart';
import 'package:flutter/material.dart';
/// Returns a boolean value whether the window is considered medium or large size.
/// Used to build adaptive and responsive layouts.
bool isDisplayLarge(BuildContext context) =>
getWindowType(context) >= AdaptiveWindowType.medium;
/// Returns boolean value whether the window is considered medium size.
/// Used to build adaptive and responsive layouts.
bool isDisplayMedium(BuildContext context) =>
getWindowType(context) == AdaptiveWindowType.medium;
/// Returns boolean value whether the window is considered small size.
/// Used to build adaptive and responsive layouts.
bool isDisplaySmall(BuildContext context) =>
getWindowType(context) <= AdaptiveWindowType.small;
| samples/experimental/linting_tool/lib/layout/adaptive.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/layout/adaptive.dart",
"repo_id": "samples",
"token_count": 237
} | 1,303 |
// Copyright 2021 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:http/http.dart' as http;
import 'package:linting_tool/model/rule.dart';
import 'package:linting_tool/repository/api_provider.dart';
import 'package:yaml/yaml.dart';
class Repository {
final APIProvider _apiProvider;
Repository(http.Client httpClient) : _apiProvider = APIProvider(httpClient);
Future<List<Rule>> getRulesList() => _apiProvider.getRulesList();
Future<YamlMap> getTemplateFile() => _apiProvider.getTemplateFile();
}
| samples/experimental/linting_tool/lib/repository/repository.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/repository/repository.dart",
"repo_id": "samples",
"token_count": 193
} | 1,304 |
rootProject.name = 'pedometer'
| samples/experimental/pedometer/android/settings.gradle/0 | {
"file_path": "samples/experimental/pedometer/android/settings.gradle",
"repo_id": "samples",
"token_count": 10
} | 1,305 |
#import "GeneratedPluginRegistrant.h"
| samples/experimental/pedometer/example/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/experimental/pedometer/example/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,306 |
// Copyright (c) 2011, 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.
#ifndef RUNTIME_INCLUDE_DART_TOOLS_API_H_
#define RUNTIME_INCLUDE_DART_TOOLS_API_H_
#include "dart_api.h" /* NOLINT */
/** \mainpage Dart Tools Embedding API Reference
*
* This reference describes the Dart embedding API for tools. Tools include
* a debugger, service protocol, and timeline.
*
* NOTE: The APIs described in this file are unstable and subject to change.
*
* This reference is generated from the header include/dart_tools_api.h.
*/
/*
* ========
* Debugger
* ========
*/
/**
* ILLEGAL_ISOLATE_ID is a number guaranteed never to be associated with a
* valid isolate.
*/
#define ILLEGAL_ISOLATE_ID ILLEGAL_PORT
/*
* =======
* Service
* =======
*/
/**
* A service request callback function.
*
* These callbacks, registered by the embedder, are called when the VM receives
* a service request it can't handle and the service request command name
* matches one of the embedder registered handlers.
*
* The return value of the callback indicates whether the response
* should be used as a regular result or an error result.
* Specifically, if the callback returns true, a regular JSON-RPC
* response is built in the following way:
*
* {
* "jsonrpc": "2.0",
* "result": <json_object>,
* "id": <some sequence id>,
* }
*
* If the callback returns false, a JSON-RPC error is built like this:
*
* {
* "jsonrpc": "2.0",
* "error": <json_object>,
* "id": <some sequence id>,
* }
*
* \param method The rpc method name.
* \param param_keys Service requests can have key-value pair parameters. The
* keys and values are flattened and stored in arrays.
* \param param_values The values associated with the keys.
* \param num_params The length of the param_keys and param_values arrays.
* \param user_data The user_data pointer registered with this handler.
* \param result A C string containing a valid JSON object. The returned
* pointer will be freed by the VM by calling free.
*
* \return True if the result is a regular JSON-RPC response, false if the
* result is a JSON-RPC error.
*/
typedef bool (*Dart_ServiceRequestCallback)(const char* method,
const char** param_keys,
const char** param_values,
intptr_t num_params,
void* user_data,
const char** json_object);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc on a specific isolate. The callback will
* be invoked with the current isolate set to the request target.
*
* \param method The name of the method that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_RegisterIsolateServiceRequestCallback(
const char* method,
Dart_ServiceRequestCallback callback,
void* user_data);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc. The callback will be invoked without a
* current isolate.
*
* \param method The name of the command that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_RegisterRootServiceRequestCallback(
const char* method,
Dart_ServiceRequestCallback callback,
void* user_data);
/**
* Embedder information which can be requested by the VM for internal or
* reporting purposes.
*
* The pointers in this structure are not going to be cached or freed by the VM.
*/
#define DART_EMBEDDER_INFORMATION_CURRENT_VERSION (0x00000001)
typedef struct {
int32_t version;
const char* name; // [optional] The name of the embedder
int64_t current_rss; // [optional] the current RSS of the embedder
int64_t max_rss; // [optional] the maximum RSS of the embedder
} Dart_EmbedderInformation;
/**
* Callback provided by the embedder that is used by the vm to request
* information.
*
* \return Returns a pointer to a Dart_EmbedderInformation structure.
* The embedder keeps the ownership of the structure and any field in it.
* The embedder must ensure that the structure will remain valid until the
* next invokation of the callback.
*/
typedef void (*Dart_EmbedderInformationCallback)(
Dart_EmbedderInformation* info);
/**
* Register a Dart_ServiceRequestCallback to be called to handle
* requests for the named rpc. The callback will be invoked without a
* current isolate.
*
* \param method The name of the command that this callback is responsible for.
* \param callback The callback to invoke.
* \param user_data The user data passed to the callback.
*
* NOTE: If multiple callbacks with the same name are registered, only
* the last callback registered will be remembered.
*/
DART_EXPORT void Dart_SetEmbedderInformationCallback(
Dart_EmbedderInformationCallback callback);
/**
* Invoke a vm-service method and wait for its result.
*
* \param request_json The utf8-encoded json-rpc request.
* \param request_json_length The length of the json-rpc request.
*
* \param response_json The returned utf8-encoded json response, must be
* free()ed by caller.
* \param response_json_length The length of the returned json response.
* \param error An optional error, must be free()ed by caller.
*
* \return Whether the call was sucessfully performed.
*
* NOTE: This method does not need a current isolate and must not have the
* vm-isolate being the current isolate. It must be called after
* Dart_Initialize() and before Dart_Cleanup().
*/
DART_EXPORT bool Dart_InvokeVMServiceMethod(uint8_t* request_json,
intptr_t request_json_length,
uint8_t** response_json,
intptr_t* response_json_length,
char** error);
/*
* ========
* Event Streams
* ========
*/
/**
* A callback invoked when the VM service gets a request to listen to
* some stream.
*
* \return Returns true iff the embedder supports the named stream id.
*/
typedef bool (*Dart_ServiceStreamListenCallback)(const char* stream_id);
/**
* A callback invoked when the VM service gets a request to cancel
* some stream.
*/
typedef void (*Dart_ServiceStreamCancelCallback)(const char* stream_id);
/**
* Adds VM service stream callbacks.
*
* \param listen_callback A function pointer to a listen callback function.
* A listen callback function should not be already set when this function
* is called. A NULL value removes the existing listen callback function
* if any.
*
* \param cancel_callback A function pointer to a cancel callback function.
* A cancel callback function should not be already set when this function
* is called. A NULL value removes the existing cancel callback function
* if any.
*
* \return Success if the callbacks were added. Otherwise, returns an
* error handle.
*/
DART_EXPORT char* Dart_SetServiceStreamCallbacks(
Dart_ServiceStreamListenCallback listen_callback,
Dart_ServiceStreamCancelCallback cancel_callback);
/**
* A callback invoked when the VM service receives an event.
*/
typedef void (*Dart_NativeStreamConsumer)(const uint8_t* event_json,
intptr_t event_json_length);
/**
* Sets the native VM service stream callbacks for a particular stream.
* Note: The function may be called on multiple threads concurrently.
*
* \param consumer A function pointer to an event handler callback function.
* A NULL value removes the existing listen callback function if any.
*
* \param stream_id The ID of the stream on which to set the callback.
*/
DART_EXPORT void Dart_SetNativeServiceStreamCallback(
Dart_NativeStreamConsumer consumer,
const char* stream_id);
/**
* Sends a data event to clients of the VM Service.
*
* A data event is used to pass an array of bytes to subscribed VM
* Service clients. For example, in the standalone embedder, this is
* function used to provide WriteEvents on the Stdout and Stderr
* streams.
*
* If the embedder passes in a stream id for which no client is
* subscribed, then the event is ignored.
*
* \param stream_id The id of the stream on which to post the event.
*
* \param event_kind A string identifying what kind of event this is.
* For example, 'WriteEvent'.
*
* \param bytes A pointer to an array of bytes.
*
* \param bytes_length The length of the byte array.
*
* \return NULL if the arguments are well formed. Otherwise, returns an
* error string. The caller is responsible for freeing the error message.
*/
DART_EXPORT char* Dart_ServiceSendDataEvent(const char* stream_id,
const char* event_kind,
const uint8_t* bytes,
intptr_t bytes_length);
/**
* Usage statistics for a space/generation at a particular moment in time.
*
* \param used Amount of memory used, in bytes.
*
* \param capacity Memory capacity, in bytes.
*
* \param external External memory, in bytes.
*
* \param collections How many times the garbage collector has run in this
* space.
*
* \param time Cumulative time spent collecting garbage in this space, in
* seconds.
*
* \param avg_collection_period Average time between garbage collector running
* in this space, in milliseconds.
*/
typedef struct {
intptr_t used;
intptr_t capacity;
intptr_t external;
intptr_t collections;
double time;
double avg_collection_period;
} Dart_GCStats;
/**
* A Garbage Collection event with memory usage statistics.
*
* \param type The event type. Static lifetime.
*
* \param reason The reason for the GC event. Static lifetime.
*
* \param new_space Data for New Space.
*
* \param old_space Data for Old Space.
*/
typedef struct {
const char* type;
const char* reason;
const char* isolate_id;
Dart_GCStats new_space;
Dart_GCStats old_space;
} Dart_GCEvent;
/**
* A callback invoked when the VM emits a GC event.
*
* \param event The GC event data. Pointer only valid for the duration of the
* callback.
*/
typedef void (*Dart_GCEventCallback)(Dart_GCEvent* event);
/**
* Sets the native GC event callback.
*
* \param callback A function pointer to an event handler callback function.
* A NULL value removes the existing listen callback function if any.
*/
DART_EXPORT void Dart_SetGCEventCallback(Dart_GCEventCallback callback);
/*
* ========
* Reload support
* ========
*
* These functions are used to implement reloading in the Dart VM.
* This is an experimental feature, so embedders should be prepared
* for these functions to change.
*/
/**
* A callback which determines whether the file at some url has been
* modified since some time. If the file cannot be found, true should
* be returned.
*/
typedef bool (*Dart_FileModifiedCallback)(const char* url, int64_t since);
DART_EXPORT char* Dart_SetFileModifiedCallback(
Dart_FileModifiedCallback file_modified_callback);
/**
* Returns true if isolate is currently reloading.
*/
DART_EXPORT bool Dart_IsReloading();
/*
* ========
* Timeline
* ========
*/
/**
* Returns a timestamp in microseconds. This timestamp is suitable for
* passing into the timeline system, and uses the same monotonic clock
* as dart:developer's Timeline.now.
*
* \return A timestamp that can be passed to the timeline system.
*/
DART_EXPORT int64_t Dart_TimelineGetMicros();
/**
* Returns a raw timestamp in from the monotonic clock.
*
* \return A raw timestamp from the monotonic clock.
*/
DART_EXPORT int64_t Dart_TimelineGetTicks();
/**
* Returns the frequency of the monotonic clock.
*
* \return The frequency of the monotonic clock.
*/
DART_EXPORT int64_t Dart_TimelineGetTicksFrequency();
typedef enum {
Dart_Timeline_Event_Begin, // Phase = 'B'.
Dart_Timeline_Event_End, // Phase = 'E'.
Dart_Timeline_Event_Instant, // Phase = 'i'.
Dart_Timeline_Event_Duration, // Phase = 'X'.
Dart_Timeline_Event_Async_Begin, // Phase = 'b'.
Dart_Timeline_Event_Async_End, // Phase = 'e'.
Dart_Timeline_Event_Async_Instant, // Phase = 'n'.
Dart_Timeline_Event_Counter, // Phase = 'C'.
Dart_Timeline_Event_Flow_Begin, // Phase = 's'.
Dart_Timeline_Event_Flow_Step, // Phase = 't'.
Dart_Timeline_Event_Flow_End, // Phase = 'f'.
} Dart_Timeline_Event_Type;
/**
* Add a timeline event to the embedder stream.
*
* \param label The name of the event. Its lifetime must extend at least until
* Dart_Cleanup.
* \param timestamp0 The first timestamp of the event.
* \param timestamp1_or_async_id The second timestamp of the event or
* the async id.
* \param argument_count The number of argument names and values.
* \param argument_names An array of names of the arguments. The lifetime of the
* names must extend at least until Dart_Cleanup. The array may be reclaimed
* when this call returns.
* \param argument_values An array of values of the arguments. The values and
* the array may be reclaimed when this call returns.
*/
DART_EXPORT void Dart_TimelineEvent(const char* label,
int64_t timestamp0,
int64_t timestamp1_or_async_id,
Dart_Timeline_Event_Type type,
intptr_t argument_count,
const char** argument_names,
const char** argument_values);
/**
* Associates a name with the current thread. This name will be used to name
* threads in the timeline. Can only be called after a call to Dart_Initialize.
*
* \param name The name of the thread.
*/
DART_EXPORT void Dart_SetThreadName(const char* name);
/*
* =======
* Metrics
* =======
*/
/**
* Return metrics gathered for the VM and individual isolates.
*
* NOTE: Non-heap metrics are not available in PRODUCT builds of Dart.
* Calling the non-heap metric functions on a PRODUCT build might return invalid metrics.
*/
DART_EXPORT int64_t Dart_VMIsolateCountMetric(); // Counter
DART_EXPORT int64_t Dart_VMCurrentRSSMetric(); // Byte
DART_EXPORT int64_t Dart_VMPeakRSSMetric(); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldUsedMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldUsedMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldCapacityMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldCapacityMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapOldExternalMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewUsedMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewUsedMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewCapacityMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewCapacityMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapNewExternalMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapGlobalUsedMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateHeapGlobalUsedMaxMetric(Dart_Isolate isolate); // Byte
DART_EXPORT int64_t
Dart_IsolateRunnableLatencyMetric(Dart_Isolate isolate); // Microsecond
DART_EXPORT int64_t
Dart_IsolateRunnableHeapSizeMetric(Dart_Isolate isolate); // Byte
/*
* ========
* UserTags
* ========
*/
/*
* Gets the current isolate's currently set UserTag instance.
*
* \return The currently set UserTag instance.
*/
DART_EXPORT Dart_Handle Dart_GetCurrentUserTag();
/*
* Gets the current isolate's default UserTag instance.
*
* \return The default UserTag with label 'Default'
*/
DART_EXPORT Dart_Handle Dart_GetDefaultUserTag();
/*
* Creates a new UserTag instance.
*
* \param label The name of the new UserTag.
*
* \return The newly created UserTag instance or an error handle.
*/
DART_EXPORT Dart_Handle Dart_NewUserTag(const char* label);
/*
* Updates the current isolate's UserTag to a new value.
*
* \param user_tag The UserTag to be set as the current UserTag.
*
* \return The previously set UserTag instance or an error handle.
*/
DART_EXPORT Dart_Handle Dart_SetCurrentUserTag(Dart_Handle user_tag);
/*
* Returns the label of a given UserTag instance.
*
* \param user_tag The UserTag from which the label will be retrieved.
*
* \return The UserTag's label. NULL if the user_tag is invalid. The caller is
* responsible for freeing the returned label.
*/
DART_EXPORT DART_WARN_UNUSED_RESULT char* Dart_GetUserTagLabel(
Dart_Handle user_tag);
#endif // RUNTIME_INCLUDE_DART_TOOLS_API_H_
| samples/experimental/pedometer/src/dart-sdk/include/dart_tools_api.h/0 | {
"file_path": "samples/experimental/pedometer/src/dart-sdk/include/dart_tools_api.h",
"repo_id": "samples",
"token_count": 5764
} | 1,307 |
#import "GeneratedPluginRegistrant.h"
| samples/experimental/varfont_shader_puzzle/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,308 |
// 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.
export 'page_ascender_descender.dart';
export 'page_narrative_post.dart';
export 'page_narrative_pre.dart';
export 'page_optical_size.dart';
export 'page_weight.dart';
export 'page_width.dart';
| samples/experimental/varfont_shader_puzzle/lib/page_content/pages.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/pages.dart",
"repo_id": "samples",
"token_count": 118
} | 1,309 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'api/api.dart';
import 'api/firebase.dart';
import 'api/mock.dart';
import 'auth/auth.dart';
import 'auth/firebase.dart';
import 'auth/mock.dart';
import 'pages/home.dart';
import 'pages/sign_in.dart';
/// The global state the app.
class AppState {
final Auth auth;
DashboardApi? api;
AppState(this.auth);
}
/// Creates a [DashboardApi] for the given user. This allows users of this
/// widget to specify whether [MockDashboardApi] or [ApiBuilder] should be
/// created when the user logs in.
typedef ApiBuilder = DashboardApi Function(User user);
/// An app that displays a personalized dashboard.
class DashboardApp extends StatefulWidget {
static DashboardApi _mockApiBuilder(User user) =>
MockDashboardApi()..fillWithMockData();
static DashboardApi _apiBuilder(User user) =>
FirebaseDashboardApi(FirebaseFirestore.instance, user.uid);
final Auth auth;
final ApiBuilder apiBuilder;
/// Runs the app using Firebase
DashboardApp.firebase({super.key})
: auth = FirebaseAuthService(),
apiBuilder = _apiBuilder;
/// Runs the app using mock data
DashboardApp.mock({super.key})
: auth = MockAuthService(),
apiBuilder = _mockApiBuilder;
@override
State<DashboardApp> createState() => _DashboardAppState();
}
class _DashboardAppState extends State<DashboardApp> {
late final AppState _appState;
@override
void initState() {
super.initState();
_appState = AppState(widget.auth);
}
@override
Widget build(BuildContext context) {
return Provider.value(
value: _appState,
child: MaterialApp(
theme: ThemeData.light(),
home: SignInSwitcher(
appState: _appState,
apiBuilder: widget.apiBuilder,
),
),
);
}
}
/// Switches between showing the [SignInPage] or [HomePage], depending on
/// whether or not the user is signed in.
class SignInSwitcher extends StatefulWidget {
final AppState? appState;
final ApiBuilder? apiBuilder;
const SignInSwitcher({
this.appState,
this.apiBuilder,
super.key,
});
@override
State<SignInSwitcher> createState() => _SignInSwitcherState();
}
class _SignInSwitcherState extends State<SignInSwitcher> {
bool _isSignedIn = false;
@override
Widget build(BuildContext context) {
return AnimatedSwitcher(
switchInCurve: Curves.easeOut,
switchOutCurve: Curves.easeOut,
duration: const Duration(milliseconds: 200),
child: _isSignedIn
? HomePage(
onSignOut: _handleSignOut,
)
: SignInPage(
auth: widget.appState!.auth,
onSuccess: _handleSignIn,
),
);
}
void _handleSignIn(User user) {
widget.appState!.api = widget.apiBuilder!(user);
setState(() {
_isSignedIn = true;
});
}
Future _handleSignOut() async {
await widget.appState!.auth.signOut();
setState(() {
_isSignedIn = false;
});
}
}
| samples/experimental/web_dashboard/lib/src/app.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/app.dart",
"repo_id": "samples",
"token_count": 1236
} | 1,310 |
name: web_dashboard
description: A dashboard app sample
version: 1.0.0+1
publish_to: none
environment:
sdk: ^3.2.0
dependencies:
cloud_firestore: ^4.15.6
collection: ^1.16.0
community_charts_flutter: ^1.0.2
cupertino_icons: ^1.0.0
firebase_auth: ^4.0.1
firebase_core: ^2.25.5
flutter:
sdk: flutter
google_sign_in: ^6.0.0
intl: any # Pinned by Flutter SDK version
json_annotation: ^4.5.0
path: ^1.8.1
provider: ^6.0.0
uuid: ^4.0.0
dev_dependencies:
analysis_defaults:
path: ../../analysis_defaults
build_runner: ^2.1.0
flutter_test:
sdk: flutter
grinder: ^0.9.0
json_serializable: ^6.2.0
flutter:
uses-material-design: true
| samples/experimental/web_dashboard/pubspec.yaml/0 | {
"file_path": "samples/experimental/web_dashboard/pubspec.yaml",
"repo_id": "samples",
"token_count": 309
} | 1,311 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/form_app/android/gradle.properties/0 | {
"file_path": "samples/form_app/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,312 |
// 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 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
part 'sign_in_http.g.dart';
@JsonSerializable()
class FormData {
String? email;
String? password;
FormData({
this.email,
this.password,
});
factory FormData.fromJson(Map<String, dynamic> json) =>
_$FormDataFromJson(json);
Map<String, dynamic> toJson() => _$FormDataToJson(this);
}
class SignInHttpDemo extends StatefulWidget {
final http.Client? httpClient;
const SignInHttpDemo({
this.httpClient,
super.key,
});
@override
State<SignInHttpDemo> createState() => _SignInHttpDemoState();
}
class _SignInHttpDemoState extends State<SignInHttpDemo> {
FormData formData = FormData();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sign in Form'),
),
body: Form(
child: Scrollbar(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
...[
TextFormField(
autofocus: true,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(
filled: true,
hintText: 'Your email address',
labelText: 'Email',
),
onChanged: (value) {
formData.email = value;
},
),
TextFormField(
decoration: const InputDecoration(
filled: true,
labelText: 'Password',
),
obscureText: true,
onChanged: (value) {
formData.password = value;
},
),
TextButton(
child: const Text('Sign in'),
onPressed: () async {
// Use a JSON encoded string to send
var result = await widget.httpClient!.post(
Uri.parse('https://example.com/signin'),
body: json.encode(formData.toJson()),
headers: {'content-type': 'application/json'});
_showDialog(switch (result.statusCode) {
200 => 'Successfully signed in.',
401 => 'Unable to sign in.',
_ => 'Something went wrong. Please try again.'
});
},
),
].expand(
(widget) => [
widget,
const SizedBox(
height: 24,
)
],
)
],
),
),
),
),
);
}
void _showDialog(String message) {
showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: Text(message),
actions: [
TextButton(
child: const Text('OK'),
onPressed: () => Navigator.of(context).pop(),
),
],
),
);
}
}
| samples/form_app/lib/src/sign_in_http.dart/0 | {
"file_path": "samples/form_app/lib/src/sign_in_http.dart",
"repo_id": "samples",
"token_count": 1930
} | 1,313 |
Sounds in this folder are made by Filip Hracek and are CC0 (Public Domain).
| samples/game_template/assets/sfx/README.md/0 | {
"file_path": "samples/game_template/assets/sfx/README.md",
"repo_id": "samples",
"token_count": 20
} | 1,314 |
// 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.
/// Represents the state of an in-app purchase of ad removal such as
/// [AdRemovalPurchase.notStarted()] or [AdRemovalPurchase.active()].
class AdRemovalPurchase {
/// The representation of this product on the stores.
static const productId = 'remove_ads';
/// This is `true` if the `remove_ad` product has been purchased and verified.
/// Do not show ads if so.
final bool active;
/// This is `true` when the purchase is pending.
final bool pending;
/// If there was an error with the purchase, this field will contain
/// that error.
final Object? error;
const AdRemovalPurchase.active() : this._(true, false, null);
const AdRemovalPurchase.error(Object error) : this._(false, false, error);
const AdRemovalPurchase.notStarted() : this._(false, false, null);
const AdRemovalPurchase.pending() : this._(false, true, null);
const AdRemovalPurchase._(this.active, this.pending, this.error);
@override
int get hashCode => Object.hash(active, pending, error);
@override
bool operator ==(Object other) =>
other is AdRemovalPurchase &&
other.active == active &&
other.pending == pending &&
other.error == error;
}
| samples/game_template/lib/src/in_app_purchase/ad_removal.dart/0 | {
"file_path": "samples/game_template/lib/src/in_app_purchase/ad_removal.dart",
"repo_id": "samples",
"token_count": 408
} | 1,315 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'dart:math';
import 'package:flutter/widgets.dart';
/// Shows a confetti (celebratory) animation: paper snippings falling down.
///
/// The widget fills the available space (like [SizedBox.expand] would).
///
/// When [isStopped] is `true`, the animation will not run. This is useful
/// when the widget is not visible yet, for example. Provide [colors]
/// to make the animation look good in context.
///
/// This is a partial port of this CodePen by Hemn Chawroka:
/// https://codepen.io/iprodev/pen/azpWBr
class Confetti extends StatefulWidget {
static const _defaultColors = [
Color(0xffd10841),
Color(0xff1d75fb),
Color(0xff0050bc),
Color(0xffa2dcc7),
];
final bool isStopped;
final List<Color> colors;
const Confetti({
this.colors = _defaultColors,
this.isStopped = false,
super.key,
});
@override
State<Confetti> createState() => _ConfettiState();
}
class ConfettiPainter extends CustomPainter {
final defaultPaint = Paint();
final int snippingsCount = 200;
late final List<_PaperSnipping> _snippings;
Size? _size;
DateTime _lastTime = DateTime.now();
final UnmodifiableListView<Color> colors;
ConfettiPainter(
{required Listenable animation, required Iterable<Color> colors})
: colors = UnmodifiableListView(colors),
super(repaint: animation);
@override
void paint(Canvas canvas, Size size) {
if (_size == null) {
// First time we have a size.
_snippings = List.generate(
snippingsCount,
(i) => _PaperSnipping(
frontColor: colors[i % colors.length],
bounds: size,
));
}
final didResize = _size != null && _size != size;
final now = DateTime.now();
final dt = now.difference(_lastTime);
for (final snipping in _snippings) {
if (didResize) {
snipping.updateBounds(size);
}
snipping.update(dt.inMilliseconds / 1000);
snipping.draw(canvas);
}
_size = size;
_lastTime = now;
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
class _ConfettiState extends State<Confetti>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: ConfettiPainter(
colors: widget.colors,
animation: _controller,
),
willChange: true,
child: const SizedBox.expand(),
);
}
@override
void didUpdateWidget(covariant Confetti oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.isStopped && !widget.isStopped) {
_controller.repeat();
} else if (!oldWidget.isStopped && widget.isStopped) {
_controller.stop(canceled: false);
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
_controller = AnimationController(
// We don't really care about the duration, since we're going to
// use the controller on loop anyway.
duration: const Duration(seconds: 1),
vsync: this,
);
if (!widget.isStopped) {
_controller.repeat();
}
}
}
class _PaperSnipping {
static final Random _random = Random();
static const degToRad = pi / 180;
static const backSideBlend = Color(0x70EEEEEE);
Size _bounds;
late final _Vector position = _Vector(
_random.nextDouble() * _bounds.width,
_random.nextDouble() * _bounds.height,
);
final double rotationSpeed = 800 + _random.nextDouble() * 600;
final double angle = _random.nextDouble() * 360 * degToRad;
double rotation = _random.nextDouble() * 360 * degToRad;
double cosA = 1.0;
final double size = 7.0;
final double oscillationSpeed = 0.5 + _random.nextDouble() * 1.5;
final double xSpeed = 40;
final double ySpeed = 50 + _random.nextDouble() * 60;
late List<_Vector> corners = List.generate(4, (i) {
final angle = this.angle + degToRad * (45 + i * 90);
return _Vector(cos(angle), sin(angle));
});
double time = _random.nextDouble();
final Color frontColor;
late final Color backColor = Color.alphaBlend(backSideBlend, frontColor);
final paint = Paint()..style = PaintingStyle.fill;
_PaperSnipping({
required this.frontColor,
required Size bounds,
}) : _bounds = bounds;
void draw(Canvas canvas) {
if (cosA > 0) {
paint.color = frontColor;
} else {
paint.color = backColor;
}
final path = Path()
..addPolygon(
List.generate(
4,
(index) => Offset(
position.x + corners[index].x * size,
position.y + corners[index].y * size * cosA,
)),
true,
);
canvas.drawPath(path, paint);
}
void update(double dt) {
time += dt;
rotation += rotationSpeed * dt;
cosA = cos(degToRad * rotation);
position.x += cos(time * oscillationSpeed) * xSpeed * dt;
position.y += ySpeed * dt;
if (position.y > _bounds.height) {
// Move the snipping back to the top.
position.x = _random.nextDouble() * _bounds.width;
position.y = 0;
}
}
void updateBounds(Size newBounds) {
if (!newBounds.contains(Offset(position.x, position.y))) {
position.x = _random.nextDouble() * newBounds.width;
position.y = _random.nextDouble() * newBounds.height;
}
_bounds = newBounds;
}
}
class _Vector {
double x, y;
_Vector(this.x, this.y);
}
| samples/game_template/lib/src/style/confetti.dart/0 | {
"file_path": "samples/game_template/lib/src/style/confetti.dart",
"repo_id": "samples",
"token_count": 2202
} | 1,316 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:infinitelist/main.dart';
void main() {
testWidgets('Infinite list smoke test', (tester) async {
await tester.pumpWidget(const MyApp());
const loadingDuration = Duration(milliseconds: 500);
// At first, the catalog shows only "..." (loading items).
expect(find.text('...'), findsWidgets);
expect(find.text('Color #1'), findsNothing);
await tester.pump(loadingDuration);
// After the app has had a chance to load items, it should no longer
// show "...".
expect(find.text('...'), findsNothing);
expect(find.text('Color #1'), findsOneWidget);
// Flinging up quickly (i.e. scrolling down).
await tester.fling(find.byType(ListView), const Offset(0, -2000), 5000);
// As we scroll down, we should see more items loading.
expect(find.text('...'), findsWidgets);
// The item at the top should no longer be in view.
expect(find.text('Color #1'), findsNothing);
// This last part is just giving the app time to complete its "fetch"
// of new items. Otherwise, the test fails because of outstanding
// asynchronous callbacks.
await tester.pump(loadingDuration);
});
}
| samples/infinite_list/test/smoke_test.dart/0 | {
"file_path": "samples/infinite_list/test/smoke_test.dart",
"repo_id": "samples",
"token_count": 455
} | 1,317 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>ios_app_clip</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppClip</key>
<dict>
<key>NSAppClipRequestEphemeralUserNotification</key>
<false/>
<key>NSAppClipRequestLocationConfirmation</key>
<false/>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
| samples/ios_app_clip/ios/AppClip/Info.plist/0 | {
"file_path": "samples/ios_app_clip/ios/AppClip/Info.plist",
"repo_id": "samples",
"token_count": 729
} | 1,318 |
// Copyright 2021 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 TypographyScreen extends StatelessWidget {
const TypographyScreen({super.key});
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context)
.textTheme
.apply(displayColor: Theme.of(context).colorScheme.onSurface);
return Expanded(
child: ListView(
children: <Widget>[
const SizedBox(height: 7),
TextStyleExample(
name: 'Display Large', style: textTheme.displayLarge!),
TextStyleExample(
name: 'Display Medium', style: textTheme.displayMedium!),
TextStyleExample(
name: 'Display Small', style: textTheme.displaySmall!),
TextStyleExample(
name: 'Headline Large', style: textTheme.headlineLarge!),
TextStyleExample(
name: 'Headline Medium', style: textTheme.headlineMedium!),
TextStyleExample(
name: 'Headline Small', style: textTheme.headlineSmall!),
TextStyleExample(name: 'Title Large', style: textTheme.titleLarge!),
TextStyleExample(name: 'Title Medium', style: textTheme.titleMedium!),
TextStyleExample(name: 'Title Small', style: textTheme.titleSmall!),
TextStyleExample(name: 'Label Large', style: textTheme.labelLarge!),
TextStyleExample(name: 'Label Medium', style: textTheme.labelMedium!),
TextStyleExample(name: 'Label Small', style: textTheme.labelSmall!),
TextStyleExample(name: 'Body Large', style: textTheme.bodyLarge!),
TextStyleExample(name: 'Body Medium', style: textTheme.bodyMedium!),
TextStyleExample(name: 'Body Small', style: textTheme.bodySmall!),
],
),
);
}
}
class TextStyleExample extends StatelessWidget {
const TextStyleExample({
super.key,
required this.name,
required this.style,
});
final String name;
final TextStyle style;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(name, style: style),
);
}
}
| samples/material_3_demo/lib/typography_screen.dart/0 | {
"file_path": "samples/material_3_demo/lib/typography_screen.dart",
"repo_id": "samples",
"token_count": 862
} | 1,319 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/material_3_demo/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/material_3_demo/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,320 |
// 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:adaptive_navigation/adaptive_navigation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class BookstoreScaffold extends StatelessWidget {
final Widget child;
final int selectedIndex;
const BookstoreScaffold({
required this.child,
required this.selectedIndex,
super.key,
});
@override
Widget build(BuildContext context) {
final goRouter = GoRouter.of(context);
return Scaffold(
body: AdaptiveNavigationScaffold(
selectedIndex: selectedIndex,
body: child,
onDestinationSelected: (idx) {
if (idx == 0) goRouter.go('/books/popular');
if (idx == 1) goRouter.go('/authors');
if (idx == 2) goRouter.go('/settings');
},
destinations: const [
AdaptiveScaffoldDestination(
title: 'Books',
icon: Icons.book,
),
AdaptiveScaffoldDestination(
title: 'Authors',
icon: Icons.person,
),
AdaptiveScaffoldDestination(
title: 'Settings',
icon: Icons.settings,
),
],
),
);
}
}
| samples/navigation_and_routing/lib/src/screens/scaffold.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/screens/scaffold.dart",
"repo_id": "samples",
"token_count": 596
} | 1,321 |
package dev.flutter.place_tracker
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/place_tracker/android/app/src/main/kotlin/dev/flutter/place_tracker/MainActivity.kt/0 | {
"file_path": "samples/place_tracker/android/app/src/main/kotlin/dev/flutter/place_tracker/MainActivity.kt",
"repo_id": "samples",
"token_count": 40
} | 1,322 |
// 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:async';
import 'dart:math';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
import 'place.dart';
import 'place_tracker_app.dart';
class MapConfiguration {
final List<Place> places;
final PlaceCategory selectedCategory;
const MapConfiguration({
required this.places,
required this.selectedCategory,
});
@override
int get hashCode => places.hashCode ^ selectedCategory.hashCode;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is MapConfiguration &&
other.places == places &&
other.selectedCategory == selectedCategory;
}
static MapConfiguration of(AppState appState) {
return MapConfiguration(
places: appState.places,
selectedCategory: appState.selectedCategory,
);
}
}
class PlaceMap extends StatefulWidget {
final LatLng? center;
const PlaceMap({
super.key,
this.center,
});
@override
State<PlaceMap> createState() => _PlaceMapState();
}
class _PlaceMapState extends State<PlaceMap> {
Completer<GoogleMapController> mapController = Completer();
MapType _currentMapType = MapType.normal;
LatLng? _lastMapPosition;
final Map<Marker, Place> _markedPlaces = <Marker, Place>{};
final Set<Marker> _markers = {};
Marker? _pendingMarker;
MapConfiguration? _configuration;
@override
void initState() {
super.initState();
context.read<AppState>().addListener(_watchMapConfigurationChanges);
}
@override
void dispose() {
context.read<AppState>().removeListener(_watchMapConfigurationChanges);
super.dispose();
}
@override
Widget build(BuildContext context) {
_watchMapConfigurationChanges();
var state = Provider.of<AppState>(context, listen: true);
return Builder(builder: (context) {
// We need this additional builder here so that we can pass its context to
// _AddPlaceButtonBar's onSavePressed callback. This callback shows a
// SnackBar and to do this, we need a build context that has Scaffold as
// an ancestor.
return Center(
child: Stack(
children: [
GoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: CameraPosition(
target: widget.center!,
zoom: 11.0,
),
mapType: _currentMapType,
markers: _markers,
onCameraMove: (position) => _lastMapPosition = position.target,
),
_CategoryButtonBar(
selectedPlaceCategory: state.selectedCategory,
visible: _pendingMarker == null,
onChanged: _switchSelectedCategory,
),
_AddPlaceButtonBar(
visible: _pendingMarker != null,
onSavePressed: () => _confirmAddPlace(context),
onCancelPressed: _cancelAddPlace,
),
_MapFabs(
visible: _pendingMarker == null,
onAddPlacePressed: _onAddPlacePressed,
onToggleMapTypePressed: _onToggleMapTypePressed,
),
],
),
);
});
}
Future<void> onMapCreated(GoogleMapController controller) async {
if (!context.mounted) return;
final appState = Provider.of<AppState>(context, listen: false);
mapController.complete(controller);
_lastMapPosition = widget.center;
// Draw initial place markers on creation so that we have something
// interesting to look at.
var markers = <Marker>{};
for (var place in appState.places) {
markers.add(await _createPlaceMarker(place, appState.selectedCategory));
}
setState(() {
_markers.addAll(markers);
});
// Zoom to fit the initially selected category.
_zoomToFitSelectedCategory();
}
@override
void didUpdateWidget(PlaceMap oldWidget) {
super.didUpdateWidget(oldWidget);
// Zoom to fit the selected category.
if (mounted) {
_zoomToFitSelectedCategory();
}
}
/// Applies zoom to fit the places of the selected category
void _zoomToFitSelectedCategory() {
_zoomToFitPlaces(
_getPlacesForCategory(
Provider.of<AppState>(context, listen: false).selectedCategory,
_markedPlaces.values.toList(),
),
);
}
void _cancelAddPlace() {
if (_pendingMarker != null) {
setState(() {
_markers.remove(_pendingMarker);
_pendingMarker = null;
});
}
}
Future<void> _confirmAddPlace(BuildContext context) async {
if (!context.mounted) return;
if (_pendingMarker != null) {
// Create a new Place and map it to the marker we just added.
final appState = Provider.of<AppState>(context, listen: false);
final newPlace = Place(
id: const Uuid().v1(),
latLng: _pendingMarker!.position,
name: _pendingMarker!.infoWindow.title!,
category: appState.selectedCategory,
);
final scaffoldMessenger = ScaffoldMessenger.of(context);
var placeMarker = await _getPlaceMarkerIcon(appState.selectedCategory);
setState(() {
final updatedMarker = _pendingMarker!.copyWith(
iconParam: placeMarker,
infoWindowParam: InfoWindow(
title: 'New Place',
snippet: null,
onTap: () => context.go('/place/${newPlace.id}'),
),
draggableParam: false,
);
_updateMarker(
marker: _pendingMarker,
updatedMarker: updatedMarker,
place: newPlace,
);
_pendingMarker = null;
});
// Show a confirmation snackbar that has an action to edit the new place.
scaffoldMessenger.showSnackBar(
SnackBar(
duration: const Duration(seconds: 3),
content:
const Text('New place added.', style: TextStyle(fontSize: 16.0)),
action: SnackBarAction(
label: 'Edit',
onPressed: () async {
context.go('/place/${newPlace.id}');
},
),
),
);
// Add the new place to the places stored in appState.
final newPlaces = List<Place>.from(appState.places)..add(newPlace);
appState.setPlaces(newPlaces);
}
}
Future<Marker> _createPlaceMarker(
Place place,
PlaceCategory selectedCategory,
) async {
final marker = Marker(
markerId: MarkerId(place.latLng.toString()),
position: place.latLng,
infoWindow: InfoWindow(
title: place.name,
snippet: '${place.starRating} Star Rating',
onTap: () => context.go('/place/${place.id}'),
),
icon: await _getPlaceMarkerIcon(place.category),
visible: place.category == selectedCategory,
);
_markedPlaces[marker] = place;
return marker;
}
Future<void> _watchMapConfigurationChanges() async {
final appState = context.read<AppState>();
_configuration ??= MapConfiguration.of(appState);
final newConfiguration = MapConfiguration.of(appState);
// Since we manually update [_configuration] when place or selectedCategory
// changes come from the [place_map], we should only enter this if statement
// when returning to the [place_map] after changes have been made from
// [place_list].
if (_configuration != newConfiguration) {
if (_configuration!.places == newConfiguration.places &&
_configuration!.selectedCategory !=
newConfiguration.selectedCategory) {
// If the configuration change is only a category change, just update
// the marker visibilities.
await _showPlacesForSelectedCategory(newConfiguration.selectedCategory);
} else {
// At this point, we know the places have been updated from the list
// view. We need to reconfigure the map to respect the updates.
for (final place in newConfiguration.places) {
final oldPlace =
_configuration!.places.firstWhereOrNull((p) => p.id == place.id);
if (oldPlace == null || oldPlace != place) {
// New place or updated place.
_updateExistingPlaceMarker(place: place);
}
}
await _zoomToFitPlaces(
_getPlacesForCategory(
newConfiguration.selectedCategory,
newConfiguration.places,
),
);
}
_configuration = newConfiguration;
}
}
Future<void> _onAddPlacePressed() async {
setState(() {
final newMarker = Marker(
markerId: MarkerId(_lastMapPosition.toString()),
position: _lastMapPosition!,
infoWindow: const InfoWindow(title: 'New Place'),
draggable: true,
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
);
_markers.add(newMarker);
_pendingMarker = newMarker;
});
}
void _onToggleMapTypePressed() {
final nextType =
MapType.values[(_currentMapType.index + 1) % MapType.values.length];
setState(() {
_currentMapType = nextType;
});
}
Future<void> _showPlacesForSelectedCategory(PlaceCategory category) async {
setState(() {
for (var marker in List.of(_markedPlaces.keys)) {
final place = _markedPlaces[marker]!;
final updatedMarker = marker.copyWith(
visibleParam: place.category == category,
);
_updateMarker(
marker: marker,
updatedMarker: updatedMarker,
place: place,
);
}
});
await _zoomToFitPlaces(_getPlacesForCategory(
category,
_markedPlaces.values.toList(),
));
}
Future<void> _switchSelectedCategory(PlaceCategory category) async {
Provider.of<AppState>(context, listen: false).setSelectedCategory(category);
await _showPlacesForSelectedCategory(category);
}
void _updateExistingPlaceMarker({required Place place}) {
var marker = _markedPlaces.keys
.singleWhere((value) => _markedPlaces[value]!.id == place.id);
setState(() {
final updatedMarker = marker.copyWith(
infoWindowParam: InfoWindow(
title: place.name,
snippet:
place.starRating != 0 ? '${place.starRating} Star Rating' : null,
),
);
_updateMarker(marker: marker, updatedMarker: updatedMarker, place: place);
});
}
void _updateMarker({
required Marker? marker,
required Marker updatedMarker,
required Place place,
}) {
_markers.remove(marker);
_markedPlaces.remove(marker);
_markers.add(updatedMarker);
_markedPlaces[updatedMarker] = place;
}
Future<void> _zoomToFitPlaces(List<Place> places) async {
var controller = await mapController.future;
// Default min/max values to latitude and longitude of center.
var minLat = widget.center!.latitude;
var maxLat = widget.center!.latitude;
var minLong = widget.center!.longitude;
var maxLong = widget.center!.longitude;
for (var place in places) {
minLat = min(minLat, place.latitude);
maxLat = max(maxLat, place.latitude);
minLong = min(minLong, place.longitude);
maxLong = max(maxLong, place.longitude);
}
WidgetsBinding.instance.addPostFrameCallback((_) {
controller.animateCamera(
CameraUpdate.newLatLngBounds(
LatLngBounds(
southwest: LatLng(minLat, minLong),
northeast: LatLng(maxLat, maxLong),
),
48.0,
),
);
});
}
Future<BitmapDescriptor> _getPlaceMarkerIcon(PlaceCategory category) =>
switch (category) {
PlaceCategory.favorite => BitmapDescriptor.fromAssetImage(
createLocalImageConfiguration(context, size: const Size.square(32)),
'assets/heart.png'),
PlaceCategory.visited => BitmapDescriptor.fromAssetImage(
createLocalImageConfiguration(context, size: const Size.square(32)),
'assets/visited.png'),
PlaceCategory.wantToGo => Future.value(BitmapDescriptor.defaultMarker),
};
static List<Place> _getPlacesForCategory(
PlaceCategory category, List<Place> places) {
return places.where((place) => place.category == category).toList();
}
}
class _AddPlaceButtonBar extends StatelessWidget {
final bool visible;
final VoidCallback onSavePressed;
final VoidCallback onCancelPressed;
const _AddPlaceButtonBar({
required this.visible,
required this.onSavePressed,
required this.onCancelPressed,
});
@override
Widget build(BuildContext context) {
return Visibility(
visible: visible,
child: Container(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 14.0),
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: OverflowBar(
alignment: MainAxisAlignment.center,
spacing: 8.0,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
onPressed: onSavePressed,
child: const Text('Save'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: onCancelPressed,
child: const Text('Cancel'),
),
],
),
),
),
);
}
}
class _CategoryButtonBar extends StatelessWidget {
final PlaceCategory selectedPlaceCategory;
final bool visible;
final ValueChanged<PlaceCategory> onChanged;
const _CategoryButtonBar({
required this.selectedPlaceCategory,
required this.visible,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Visibility(
visible: visible,
child: Container(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 14.0),
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: OverflowBar(
alignment: MainAxisAlignment.center,
spacing: 8.0,
children: <Widget>[
FilledButton(
style: FilledButton.styleFrom(
backgroundColor:
selectedPlaceCategory == PlaceCategory.favorite
? Colors.green[700]
: Colors.lightGreen),
onPressed: () => onChanged(PlaceCategory.favorite),
child: const Text(
'Favorites',
style: TextStyle(color: Colors.white, fontSize: 14.0),
),
),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor:
selectedPlaceCategory == PlaceCategory.visited
? Colors.green[700]
: Colors.lightGreen),
onPressed: () => onChanged(PlaceCategory.visited),
child: const Text(
'Visited',
style: TextStyle(color: Colors.white, fontSize: 14.0),
),
),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor:
selectedPlaceCategory == PlaceCategory.wantToGo
? Colors.green[700]
: Colors.lightGreen),
onPressed: () => onChanged(PlaceCategory.wantToGo),
child: const Text(
'Want To Go',
style: TextStyle(color: Colors.white, fontSize: 14.0),
),
),
],
),
),
),
);
}
}
class _MapFabs extends StatelessWidget {
final bool visible;
final VoidCallback onAddPlacePressed;
final VoidCallback onToggleMapTypePressed;
const _MapFabs({
required this.visible,
required this.onAddPlacePressed,
required this.onToggleMapTypePressed,
});
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.topRight,
margin: const EdgeInsets.only(top: 12.0, right: 12.0),
child: Visibility(
visible: visible,
child: Column(
children: [
FloatingActionButton(
heroTag: 'add_place_button',
onPressed: onAddPlacePressed,
materialTapTargetSize: MaterialTapTargetSize.padded,
child: const Icon(Icons.add_location, size: 36.0),
),
const SizedBox(height: 12.0),
FloatingActionButton(
heroTag: 'toggle_map_type_button',
onPressed: onToggleMapTypePressed,
materialTapTargetSize: MaterialTapTargetSize.padded,
mini: true,
child: const Icon(Icons.layers, size: 28.0),
),
],
),
),
);
}
}
| samples/place_tracker/lib/place_map.dart/0 | {
"file_path": "samples/place_tracker/lib/place_map.dart",
"repo_id": "samples",
"token_count": 7565
} | 1,323 |
#import "GeneratedPluginRegistrant.h"
| samples/platform_channels/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/platform_channels/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,324 |
// 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_channels/src/method_channel_demo.dart';
void main() {
group('MethodChannelDemo tests', () {
testWidgets('MethodChannelDemo count test', (tester) async {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('methodChannelDemo'),
(call) async {
var count = call.arguments['count'] as int;
if (call.method == 'increment') {
return ++count;
} else if (call.method == 'decrement') {
return --count;
}
return MissingPluginException();
},
);
await tester.pumpWidget(const MaterialApp(
home: MethodChannelDemo(),
));
// Initially the value of count should be 0.
expect(find.text('Value of count is 0'), findsOneWidget);
// Tap the ElevatedButton with Icons.add to increment the value of count.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('Value of count is 1'), findsOneWidget);
// Tap the ElevatedButton with Icons.remove to decrement the value of count.
await tester.tap(find.byIcon(Icons.remove));
await tester.pump();
expect(find.text('Value of count is 0'), findsOneWidget);
});
});
}
| samples/platform_channels/test/src/method_channel_demo_test.dart/0 | {
"file_path": "samples/platform_channels/test/src/method_channel_demo_test.dart",
"repo_id": "samples",
"token_count": 595
} | 1,325 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Platform Design</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>platform_design</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
</dict>
</plist>
| samples/platform_design/ios/Runner/Info.plist/0 | {
"file_path": "samples/platform_design/ios/Runner/Info.plist",
"repo_id": "samples",
"token_count": 647
} | 1,326 |
name: provider_shopper
description: A shopping app sample that uses Provider for state management.
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
go_router: ^13.0.0
provider: ^6.0.2
window_size:
git:
url: https://github.com/google/flutter-desktop-embedding.git
path: plugins/window_size
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
fonts:
- family: Corben
fonts:
- asset: fonts/Corben/Corben-Bold.ttf
weight: 700
| samples/provider_shopper/pubspec.yaml/0 | {
"file_path": "samples/provider_shopper/pubspec.yaml",
"repo_id": "samples",
"token_count": 261
} | 1,327 |
# `simple_shader`
A simple [Flutter fragment shaders][] sample project.
[Flutter fragment shaders]: https://docs.flutter.dev/development/ui/advanced/shaders

| samples/simple_shader/README.md/0 | {
"file_path": "samples/simple_shader/README.md",
"repo_id": "samples",
"token_count": 70
} | 1,328 |
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled.
version:
revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
channel: beta
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
- platform: android
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
- platform: ios
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
- platform: linux
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
- platform: macos
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
- platform: web
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
- platform: windows
create_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
base_revision: a14a4eac6132065fcbd853a2ff376e6911cdb2ea
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
| samples/simplistic_calculator/.metadata/0 | {
"file_path": "samples/simplistic_calculator/.metadata",
"repo_id": "samples",
"token_count": 743
} | 1,329 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'basic_text_input_client.dart';
/// A basic text field. Defines the appearance of a basic text input client.
class BasicTextField extends StatefulWidget {
const BasicTextField({
super.key,
required this.controller,
required this.style,
required this.focusNode,
this.contextMenuBuilder = _defaultContextMenuBuilder,
});
final TextEditingController controller;
final TextStyle style;
final FocusNode focusNode;
final BasicTextFieldContextMenuBuilder? contextMenuBuilder;
static Widget _defaultContextMenuBuilder(
BuildContext context,
ClipboardStatus clipboardStatus,
VoidCallback? onCopy,
VoidCallback? onCut,
VoidCallback? onPaste,
VoidCallback? onSelectAll,
VoidCallback? onLookUp,
VoidCallback? onLiveTextInput,
VoidCallback? onSearchWeb,
VoidCallback? onShare,
TextSelectionToolbarAnchors anchors,
) {
return AdaptiveTextSelectionToolbar.editable(
clipboardStatus: clipboardStatus,
onCopy: onCopy,
onCut: onCut,
onPaste: onPaste,
onSelectAll: onSelectAll,
onLookUp: onLookUp,
onLiveTextInput: onLiveTextInput,
onSearchWeb: onSearchWeb,
onShare: onShare,
anchors: anchors,
);
}
@override
State<BasicTextField> createState() => _BasicTextFieldState();
}
class _BasicTextFieldState extends State<BasicTextField> {
final GlobalKey<BasicTextInputClientState> textInputClientKey =
GlobalKey<BasicTextInputClientState>();
BasicTextInputClientState? get _textInputClient =>
textInputClientKey.currentState;
RenderEditable get _renderEditable => _textInputClient!.renderEditable;
// For text selection gestures.
// The viewport offset pixels of the [RenderEditable] at the last drag start.
double _dragStartViewportOffset = 0.0;
late DragStartDetails _startDetails;
// For text selection.
TextSelectionControls? _textSelectionControls;
bool _showSelectionHandles = false;
bool _shouldShowSelectionHandles(SelectionChangedCause? cause) {
// When the text field is activated by something that doesn't trigger the
// selection overlay, we shouldn't show the handles either.
if (cause == SelectionChangedCause.keyboard) {
return false;
}
if (cause == SelectionChangedCause.longPress ||
cause == SelectionChangedCause.scribble) {
return true;
}
if (widget.controller.text.isNotEmpty) {
return true;
}
return false;
}
void _handleSelectionChanged(
TextSelection selection, SelectionChangedCause? cause) {
final bool willShowSelectionHandles = _shouldShowSelectionHandles(cause);
if (willShowSelectionHandles != _showSelectionHandles) {
setState(() {
_showSelectionHandles = willShowSelectionHandles;
});
}
}
void _onDragUpdate(DragUpdateDetails details) {
final Offset startOffset = _renderEditable.maxLines == 1
? Offset(_renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
: Offset(0.0, _renderEditable.offset.pixels - _dragStartViewportOffset);
_renderEditable.selectPositionAt(
from: _startDetails.globalPosition - startOffset,
to: details.globalPosition,
cause: SelectionChangedCause.drag,
);
}
void _onDragStart(DragStartDetails details) {
_startDetails = details;
_dragStartViewportOffset = _renderEditable.offset.pixels;
}
@override
Widget build(BuildContext context) {
switch (Theme.of(this.context).platform) {
// ignore: todo
// TODO(Renzo-Olivares): Remove use of deprecated members once
// TextSelectionControls.buildToolbar has been deleted.
// See https://github.com/flutter/flutter/pull/124611 and
// https://github.com/flutter/flutter/pull/124262 for more details.
case TargetPlatform.iOS:
// ignore: deprecated_member_use
_textSelectionControls = cupertinoTextSelectionHandleControls;
case TargetPlatform.macOS:
// ignore: deprecated_member_use
_textSelectionControls = cupertinoDesktopTextSelectionHandleControls;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
// ignore: deprecated_member_use
_textSelectionControls = materialTextSelectionHandleControls;
case TargetPlatform.linux:
// ignore: deprecated_member_use
_textSelectionControls = desktopTextSelectionHandleControls;
case TargetPlatform.windows:
// ignore: deprecated_member_use
_textSelectionControls = desktopTextSelectionHandleControls;
}
return TextFieldTapRegion(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onPanStart: (dragStartDetails) => _onDragStart(dragStartDetails),
onPanUpdate: (dragUpdateDetails) => _onDragUpdate(dragUpdateDetails),
onSecondaryTapDown: (secondaryTapDownDetails) {
_renderEditable.selectWordsInRange(
from: secondaryTapDownDetails.globalPosition,
cause: SelectionChangedCause.tap);
_renderEditable.handleSecondaryTapDown(secondaryTapDownDetails);
_textInputClient!.hideToolbar();
_textInputClient!.showToolbar();
},
onTap: () {
_textInputClient!.requestKeyboard();
_textInputClient!.hideToolbar();
},
onTapDown: (tapDownDetails) {
_renderEditable.handleTapDown(tapDownDetails);
_renderEditable.selectPosition(cause: SelectionChangedCause.tap);
},
onLongPressMoveUpdate: (longPressMoveUpdateDetails) {
switch (Theme.of(this.context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
_renderEditable.selectPositionAt(
from: longPressMoveUpdateDetails.globalPosition,
cause: SelectionChangedCause.longPress,
);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
_renderEditable.selectWordsInRange(
from: longPressMoveUpdateDetails.globalPosition -
longPressMoveUpdateDetails.offsetFromOrigin,
to: longPressMoveUpdateDetails.globalPosition,
cause: SelectionChangedCause.longPress,
);
}
},
onLongPressEnd: (longPressEndDetails) =>
_textInputClient!.showToolbar(),
onHorizontalDragStart: (dragStartDetails) =>
_onDragStart(dragStartDetails),
onHorizontalDragUpdate: (dragUpdateDetails) =>
_onDragUpdate(dragUpdateDetails),
child: SizedBox(
height: double.infinity,
width: MediaQuery.of(context).size.width,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
),
child: BasicTextInputClient(
key: textInputClientKey,
controller: widget.controller,
style: widget.style,
focusNode: widget.focusNode,
selectionControls: _textSelectionControls,
onSelectionChanged: _handleSelectionChanged,
showSelectionHandles: _showSelectionHandles,
contextMenuBuilder: widget.contextMenuBuilder,
),
),
),
),
);
}
}
| samples/simplistic_editor/lib/basic_text_field.dart/0 | {
"file_path": "samples/simplistic_editor/lib/basic_text_field.dart",
"repo_id": "samples",
"token_count": 2959
} | 1,330 |
#include "ephemeral/Flutter-Generated.xcconfig"
| samples/simplistic_editor/macos/Flutter/Flutter-Debug.xcconfig/0 | {
"file_path": "samples/simplistic_editor/macos/Flutter/Flutter-Debug.xcconfig",
"repo_id": "samples",
"token_count": 19
} | 1,331 |
// 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:integration_test/integration_test.dart';
import 'package:testing_app/main.dart';
void main() {
group('Testing App Performance Tests', () {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// The fullyLive frame policy simulates
// the way Flutter responds to animations.
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
testWidgets('Scrolling test', (tester) async {
await tester.pumpWidget(const TestingApp());
// Create variables for finders that are used multiple times.
final listFinder = find.byType(ListView);
final scroller = tester.widget<ListView>(listFinder).controller;
// Record the performance summary as the app scrolls through
// the list of items.
await binding.watchPerformance(
() async {
// Quickly scroll all the way down.
await scroller!.animateTo(
7000,
duration: const Duration(seconds: 1),
curve: Curves.linear,
);
await tester.pumpAndSettle();
// Quickly scroll back up all the way.
await scroller.animateTo(
-7000,
duration: const Duration(seconds: 1),
curve: Curves.linear,
);
await tester.pumpAndSettle();
},
// Send the performance summary to the driver.
reportKey: 'scrolling_summary',
);
});
testWidgets('Favorites operations test', (tester) async {
await tester.pumpWidget(const TestingApp());
// Record the performance summary as operations are performed
// on the favorites list.
await binding.watchPerformance(
() async {
// Create a list of icon keys.
final iconKeys = [
'icon_0',
'icon_1',
'icon_2',
];
// Add first three items to favorites.
for (var icon in iconKeys) {
// Tap onto the icon.
await tester.tap(find.byKey(ValueKey(icon)));
await tester.pumpAndSettle(const Duration(seconds: 1));
// Verify if appropriate message appears.
expect(find.text('Added to favorites.'), findsOneWidget);
}
// Tap onto the favorites button on the AppBar.
// The Favorites List should appear.
await tester.tap(find.text('Favorites'));
await tester.pumpAndSettle();
final removeIconKeys = [
'remove_icon_0',
'remove_icon_1',
'remove_icon_2',
];
// Remove all the items from favorites.
for (final iconKey in removeIconKeys) {
// Tap onto the remove icon.
await tester.tap(find.byKey(ValueKey(iconKey)));
await tester.pumpAndSettle(const Duration(seconds: 1));
// Verify if appropriate message appears.
expect(find.text('Removed from favorites.'), findsOneWidget);
}
},
// Send the performance summary to the driver.
reportKey: 'favorites_operations_summary',
);
});
});
}
| samples/testing_app/integration_test/perf_test.dart/0 | {
"file_path": "samples/testing_app/integration_test/perf_test.dart",
"repo_id": "samples",
"token_count": 1401
} | 1,332 |
// 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/cupertino.dart';
class FadeTransitionPage<T> extends Page<T> {
final Widget child;
final Duration duration;
const FadeTransitionPage({
super.key,
required this.child,
this.duration = const Duration(milliseconds: 300),
super.restorationId,
});
@override
Route<T> createRoute(BuildContext context) =>
PageBasedFadeTransitionRoute<T>(this);
}
class PageBasedFadeTransitionRoute<T> extends PageRoute<T> {
PageBasedFadeTransitionRoute(FadeTransitionPage<T> page)
: super(settings: page);
FadeTransitionPage<T> get _page => settings as FadeTransitionPage<T>;
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
@override
Duration get transitionDuration => _page.duration;
@override
Duration get reverseTransitionDuration => _page.duration;
@override
bool get maintainState => true;
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return _page.child;
}
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
final tween = CurveTween(curve: Curves.easeInOut);
return FadeTransition(
opacity: animation.drive(tween),
child: _page.child,
);
}
}
| samples/veggieseasons/lib/widgets/fade_transition_page.dart/0 | {
"file_path": "samples/veggieseasons/lib/widgets/fade_transition_page.dart",
"repo_id": "samples",
"token_count": 534
} | 1,333 |
include: package:flutter_lints/flutter.yaml
linter:
rules:
| samples/web/_packages/web_startup_analyzer/example/analysis_options.yaml/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/example/analysis_options.yaml",
"repo_id": "samples",
"token_count": 24
} | 1,334 |
// Copyright 2021 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.
// Helper class to capture Flutter web app startup timing information
class FlutterWebStartupAnalyzer {
timings;
constructor() {
this.timings = {};
}
markStart(name) {
this.timings[name] = null;
performance.mark('flt-' + name + '-started');
}
markFinished(name) {
performance.mark('flt-' + name + '-finished');
}
capture(name) {
var timingName = 'flt-' + name;
var started = 'flt-' + name + 'started';
try {
var measurement = performance.measure('flt-' + name, 'flt-' + name + '-started', 'flt-' + name + '-finished');
} catch(e) {
// ignore errors if the mark doesn't exist
return;
}
this.timings[name] = measurement.duration;
}
captureAll() {
for (var [key, value] of Object.entries(this.timings)) {
this.capture(key);
}
// Capture
this.timings['load'] = performance.timing.loadEventEnd - performance.timing.domContentLoadedEventEnd;
this.timings['domContentLoaded'] = performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart;
}
capturePaint() {
const entries = performance.getEntriesByType("paint");
// Collect first-paint and first-contentful-paint entries
entries.forEach((entry) => {
this.timings[entry.name] = entry.startTime;
});
}
}
| samples/web/_packages/web_startup_analyzer/lib/web_startup_analyzer.js/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/lib/web_startup_analyzer.js",
"repo_id": "samples",
"token_count": 653
} | 1,335 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file
import 'dart:io';
import 'package:checked_yaml/checked_yaml.dart';
import 'package:samples_index/browser.dart';
import 'package:samples_index/samples_index.dart';
import 'package:test/test.dart';
void main() {
group('YAML', () {
test('parsing', () async {
var file = File('test/yaml/single.yaml');
var contents = await file.readAsString();
expect(contents, isNotEmpty);
var index = checkedYamlDecode(
contents, (m) => m != null ? Index.fromJson(m) : null,
sourceUrl: file.uri);
if (index == null) {
throw ('unable to load YAML from $file');
}
expect(index.samples, isNotEmpty);
var sample = index.samples.first;
expect(sample, isNotNull);
expect(sample.name, 'Kittens');
expect(sample.screenshots, hasLength(2));
expect(sample.source, 'https://github.com/johnpryan/kittens');
expect(sample.description, 'A sample kitten app');
expect(sample.difficulty, 'beginner');
expect(sample.widgets, hasLength(2));
expect(sample.widgets.first, 'AnimatedBuilder');
expect(sample.packages, hasLength(2));
expect(sample.packages.first, 'json_serializable');
expect(sample.tags, hasLength(3));
expect(sample.tags[1], 'kittens');
expect(sample.platforms, hasLength(3));
expect(sample.type, 'sample');
expect(sample.date, DateTime.parse('2019-12-15T02:59:43.1Z'));
expect(sample.channel, 'stable');
});
});
group('searching', () {
test('search attributes', () async {
var file = File('test/yaml/single.yaml');
var contents = await file.readAsString();
expect(contents, isNotEmpty);
var index = checkedYamlDecode(
contents, (m) => m != null ? Index.fromJson(m) : null,
sourceUrl: file.uri);
if (index == null) {
throw ('unable to load YAML from $file');
}
var sample = index.samples.first;
expect(
sample.searchAttributes.split(' '),
containsAll(const <String>[
'kittens',
'tag:beginner',
'tag:kittens',
'tag:cats',
// Verify tags are searchable without the prefix
'beginner',
'kittens',
'cats',
'platform:web',
'platform:ios',
'platform:android',
// Verify platforms are searchable without the prefix
'web',
'ios',
'android',
'widget:AnimatedBuilder',
'widget:FutureBuilder',
'package:json_serializable',
'package:path',
'type:sample',
]));
});
test('matchesQuery', () {
var attributes = 'kittens '
'tag:beginner '
'tag:kittens '
'tag:cats '
'platform:web '
'platform:ios '
'platform:android '
'widget:AnimatedBuilder '
'widget:FutureBuilder '
'package:json_serializable '
'package:path '
'type:sample';
// Test if various queries match these attributes
expect(matchesQuery('foo', attributes), false);
expect(matchesQuery('Foo', attributes), false);
expect(matchesQuery('kittens', attributes), true);
expect(matchesQuery('Kittens', attributes), true);
expect(matchesQuery('tag:cats', attributes), true);
expect(matchesQuery('tag:dogs', attributes), false);
expect(matchesQuery('package:path', attributes), true);
// Test if partial queries match these attributes
expect(matchesQuery('kitten', attributes), true);
// Test if multiple keywords match
expect(matchesQuery('kittens tag:cats', attributes), true);
expect(matchesQuery('kitten tag:cats', attributes), true);
expect(matchesQuery('tag:beginner dogs', attributes), false);
expect(matchesQuery('asdf ', attributes), false);
// Test if queries match by type
expect(matchesQuery('type:sample', attributes), true);
expect(matchesQuery('type:demo', attributes), false);
expect(matchesQuery('kittens type:demo', attributes), false);
});
});
group('Hash parameters', () {
test('can be parsed', () {
expect(parseHash('#?search=kittens&platform=web'),
containsPair('search', 'kittens'));
expect(parseHash('#?search=kittens&platform=web'),
containsPair('platform', 'web'));
expect(parseHash('#?type=sample'), containsPair('type', 'sample'));
expect(parseHash('#?type=demo'), containsPair('type', 'demo'));
});
test('can be set', () {
expect(
formatHash({
'search': 'kittens',
'platform': 'web',
}),
equals('?search=kittens&platform=web'));
});
test('creates search attributes', () {
expect(
searchQueryFromParams({
'search': 'kittens',
'platform': 'web',
'type': 'sample',
}),
equals('kittens type:sample platform:web'));
expect(
searchQueryFromParams({
'search': 'kittens',
}),
equals('kittens'));
expect(searchQueryFromParams({}), equals(''));
});
});
}
| samples/web/samples_index/test/samples_index_test.dart/0 | {
"file_path": "samples/web/samples_index/test/samples_index_test.dart",
"repo_id": "samples",
"token_count": 2304
} | 1,336 |
// Manages toggling the VFX of the buttons
(function () {
"use strict";
let handheld;
let fxButtons = document.querySelector("#fx");
let flutterTarget = document.querySelector("#flutter_target");
let attribution = document.createElement("span");
attribution.className = "imageAttribution";
attribution.innerHTML = "Photo by <a href='https://unsplash.com/photos/x9WGMWwp1NM' rel='noopener noreferrer' target='_blank'>Nathana Rebouças</a> on Unsplash";
// (Re)moves the flutterTarget inside a div#handheld.
function handleHandHeld(fx) {
resetRotation();
if (!handheld) {
handheld = document.createElement("div");
handheld.id = "handheld";
handheld.classList.add("hidden");
// Inject before the flutterTarget
flutterTarget.parentNode.insertBefore(handheld, flutterTarget);
handheld.append(flutterTarget);
handheld.append(attribution);
window.setTimeout(function () {
handheld.classList.remove("hidden");
}, 100);
// Disable all effects on the flutter container
flutterTarget.className = "";
setOtherFxEnabled(false);
} else {
handheld.classList.add("hidden");
window.setTimeout(function () {
handheld.parentNode.insertBefore(flutterTarget, handheld);
handheld.remove();
handheld = null;
}, 210);
setOtherFxEnabled(true);
}
window.requestAnimationFrame(function () {
// Let the browser flush the DOM...
flutterTarget.classList.toggle(fx);
});
}
// Sets a rotation style on the flutterTarget (in degrees).
function handleRotation(degrees) {
flutterTarget.style.transform = `perspective(1000px) rotateY(${degrees}deg)`;
}
// Removes the inline style from the flutterTarget.
function resetRotation() {
flutterTarget.style = null;
}
// Enables/disables the buttons that are not compatible with the "handheld" mode.
function setOtherFxEnabled(enabled) {
fxButtons.querySelectorAll('input').forEach((btn) => {
if (btn.dataset.fx != 'handheld') {
btn.classList.toggle('disabled', !enabled);
}
});
}
// Handles clicks on the buttons inside #fx.
fxButtons.addEventListener("click", (event) => {
let fx = event.target.dataset.fx;
if (fx === "handheld") {
handleHandHeld(fx);
return;
}
flutterTarget.classList.toggle(fx);
});
fxButtons.addEventListener("input", (event) => {
if (event.target.id === "rotation") {
flutterTarget.classList.toggle("spin", false);
handleRotation(event.target.value);
}
})
})();
| samples/web_embedding/element_embedding_demo/web/js/demo-css-fx.js/0 | {
"file_path": "samples/web_embedding/element_embedding_demo/web/js/demo-css-fx.js",
"repo_id": "samples",
"token_count": 955
} | 1,337 |
/// Exposes useful functions to interop with JS from our Flutter app.
library;
export 'js_interop/counter_state_manager.dart';
export 'js_interop/helper.dart' show broadcastAppEvent;
export 'dart:js_interop' show createJSInteropWrapper;
| samples/web_embedding/ng-flutter/flutter/lib/src/js_interop.dart/0 | {
"file_path": "samples/web_embedding/ng-flutter/flutter/lib/src/js_interop.dart",
"repo_id": "samples",
"token_count": 77
} | 1,338 |
steps:
- name: gcr.io/cloud-builders/git
args: ['submodule', 'update', '--init', '--recursive']
- name: gcr.io/cloud-builders/docker
entrypoint: '/bin/bash'
args:
- '-c'
- |-
set -e
echo "Building the website using a makefile..."
make build BUILD_CONFIGS=_config.yml
- name: gcr.io/flutter-dev-230821/firebase-ghcli
entrypoint: '/bin/bash'
args:
- '-c'
- |-
cloud_build/scripts/stage_site_and_comment_on_github.sh
secretEnv: ['GH_PAT_TOKEN']
env:
- 'PR_NUMBER=$_PR_NUMBER'
- 'HEAD_BRANCH=$_HEAD_BRANCH'
- 'PROJECT_ID=$PROJECT_ID'
- 'COMMIT_SHA=$COMMIT_SHA'
- 'REPO_FULL_NAME=$REPO_FULL_NAME'
availableSecrets:
secretManager:
- versionName: projects/$PROJECT_ID/secrets/flutter-website-bot-comment-pat/versions/latest
env: 'GH_PAT_TOKEN'
timeout: 1200s
options:
logging: CLOUD_LOGGING_ONLY
| website/cloud_build/stage.yaml/0 | {
"file_path": "website/cloud_build/stage.yaml",
"repo_id": "website",
"token_count": 434
} | 1,339 |
name: hero_animation
publish_to: none
description: Shows how to create a simple Hero transition.
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/hero_animation/pubspec.yaml/0 | {
"file_path": "website/examples/_animation/hero_animation/pubspec.yaml",
"repo_id": "website",
"token_count": 132
} | 1,340 |
import 'package:flutter/material.dart';
void main() => runApp(const LogoApp());
class LogoApp extends StatefulWidget {
const LogoApp({super.key});
@override
State<LogoApp> createState() => _LogoAppState();
}
class _LogoAppState extends State<LogoApp> {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
height: 300,
width: 300,
child: const FlutterLogo(),
),
);
}
}
| website/examples/animation/animate0/lib/main.dart/0 | {
"file_path": "website/examples/animation/animate0/lib/main.dart",
"repo_id": "website",
"token_count": 201
} | 1,341 |
// ignore_for_file: unused_field, prefer_final_fields
import 'package:flutter/material.dart';
// #docregion Starter
class AnimatedContainerApp extends StatefulWidget {
const AnimatedContainerApp({super.key});
@override
State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}
class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
// Define the various properties with default values. Update these properties
// when the user taps a FloatingActionButton.
double _width = 50;
double _height = 50;
Color _color = Colors.green;
BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);
@override
Widget build(BuildContext context) {
// Fill this out in the next steps.
return Container();
}
}
// #enddocregion Starter
| website/examples/cookbook/animation/animated_container/lib/starter.dart/0 | {
"file_path": "website/examples/cookbook/animation/animated_container/lib/starter.dart",
"repo_id": "website",
"token_count": 225
} | 1,342 |
name: physics_simulation
description: Sample code for cookbook.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/animation/physics_simulation/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/animation/physics_simulation/pubspec.yaml",
"repo_id": "website",
"token_count": 90
} | 1,343 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleCupertinoDownloadButton(),
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class ExampleCupertinoDownloadButton extends StatefulWidget {
const ExampleCupertinoDownloadButton({super.key});
@override
State<ExampleCupertinoDownloadButton> createState() =>
_ExampleCupertinoDownloadButtonState();
}
class _ExampleCupertinoDownloadButtonState
extends State<ExampleCupertinoDownloadButton> {
late final List<DownloadController> _downloadControllers;
@override
void initState() {
super.initState();
_downloadControllers = List<DownloadController>.generate(
20,
(index) => SimulatedDownloadController(onOpenDownload: () {
_openDownload(index);
}),
);
}
void _openDownload(int index) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Open App ${index + 1}'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Apps')),
body: ListView.separated(
itemCount: _downloadControllers.length,
separatorBuilder: (_, __) => const Divider(),
itemBuilder: _buildListItem,
),
);
}
Widget _buildListItem(BuildContext context, int index) {
final theme = Theme.of(context);
final downloadController = _downloadControllers[index];
return ListTile(
leading: const DemoAppIcon(),
title: Text(
'App ${index + 1}',
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleLarge,
),
subtitle: Text(
'Lorem ipsum dolor #${index + 1}',
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall,
),
trailing: SizedBox(
width: 96,
child: AnimatedBuilder(
animation: downloadController,
builder: (context, child) {
return DownloadButton(
status: downloadController.downloadStatus,
downloadProgress: downloadController.progress,
onDownload: downloadController.startDownload,
onCancel: downloadController.stopDownload,
onOpen: downloadController.openDownload,
);
},
),
),
);
}
}
@immutable
class DemoAppIcon extends StatelessWidget {
const DemoAppIcon({super.key});
@override
Widget build(BuildContext context) {
return const AspectRatio(
aspectRatio: 1,
child: FittedBox(
child: SizedBox(
width: 80,
height: 80,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.red, Colors.blue],
),
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: Center(
child: Icon(
Icons.ac_unit,
color: Colors.white,
size: 40,
),
),
),
),
),
);
}
}
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
abstract class DownloadController implements ChangeNotifier {
DownloadStatus get downloadStatus;
double get progress;
void startDownload();
void stopDownload();
void openDownload();
}
class SimulatedDownloadController extends DownloadController
with ChangeNotifier {
SimulatedDownloadController({
DownloadStatus downloadStatus = DownloadStatus.notDownloaded,
double progress = 0.0,
required VoidCallback onOpenDownload,
}) : _downloadStatus = downloadStatus,
_progress = progress,
_onOpenDownload = onOpenDownload;
DownloadStatus _downloadStatus;
@override
DownloadStatus get downloadStatus => _downloadStatus;
double _progress;
@override
double get progress => _progress;
final VoidCallback _onOpenDownload;
bool _isDownloading = false;
@override
void startDownload() {
if (downloadStatus == DownloadStatus.notDownloaded) {
_doSimulatedDownload();
}
}
@override
void stopDownload() {
if (_isDownloading) {
_isDownloading = false;
_downloadStatus = DownloadStatus.notDownloaded;
_progress = 0.0;
notifyListeners();
}
}
@override
void openDownload() {
if (downloadStatus == DownloadStatus.downloaded) {
_onOpenDownload();
}
}
Future<void> _doSimulatedDownload() async {
_isDownloading = true;
_downloadStatus = DownloadStatus.fetchingDownload;
notifyListeners();
// Wait a second to simulate fetch time.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Shift to the downloading phase.
_downloadStatus = DownloadStatus.downloading;
notifyListeners();
const downloadProgressStops = [0.0, 0.15, 0.45, 0.8, 1.0];
for (final stop in downloadProgressStops) {
// Wait a second to simulate varying download speeds.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Update the download progress.
_progress = stop;
notifyListeners();
}
// Wait a second to simulate a final delay.
await Future<void>.delayed(const Duration(seconds: 1));
// If the user chose to cancel the download, stop the simulation.
if (!_isDownloading) {
return;
}
// Shift to the downloaded state, completing the simulation.
_downloadStatus = DownloadStatus.downloaded;
_isDownloading = false;
notifyListeners();
}
}
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.downloadProgress = 0.0,
required this.onDownload,
required this.onCancel,
required this.onOpen,
this.transitionDuration = const Duration(milliseconds: 500),
});
final DownloadStatus status;
final double downloadProgress;
final VoidCallback onDownload;
final VoidCallback onCancel;
final VoidCallback onOpen;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
void _onPressed() {
switch (status) {
case DownloadStatus.notDownloaded:
onDownload();
case DownloadStatus.fetchingDownload:
// do nothing.
break;
case DownloadStatus.downloading:
onCancel();
case DownloadStatus.downloaded:
onOpen();
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: Stack(
children: [
ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
Positioned.fill(
child: AnimatedOpacity(
duration: transitionDuration,
opacity: _isDownloading || _isFetching ? 1.0 : 0.0,
curve: Curves.ease,
child: Stack(
alignment: Alignment.center,
children: [
ProgressIndicatorWidget(
downloadProgress: downloadProgress,
isDownloading: _isDownloading,
isFetching: _isFetching,
),
if (_isDownloading)
const Icon(
Icons.stop,
size: 14,
color: CupertinoColors.activeBlue,
),
],
),
),
),
],
),
);
}
}
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ? 'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activeBlue,
),
),
),
),
);
}
}
@immutable
class ProgressIndicatorWidget extends StatelessWidget {
const ProgressIndicatorWidget({
super.key,
required this.downloadProgress,
required this.isDownloading,
required this.isFetching,
});
final double downloadProgress;
final bool isDownloading;
final bool isFetching;
@override
Widget build(BuildContext context) {
return AspectRatio(
aspectRatio: 1,
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: downloadProgress),
duration: const Duration(milliseconds: 200),
builder: (context, progress, child) {
return CircularProgressIndicator(
backgroundColor: isDownloading
? CupertinoColors.lightBackgroundGray
: Colors.white.withOpacity(0),
valueColor: AlwaysStoppedAnimation(isFetching
? CupertinoColors.lightBackgroundGray
: CupertinoColors.activeBlue),
strokeWidth: 2,
value: isFetching ? null : progress,
);
},
),
);
}
}
| website/examples/cookbook/effects/download_button/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/effects/download_button/lib/main.dart",
"repo_id": "website",
"token_count": 4368
} | 1,344 |
import 'package:flutter/material.dart';
// #docregion ParallaxRecipe
class ParallaxRecipe extends StatelessWidget {
const ParallaxRecipe({super.key});
@override
Widget build(BuildContext context) {
return const SingleChildScrollView(
child: Column(
children: [],
),
);
}
}
// #enddocregion ParallaxRecipe
| website/examples/cookbook/effects/parallax_scrolling/lib/excerpt1.dart/0 | {
"file_path": "website/examples/cookbook/effects/parallax_scrolling/lib/excerpt1.dart",
"repo_id": "website",
"token_count": 122
} | 1,345 |
// ignore_for_file: unused_catch_clause
import 'package:flutter/services.dart';
import 'package:games_services/games_services.dart';
void main() async {
// #docregion signIn
try {
await GamesServices.signIn();
} on PlatformException catch (e) {
// ... deal with failures ...
}
// #enddocregion signIn
// #docregion unlock
await GamesServices.unlock(
achievement: Achievement(
androidID: 'your android id',
iOSID: 'your ios id',
),
);
// #enddocregion unlock
// #docregion showAchievements
await GamesServices.showAchievements();
// #enddocregion showAchievements
// #docregion submitScore
await GamesServices.submitScore(
score: Score(
iOSLeaderboardID: 'some_id_from_app_store',
androidLeaderboardID: 'sOmE_iD_fRoM_gPlAy',
value: 100,
),
);
// #enddocregion submitScore
// #docregion showLeaderboards
await GamesServices.showLeaderboards(
iOSLeaderboardID: 'some_id_from_app_store',
androidLeaderboardID: 'sOmE_iD_fRoM_gPlAy',
);
// #enddocregion showLeaderboards
}
| website/examples/cookbook/games/achievements_leaderboards/lib/various.dart/0 | {
"file_path": "website/examples/cookbook/games/achievements_leaderboards/lib/various.dart",
"repo_id": "website",
"token_count": 390
} | 1,346 |
name: dismissible
description: Sample code for dismissible 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/dismissible/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/gestures/dismissible/pubspec.yaml",
"repo_id": "website",
"token_count": 91
} | 1,347 |
import 'package:flutter/material.dart';
class MyGif extends StatelessWidget {
const MyGif({super.key});
@override
Widget build(BuildContext context) {
// #docregion Gif
return Image.network(
'https://docs.flutter.dev/assets/images/dash/dash-fainting.gif');
// #enddocregion Gif
}
}
| website/examples/cookbook/images/network_image/lib/gif.dart/0 | {
"file_path": "website/examples/cookbook/images/network_image/lib/gif.dart",
"repo_id": "website",
"token_count": 118
} | 1,348 |
name: horizontal_list
description: Example for horizontal_list cookbook recipe
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/cookbook/lists/horizontal_list/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/lists/horizontal_list/pubspec.yaml",
"repo_id": "website",
"token_count": 140
} | 1,349 |
import 'package:flutter/material.dart';
class MainScreen extends StatelessWidget {
const MainScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Main Screen'),
),
body: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return const DetailScreen();
}));
},
child: Image.network(
'https://picsum.photos/250?image=9',
),
),
);
}
}
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Center(
child: Image.network(
'https://picsum.photos/250?image=9',
),
),
),
);
}
}
| website/examples/cookbook/navigation/hero_animations/lib/main_original.dart/0 | {
"file_path": "website/examples/cookbook/navigation/hero_animations/lib/main_original.dart",
"repo_id": "website",
"token_count": 438
} | 1,350 |
import 'package:flutter/material.dart';
// #docregion Todo
class Todo {
final String title;
final String description;
const Todo(this.title, this.description);
}
// #enddocregion Todo
void main() {
runApp(
MaterialApp(
title: 'Passing Data',
home: TodosScreen(
// #docregion Generate
todos: List.generate(
20,
(i) => Todo(
'Todo $i',
'A description of what needs to be done for Todo $i',
),
),
// #enddocregion Generate
),
),
);
}
class TodosScreen extends StatelessWidget {
const TodosScreen({super.key, required this.todos});
final List<Todo> todos;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Todos'),
),
// #docregion builder
body: ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
// When a user taps the ListTile, navigate to the DetailScreen.
// Notice that you're not only creating a DetailScreen, you're
// also passing the current todo through to it.
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(todo: todos[index]),
),
);
},
);
},
),
// #enddocregion builder
);
}
}
// #docregion detail
class DetailScreen extends StatelessWidget {
// In the constructor, require a Todo.
const DetailScreen({super.key, required this.todo});
// Declare a field that holds the Todo.
final Todo todo;
@override
Widget build(BuildContext context) {
// Use the Todo to create the UI.
return Scaffold(
appBar: AppBar(
title: Text(todo.title),
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Text(todo.description),
),
);
}
}
// #enddocregion detail
| website/examples/cookbook/navigation/passing_data/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/navigation/passing_data/lib/main.dart",
"repo_id": "website",
"token_count": 950
} | 1,351 |
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
// ignore_for_file: unused_local_variable
void main() async {
// #docregion openDatabase
// Avoid errors caused by flutter upgrade.
// Importing 'package:flutter/widgets.dart' is required.
WidgetsFlutterBinding.ensureInitialized();
// Open the database and store the reference.
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
join(await getDatabasesPath(), 'doggie_database.db'),
);
// #enddocregion openDatabase
}
| website/examples/cookbook/persistence/sqlite/lib/step3.dart/0 | {
"file_path": "website/examples/cookbook/persistence/sqlite/lib/step3.dart",
"repo_id": "website",
"token_count": 218
} | 1,352 |
import 'package:flutter/material.dart';
void main() {
runApp(MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
));
}
class MyApp extends StatelessWidget {
final List<String> items;
const MyApp({super.key, required this.items});
@override
Widget build(BuildContext context) {
const title = 'Long List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: ListView.builder(
// Add a key to the ListView. This makes it possible to
// find the list and scroll through it in the tests.
key: const Key('long_list'),
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
items[index],
// Add a key to the Text widget for each item. This makes
// it possible to look for a particular item in the list
// and verify that the text is correct
key: Key('item_${index}_text'),
),
);
},
),
),
);
}
}
| website/examples/cookbook/testing/widget/scrolling/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/testing/widget/scrolling/lib/main.dart",
"repo_id": "website",
"token_count": 532
} | 1,353 |
// #docregion Import
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// #enddocregion Import
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
// #docregion MyHomePageState
class _MyHomePageState extends State<MyHomePage> {
static const platform = MethodChannel('samples.flutter.dev/battery');
// #docregion GetBattery
// Get battery level.
// #enddocregion MyHomePageState
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;
});
}
// #enddocregion GetBattery
// #docregion Build
@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),
],
),
),
);
}
// #enddocregion Build
}
| website/examples/development/platform_integration/lib/platform_channels.dart/0 | {
"file_path": "website/examples/development/platform_integration/lib/platform_channels.dart",
"repo_id": "website",
"token_count": 557
} | 1,354 |
# Take our settings from the example_utils analysis_options.yaml file.
# If necessary for a particular example, this file can also include
# overrides for individual lints.
include: package:example_utils/analysis.yaml
analyzer:
language:
strict-casts: false
| website/examples/get-started/flutter-for/android_devs/analysis_options.yaml/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/analysis_options.yaml",
"repo_id": "website",
"token_count": 75
} | 1,355 |
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sample App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Widget> widgets = [];
@override
void initState() {
super.initState();
for (int i = 0; i < 100; i++) {
widgets.add(getRow(i));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample App'),
),
body: ListView.builder(
itemCount: widgets.length,
itemBuilder: (context, position) {
return getRow(position);
},
),
);
}
Widget getRow(int i) {
return GestureDetector(
onTap: () {
setState(() {
widgets.add(getRow(widgets.length));
developer.log('row $i');
});
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $i'),
),
);
}
}
| website/examples/get-started/flutter-for/android_devs/lib/listview_builder.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/listview_builder.dart",
"repo_id": "website",
"token_count": 624
} | 1,356 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
// #docregion ToggleWidget
class SampleApp extends StatelessWidget {
// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
// Default value for toggle.
bool toggle = true;
void _toggle() {
setState(() {
toggle = !toggle;
});
}
Widget _getToggleChild() {
if (toggle) {
return const Text('Toggle One');
}
return CupertinoButton(
onPressed: () {},
child: const Text('Toggle Two'),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample App'),
),
body: Center(
child: _getToggleChild(),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggle,
tooltip: 'Update Text',
child: const Icon(Icons.update),
),
);
}
}
// #enddocregion ToggleWidget
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
// #docregion SimpleWidget
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: Center(
child: CupertinoButton(
onPressed: () {},
padding: const EdgeInsets.only(left: 10, right: 10),
child: const Text('Hello'),
),
),
);
}
// #enddocregion SimpleWidget
}
class RowExample extends StatelessWidget {
const RowExample({super.key});
// #docregion Row
@override
Widget build(BuildContext context) {
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Row One'),
Text('Row Two'),
Text('Row Three'),
Text('Row Four'),
],
);
}
// #enddocregion Row
}
class ColumnExample extends StatelessWidget {
const ColumnExample({super.key});
// #docregion Column
@override
Widget build(BuildContext context) {
return const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Column One'),
Text('Column Two'),
Text('Column Three'),
Text('Column Four'),
],
);
}
// #enddocregion Column
}
class ListViewExample extends StatelessWidget {
const ListViewExample({super.key});
// #docregion ListView
@override
Widget build(BuildContext context) {
return ListView(
children: const <Widget>[
Text('Row One'),
Text('Row Two'),
Text('Row Three'),
Text('Row Four'),
],
);
}
// #enddocregion ListView
}
| website/examples/get-started/flutter-for/ios_devs/lib/layout.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/layout.dart",
"repo_id": "website",
"token_count": 1177
} | 1,357 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double turns = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child:
// #docregion AnimatedButton
AnimatedRotation(
duration: const Duration(seconds: 1),
turns: turns,
curve: Curves.easeIn,
child: TextButton(
onPressed: () {
setState(() {
turns += .125;
});
},
child: const Text('Tap me!')),
),
// #enddocregion AnimatedButton
),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/simple_animation.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/simple_animation.dart",
"repo_id": "website",
"token_count": 487
} | 1,358 |
// 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));
}
| website/examples/get-started/flutter-for/react_native_devs/lib/futures.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/futures.dart",
"repo_id": "website",
"token_count": 184
} | 1,359 |
import 'package:flutter/material.dart';
// #docregion Main
void main() {
runApp(const MyApp());
}
// #enddocregion Main
// #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 Center(
child: Text(
'Hello World!',
textDirection: TextDirection.ltr,
),
);
}
}
// #enddocregion MyApp
| website/examples/get-started/flutter-for/xamarin_devs/lib/main.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/main.dart",
"repo_id": "website",
"token_count": 173
} | 1,360 |
name: integration_test_example
publish_to: none
version: 0.0.1
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_driver:
sdk: flutter
test: ^1.24.9
flutter:
uses-material-design: true
| website/examples/integration_test/pubspec.yaml/0 | {
"file_path": "website/examples/integration_test/pubspec.yaml",
"repo_id": "website",
"token_count": 152
} | 1,361 |
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/date_symbol_data_custom.dart' as date_symbol_data_custom;
import 'package:intl/date_symbols.dart' as intl;
import 'package:intl/intl.dart' as intl;
/// A custom set of date patterns for the `nn` locale.
///
/// These are not accurate and are just a clone of the date patterns for the
/// `no` locale to demonstrate how one would write and use custom date patterns.
// #docregion Date
const nnLocaleDatePatterns = {
'd': 'd.',
'E': 'ccc',
'EEEE': 'cccc',
'LLL': 'LLL',
// #enddocregion Date
'LLLL': 'LLLL',
'M': 'L.',
'Md': 'd.M.',
'MEd': 'EEE d.M.',
'MMM': 'LLL',
'MMMd': 'd. MMM',
'MMMEd': 'EEE d. MMM',
'MMMM': 'LLLL',
'MMMMd': 'd. MMMM',
'MMMMEEEEd': 'EEEE d. MMMM',
'QQQ': 'QQQ',
'QQQQ': 'QQQQ',
'y': 'y',
'yM': 'M.y',
'yMd': 'd.M.y',
'yMEd': 'EEE d.MM.y',
'yMMM': 'MMM y',
'yMMMd': 'd. MMM y',
'yMMMEd': 'EEE d. MMM y',
'yMMMM': 'MMMM y',
'yMMMMd': 'd. MMMM y',
'yMMMMEEEEd': 'EEEE d. MMMM y',
'yQQQ': 'QQQ y',
'yQQQQ': 'QQQQ y',
'H': 'HH',
'Hm': 'HH:mm',
'Hms': 'HH:mm:ss',
'j': 'HH',
'jm': 'HH:mm',
'jms': 'HH:mm:ss',
'jmv': 'HH:mm v',
'jmz': 'HH:mm z',
'jz': 'HH z',
'm': 'm',
'ms': 'mm:ss',
's': 's',
'v': 'v',
'z': 'z',
'zzzz': 'zzzz',
'ZZZZ': 'ZZZZ',
};
/// A custom set of date symbols for the `nn` locale.
///
/// These are not accurate and are just a clone of the date symbols for the
/// `no` locale to demonstrate how one would write and use custom date symbols.
// #docregion Date2
const nnDateSymbols = {
'NAME': 'nn',
'ERAS': <dynamic>[
'f.Kr.',
'e.Kr.',
],
// #enddocregion Date2
'ERANAMES': <dynamic>[
'før Kristus',
'etter Kristus',
],
'NARROWMONTHS': <dynamic>[
'J',
'F',
'M',
'A',
'M',
'J',
'J',
'A',
'S',
'O',
'N',
'D',
],
'STANDALONENARROWMONTHS': <dynamic>[
'J',
'F',
'M',
'A',
'M',
'J',
'J',
'A',
'S',
'O',
'N',
'D',
],
'MONTHS': <dynamic>[
'januar',
'februar',
'mars',
'april',
'mai',
'juni',
'juli',
'august',
'september',
'oktober',
'november',
'desember',
],
'STANDALONEMONTHS': <dynamic>[
'januar',
'februar',
'mars',
'april',
'mai',
'juni',
'juli',
'august',
'september',
'oktober',
'november',
'desember',
],
'SHORTMONTHS': <dynamic>[
'jan.',
'feb.',
'mar.',
'apr.',
'mai',
'jun.',
'jul.',
'aug.',
'sep.',
'okt.',
'nov.',
'des.',
],
'STANDALONESHORTMONTHS': <dynamic>[
'jan',
'feb',
'mar',
'apr',
'mai',
'jun',
'jul',
'aug',
'sep',
'okt',
'nov',
'des',
],
'WEEKDAYS': <dynamic>[
'søndag',
'mandag',
'tirsdag',
'onsdag',
'torsdag',
'fredag',
'lørdag',
],
'STANDALONEWEEKDAYS': <dynamic>[
'søndag',
'mandag',
'tirsdag',
'onsdag',
'torsdag',
'fredag',
'lørdag',
],
'SHORTWEEKDAYS': <dynamic>[
'søn.',
'man.',
'tir.',
'ons.',
'tor.',
'fre.',
'lør.',
],
'STANDALONESHORTWEEKDAYS': <dynamic>[
'søn.',
'man.',
'tir.',
'ons.',
'tor.',
'fre.',
'lør.',
],
'NARROWWEEKDAYS': <dynamic>[
'S',
'M',
'T',
'O',
'T',
'F',
'L',
],
'STANDALONENARROWWEEKDAYS': <dynamic>[
'S',
'M',
'T',
'O',
'T',
'F',
'L',
],
'SHORTQUARTERS': <dynamic>[
'K1',
'K2',
'K3',
'K4',
],
'QUARTERS': <dynamic>[
'1. kvartal',
'2. kvartal',
'3. kvartal',
'4. kvartal',
],
'AMPMS': <dynamic>[
'a.m.',
'p.m.',
],
'DATEFORMATS': <dynamic>[
'EEEE d. MMMM y',
'd. MMMM y',
'd. MMM y',
'dd.MM.y',
],
'TIMEFORMATS': <dynamic>[
'HH:mm:ss zzzz',
'HH:mm:ss z',
'HH:mm:ss',
'HH:mm',
],
'AVAILABLEFORMATS': null,
'FIRSTDAYOFWEEK': 0,
'WEEKENDRANGE': <dynamic>[
5,
6,
],
'FIRSTWEEKCUTOFFDAY': 3,
'DATETIMEFORMATS': <dynamic>[
'{1} {0}',
'{1} \'kl\'. {0}',
'{1}, {0}',
'{1}, {0}',
],
};
// #docregion Delegate
class _NnMaterialLocalizationsDelegate
extends LocalizationsDelegate<MaterialLocalizations> {
const _NnMaterialLocalizationsDelegate();
@override
bool isSupported(Locale locale) => locale.languageCode == 'nn';
@override
Future<MaterialLocalizations> load(Locale locale) async {
final String localeName = intl.Intl.canonicalizedLocale(locale.toString());
// The locale (in this case `nn`) needs to be initialized into the custom
// date symbols and patterns setup that Flutter uses.
date_symbol_data_custom.initializeDateFormattingCustom(
locale: localeName,
patterns: nnLocaleDatePatterns,
symbols: intl.DateSymbols.deserializeFromMap(nnDateSymbols),
);
return SynchronousFuture<MaterialLocalizations>(
NnMaterialLocalizations(
localeName: localeName,
// The `intl` library's NumberFormat class is generated from CLDR data
// (see https://github.com/dart-lang/i18n/blob/main/pkgs/intl/lib/number_symbols_data.dart).
// Unfortunately, there is no way to use a locale that isn't defined in
// this map and the only way to work around this is to use a listed
// locale's NumberFormat symbols. So, here we use the number formats
// for 'en_US' instead.
decimalFormat: intl.NumberFormat('#,##0.###', 'en_US'),
twoDigitZeroPaddedFormat: intl.NumberFormat('00', 'en_US'),
// DateFormat here will use the symbols and patterns provided in the
// `date_symbol_data_custom.initializeDateFormattingCustom` call above.
// However, an alternative is to simply use a supported locale's
// DateFormat symbols, similar to NumberFormat above.
fullYearFormat: intl.DateFormat('y', localeName),
compactDateFormat: intl.DateFormat('yMd', localeName),
shortDateFormat: intl.DateFormat('yMMMd', localeName),
mediumDateFormat: intl.DateFormat('EEE, MMM d', localeName),
longDateFormat: intl.DateFormat('EEEE, MMMM d, y', localeName),
yearMonthFormat: intl.DateFormat('MMMM y', localeName),
shortMonthDayFormat: intl.DateFormat('MMM d'),
),
);
}
@override
bool shouldReload(_NnMaterialLocalizationsDelegate old) => false;
}
// #enddocregion Delegate
/// A custom set of localizations for the 'nn' locale. In this example, only
/// the value for openAppDrawerTooltip was modified to use a custom message as
/// an example. Everything else uses the American English (en_US) messages
/// and formatting.
class NnMaterialLocalizations extends GlobalMaterialLocalizations {
const NnMaterialLocalizations({
super.localeName = 'nn',
required super.fullYearFormat,
required super.compactDateFormat,
required super.shortDateFormat,
required super.mediumDateFormat,
required super.longDateFormat,
required super.yearMonthFormat,
required super.shortMonthDayFormat,
required super.decimalFormat,
required super.twoDigitZeroPaddedFormat,
});
// #docregion Getters
@override
String get moreButtonTooltip => r'More';
@override
String get aboutListTileTitleRaw => r'About $applicationName';
@override
String get alertDialogLabel => r'Alert';
// #enddocregion Getters
@override
String get anteMeridiemAbbreviation => r'AM';
@override
String get backButtonTooltip => r'Back';
@override
String get cancelButtonLabel => r'CANCEL';
@override
String get closeButtonLabel => r'CLOSE';
@override
String get closeButtonTooltip => r'Close';
@override
String get collapsedIconTapHint => r'Expand';
@override
String get continueButtonLabel => r'CONTINUE';
@override
String get copyButtonLabel => r'COPY';
@override
String get cutButtonLabel => r'CUT';
@override
String get deleteButtonTooltip => r'Delete';
@override
String get dialogLabel => r'Dialog';
@override
String get drawerLabel => r'Navigation menu';
@override
String get expandedIconTapHint => r'Collapse';
@override
String get firstPageTooltip => r'First page';
@override
String get hideAccountsLabel => r'Hide accounts';
@override
String get lastPageTooltip => r'Last page';
@override
String get licensesPageTitle => r'Licenses';
@override
String get modalBarrierDismissLabel => r'Dismiss';
@override
String get nextMonthTooltip => r'Next month';
@override
String get nextPageTooltip => r'Next page';
@override
String get okButtonLabel => r'OK';
@override
// A custom drawer tooltip message.
String get openAppDrawerTooltip => r'Custom Navigation Menu Tooltip';
// #docregion Raw
@override
String get pageRowsInfoTitleRaw => r'$firstRow–$lastRow of $rowCount';
@override
String get pageRowsInfoTitleApproximateRaw =>
r'$firstRow–$lastRow of about $rowCount';
// #enddocregion Raw
@override
String get pasteButtonLabel => r'PASTE';
@override
String get popupMenuLabel => r'Popup menu';
@override
String get menuBarMenuLabel => r'Menu Bar Label';
@override
String get postMeridiemAbbreviation => r'PM';
@override
String get previousMonthTooltip => r'Previous month';
@override
String get previousPageTooltip => r'Previous page';
@override
String get refreshIndicatorSemanticLabel => r'Refresh';
@override
String? get remainingTextFieldCharacterCountFew => null;
@override
String? get remainingTextFieldCharacterCountMany => null;
@override
String get remainingTextFieldCharacterCountOne => r'1 character remaining';
@override
String get remainingTextFieldCharacterCountOther =>
r'$remainingCount characters remaining';
@override
String? get remainingTextFieldCharacterCountTwo => null;
@override
String get remainingTextFieldCharacterCountZero => r'No characters remaining';
@override
String get reorderItemDown => r'Move down';
@override
String get reorderItemLeft => r'Move left';
@override
String get reorderItemRight => r'Move right';
@override
String get reorderItemToEnd => r'Move to the end';
@override
String get reorderItemToStart => r'Move to the start';
@override
String get reorderItemUp => r'Move up';
@override
String get rowsPerPageTitle => r'Rows per page:';
@override
ScriptCategory get scriptCategory => ScriptCategory.englishLike;
@override
String get searchFieldLabel => r'Search';
@override
String get selectAllButtonLabel => r'SELECT ALL';
@override
String? get selectedRowCountTitleFew => null;
@override
String? get selectedRowCountTitleMany => null;
@override
String get selectedRowCountTitleOne => r'1 item selected';
@override
String get selectedRowCountTitleOther => r'$selectedRowCount items selected';
@override
String? get selectedRowCountTitleTwo => null;
@override
String get selectedRowCountTitleZero => r'No items selected';
@override
String get showAccountsLabel => r'Show accounts';
@override
String get showMenuTooltip => r'Show menu';
@override
String get signedInLabel => r'Signed in';
@override
String get tabLabelRaw => r'Tab $tabIndex of $tabCount';
@override
TimeOfDayFormat get timeOfDayFormatRaw => TimeOfDayFormat.h_colon_mm_space_a;
@override
String get timePickerHourModeAnnouncement => r'Select hours';
@override
String get timePickerMinuteModeAnnouncement => r'Select minutes';
@override
String get viewLicensesButtonLabel => r'VIEW LICENSES';
@override
List<String> get narrowWeekdays =>
const <String>['S', 'M', 'T', 'W', 'T', 'F', 'S'];
@override
int get firstDayOfWeekIndex => 0;
static const LocalizationsDelegate<MaterialLocalizations> delegate =
_NnMaterialLocalizationsDelegate();
@override
String get calendarModeButtonLabel => r'Switch to calendar';
@override
String get dateHelpText => r'mm/dd/yyyy';
@override
String get dateInputLabel => r'Enter Date';
@override
String get dateOutOfRangeLabel => r'Out of range.';
@override
String get datePickerHelpText => r'SELECT DATE';
@override
String get dateRangeEndDateSemanticLabelRaw => r'End date $fullDate';
@override
String get dateRangeEndLabel => r'End Date';
@override
String get dateRangePickerHelpText => 'SELECT RANGE';
@override
String get dateRangeStartDateSemanticLabelRaw => 'Start date \$fullDate';
@override
String get dateRangeStartLabel => 'Start Date';
@override
String get dateSeparator => '/';
@override
String get dialModeButtonLabel => 'Switch to dial picker mode';
@override
String get inputDateModeButtonLabel => 'Switch to input';
@override
String get inputTimeModeButtonLabel => 'Switch to text input mode';
@override
String get invalidDateFormatLabel => 'Invalid format.';
@override
String get invalidDateRangeLabel => 'Invalid range.';
@override
String get invalidTimeLabel => 'Enter a valid time';
@override
String get licensesPackageDetailTextOther => '\$licenseCount licenses';
@override
String get saveButtonLabel => 'SAVE';
@override
String get selectYearSemanticsLabel => 'Select year';
@override
String get timePickerDialHelpText => 'SELECT TIME';
@override
String get timePickerHourLabel => 'Hour';
@override
String get timePickerInputHelpText => 'ENTER TIME';
@override
String get timePickerMinuteLabel => 'Minute';
@override
String get unspecifiedDate => 'Date';
@override
String get unspecifiedDateRange => 'Date Range';
@override
String get keyboardKeyAlt => 'Alt';
@override
String get keyboardKeyAltGraph => 'AltGr';
@override
String get keyboardKeyBackspace => 'Backspace';
@override
String get keyboardKeyCapsLock => 'Caps Lock';
@override
String get keyboardKeyChannelDown => 'Channel Down';
@override
String get keyboardKeyChannelUp => 'Channel Up';
@override
String get keyboardKeyControl => 'Ctrl';
@override
String get keyboardKeyDelete => 'Del';
@override
String get keyboardKeyEject => 'Eject';
@override
String get keyboardKeyEnd => 'End';
@override
String get keyboardKeyEscape => 'Esc';
@override
String get keyboardKeyFn => 'Fn';
@override
String get keyboardKeyHome => 'Home';
@override
String get keyboardKeyInsert => 'Insert';
@override
String get keyboardKeyMeta => 'Meta';
@override
String get keyboardKeyMetaMacOs => 'Command';
@override
String get keyboardKeyMetaWindows => 'Win';
@override
String get keyboardKeyNumLock => 'Num Lock';
@override
String get keyboardKeyNumpad0 => 'Num 0';
@override
String get keyboardKeyNumpad1 => 'Num 1';
@override
String get keyboardKeyNumpad2 => 'Num 2';
@override
String get keyboardKeyNumpad3 => 'Num 3';
@override
String get keyboardKeyNumpad4 => 'Num 4';
@override
String get keyboardKeyNumpad5 => 'Num 5';
@override
String get keyboardKeyNumpad6 => 'Num 6';
@override
String get keyboardKeyNumpad7 => 'Num 7';
@override
String get keyboardKeyNumpad8 => 'Num 8';
@override
String get keyboardKeyNumpad9 => 'Num 9';
@override
String get keyboardKeyNumpadAdd => 'Num +';
@override
String get keyboardKeyNumpadComma => 'Num ,';
@override
String get keyboardKeyNumpadDecimal => 'Num .';
@override
String get keyboardKeyNumpadDivide => 'Num /';
@override
String get keyboardKeyNumpadEnter => 'Num Enter';
@override
String get keyboardKeyNumpadEqual => 'Num =';
@override
String get keyboardKeyNumpadMultiply => 'Num *';
@override
String get keyboardKeyNumpadParenLeft => 'Num (';
@override
String get keyboardKeyNumpadParenRight => 'Num )';
@override
String get keyboardKeyNumpadSubtract => 'Num -';
@override
String get keyboardKeyPageDown => 'PgDown';
@override
String get keyboardKeyPageUp => 'PgUp';
@override
String get keyboardKeyPower => 'Power';
@override
String get keyboardKeyPowerOff => 'Power Off';
@override
String get keyboardKeyPrintScreen => 'Print Screen';
@override
String get keyboardKeyScrollLock => 'Scroll Lock';
@override
String get keyboardKeySelect => 'Select';
@override
String get keyboardKeyShift => 'Shift';
@override
String get keyboardKeySpace => 'Space';
@override
String get scrimOnTapHintRaw => r'Close $modalRouteContentName';
@override
String get bottomSheetLabel => 'Bottom Sheet';
@override
String get currentDateLabel => 'Today';
@override
String get scrimLabel => 'Scrim';
@override
String get collapsedHint => 'Expanded';
@override
String get expandedHint => 'Collapsed';
@override
String get expansionTileCollapsedHint => 'double tap to expand';
@override
String get expansionTileCollapsedTapHint => 'Expand for more details';
@override
String get expansionTileExpandedHint => 'double tap to collapse';
@override
String get expansionTileExpandedTapHint => 'Collapse';
@override
String get scanTextButtonLabel => 'Scan text';
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Dismiss menu';
@override
String get searchWebButtonLabel => 'Search web';
@override
String get shareButtonLabel => 'Share...';
}
| website/examples/internationalization/add_language/lib/nn_intl.dart/0 | {
"file_path": "website/examples/internationalization/add_language/lib/nn_intl.dart",
"repo_id": "website",
"token_count": 6564
} | 1,362 |
// Basic Flutter widget test.
// Learn more at https://docs.flutter.dev/testing/overview#widget-tests.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:interactive/main.dart';
void main() {
testWidgets('Example app smoke test', (tester) async {
await tester.pumpWidget(const MyApp());
expect(find.text('Oeschinen Lake Campground'), findsOneWidget);
expect(find.text('ROUTE'), findsOneWidget);
expect(find.byIcon(Icons.star), findsOneWidget);
expect(find.text('41'), findsOneWidget);
await tester.tap(find.byIcon(Icons.star));
await tester.pump();
expect(find.byIcon(Icons.star_border), findsOneWidget);
expect(find.text('40'), findsOneWidget);
await tester.tap(find.byIcon(Icons.star_border));
await tester.pump();
expect(find.byIcon(Icons.star), findsOneWidget);
expect(find.text('41'), findsOneWidget);
});
}
| website/examples/layout/lakes/interactive/test/widget_test.dart/0 | {
"file_path": "website/examples/layout/lakes/interactive/test/widget_test.dart",
"repo_id": "website",
"token_count": 335
} | 1,363 |
// Basic Flutter widget test.
// Learn more at https://docs.flutter.dev/testing/overview#widget-tests.
import 'package:flutter_test/flutter_test.dart';
import 'package:layout/main.dart';
void main() {
testWidgets('Example app smoke test', (tester) async {
await tester.pumpWidget(const MyApp());
expect(find.text('Hello World'), findsOneWidget);
});
}
| website/examples/layout/non_material/test/widget_test.dart/0 | {
"file_path": "website/examples/layout/non_material/test/widget_test.dart",
"repo_id": "website",
"token_count": 124
} | 1,364 |
import 'package:flutter/cupertino.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: HomePage(),
);
}
}
// #docregion Weather
enum Weather {
rainy,
windy,
sunny,
}
// #enddocregion Weather
// #docregion HomePageViewModel
@immutable
class HomePageViewModel {
const HomePageViewModel();
Future<Weather> load() async {
await Future.delayed(const Duration(seconds: 1));
return Weather.sunny;
}
}
// #enddocregion HomePageViewModel
// #docregion HomePageWidget
class HomePage extends StatelessWidget {
const HomePage({super.key});
final HomePageViewModel viewModel = const HomePageViewModel();
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
// Feed a FutureBuilder to your widget tree.
child: FutureBuilder<Weather>(
// Specify the Future that you want to track.
future: viewModel.load(),
builder: (context, snapshot) {
// A snapshot is of type `AsyncSnapshot` and contains the
// state of the Future. By looking if the snapshot contains
// an error or if the data is null, you can decide what to
// show to the user.
if (snapshot.hasData) {
return Center(
child: Text(
snapshot.data.toString(),
),
);
} else {
return const Center(
child: CupertinoActivityIndicator(),
);
}
},
),
);
}
}
// #enddocregion HomePageWidget
| website/examples/resources/dart_swift_concurrency/lib/async_weather.dart/0 | {
"file_path": "website/examples/resources/dart_swift_concurrency/lib/async_weather.dart",
"repo_id": "website",
"token_count": 667
} | 1,365 |
import 'package:flutter/material.dart';
class ProblemWidget extends StatelessWidget {
const ProblemWidget({super.key});
@override
// #docregion Problem
Widget build(BuildContext context) {
// Don't do this.
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text('Alert Dialog'),
);
});
return const Center(
child: Column(
children: <Widget>[
Text('Show Material Dialog'),
],
),
);
}
// #enddocregion Problem
}
// #docregion Fix
class FirstScreen extends StatelessWidget {
const FirstScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Screen'),
),
body: Center(
child: ElevatedButton(
child: const Text('Launch screen'),
onPressed: () {
// Navigate to the second screen using a named route.
Navigator.pushNamed(context, '/second');
// Immediately show a dialog upon loading the second screen.
Navigator.push(
context,
PageRouteBuilder(
barrierDismissible: true,
opaque: false,
pageBuilder: (_, anim1, anim2) => const MyDialog(),
),
);
},
),
),
);
}
}
// #enddocregion Fix
class MyDialog extends StatelessWidget {
const MyDialog({super.key});
@override
Widget build(BuildContext context) {
return const AlertDialog(
title: Text('Alert Dialog'),
);
}
}
| website/examples/testing/common_errors/lib/set_state_build.dart/0 | {
"file_path": "website/examples/testing/common_errors/lib/set_state_build.dart",
"repo_id": "website",
"token_count": 719
} | 1,366 |
import 'package:flextras/flextras.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../global/device_type.dart';
class FocusExamplesPage extends StatelessWidget {
const FocusExamplesPage({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(Insets.extraLarge),
child: Center(
child: SeparatedColumn(
separatorBuilder: () => const SizedBox(height: 5),
mainAxisSize: MainAxisSize.min,
children: [
// Basic widget that can accept traversal, built with FocusableActionDetector
const Text('BasicActionDetector:'),
const BasicActionDetector(),
const SizedBox(height: 10),
// Clickable widget that can accept traversal, built with FocusableActionDetector
const Text('AdvancedActionDetector:'),
const ClickableActionDetector(),
const SizedBox(height: 10),
// A totally custom control, built by stacking together various widgets
const Text('CustomControl:'),
const ClickableControl(),
_TextListener(),
],
),
),
);
}
}
class _TextListener extends StatefulWidget {
@override
State<_TextListener> createState() => __TextListenerState();
}
class __TextListenerState extends State<_TextListener> {
FocusNode focusNode = FocusNode();
// #docregion focus-keyboard-listener
@override
Widget build(BuildContext context) {
return Focus(
onKeyEvent: (node, event) {
if (event is KeyDownEvent) {
print(event.logicalKey);
}
return KeyEventResult.ignored;
},
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: const TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
),
),
),
);
}
}
// #enddocregion focus-keyboard-listener
class BasicActionDetector extends StatefulWidget {
const BasicActionDetector({super.key});
@override
State<BasicActionDetector> createState() => _BasicActionDetectorState();
}
// #docregion _BasicActionDetectorState
class _BasicActionDetectorState extends State<BasicActionDetector> {
bool _hasFocus = false;
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
onFocusChange: (value) => setState(() => _hasFocus = value),
actions: <Type, Action<Intent>>{
ActivateIntent: CallbackAction<Intent>(onInvoke: (intent) {
print('Enter or Space was pressed!');
return null;
}),
},
child: Stack(
clipBehavior: Clip.none,
children: [
const FlutterLogo(size: 100),
// Position focus in the negative margin for a cool effect
if (_hasFocus)
Positioned(
left: -4,
top: -4,
bottom: -4,
right: -4,
child: _roundedBorder(),
)
],
),
);
}
}
// #enddocregion _BasicActionDetectorState
/// Uses [FocusableActionDetector]
class ClickableActionDetector extends StatefulWidget {
const ClickableActionDetector({super.key});
@override
State<ClickableActionDetector> createState() =>
_ClickableActionDetectorState();
}
class _ClickableActionDetectorState extends State<ClickableActionDetector> {
bool _hasFocus = false;
late final FocusNode _focusNode = FocusNode();
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
focusNode: _focusNode,
mouseCursor: SystemMouseCursors.click,
onFocusChange: (value) => setState(() => _hasFocus = value),
actions: <Type, Action<Intent>>{
ActivateIntent: CallbackAction<Intent>(onInvoke: (intent) {
_submit();
return null;
}),
},
child: GestureDetector(
onTap: () {
_focusNode.requestFocus();
_submit();
},
child: Logo(showBorder: _hasFocus),
),
);
}
void _submit() => print('Submit!');
}
// Example of a custom focus widget from scratch
class ClickableControl extends StatelessWidget {
const ClickableControl({super.key});
@override
Widget build(BuildContext context) {
return Focus(
// Process keyboard event
onKeyEvent: _handleKeyDown,
child: Builder(
builder: (context) {
// Check whether we have focus
bool hasFocus = Focus.of(context).hasFocus;
// #docregion MouseRegion
// Show hand cursor
return MouseRegion(
cursor: SystemMouseCursors.click,
// Request focus when clicked
child: GestureDetector(
onTap: () {
Focus.of(context).requestFocus();
_submit();
},
child: Logo(showBorder: hasFocus),
),
);
// #enddocregion MouseRegion
},
),
);
}
void _submit() => print('Submit!');
KeyEventResult _handleKeyDown(FocusNode node, KeyEvent event) {
if (event is KeyDownEvent &&
{LogicalKeyboardKey.enter, LogicalKeyboardKey.space}
.contains(event.logicalKey)) {
_submit();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
}
class Logo extends StatelessWidget {
const Logo({super.key, required this.showBorder});
final bool showBorder;
@override
Widget build(BuildContext context) {
return Stack(
clipBehavior: Clip.none,
children: [
// Content
const FlutterLogo(size: 100),
// Focus effect:
if (showBorder)
Positioned(
left: 0, top: -4, bottom: -4, right: -4, child: _roundedBorder())
],
);
}
}
Widget _roundedBorder() => Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.orange),
borderRadius: BorderRadius.circular(6),
),
);
class MyFocusTraversalWidget extends StatelessWidget {
const MyFocusTraversalWidget({super.key});
@override
Widget build(BuildContext context) {
// #docregion FocusTraversalGroup
return Column(children: [
FocusTraversalGroup(
child: MyFormWithMultipleColumnsAndRows(),
),
SubmitButton(),
]);
// #enddocregion FocusTraversalGroup
}
}
class MyFormWithMultipleColumnsAndRows extends StatelessWidget {
// ignore: prefer_const_constructors_in_immutables
MyFormWithMultipleColumnsAndRows({super.key});
@override
Widget build(BuildContext context) {
return Form(
child: Container(),
);
}
}
class SubmitButton extends StatelessWidget {
// ignore: prefer_const_constructors_in_immutables
SubmitButton({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => {DoNothingAction /* Submit */},
child: const Text('Submit'),
);
}
}
class MyHoverWidget extends StatefulWidget {
const MyHoverWidget({super.key, required this.title});
final String title;
@override
State<MyHoverWidget> createState() => _MyHoverWidgetState();
}
class _MyHoverWidgetState extends State<MyHoverWidget> {
bool _isMouseOver = false;
@override
Widget build(BuildContext context) {
// #docregion MouseOver
return MouseRegion(
onEnter: (_) => setState(() => _isMouseOver = true),
onExit: (_) => setState(() => _isMouseOver = false),
onHover: (e) => print(e.localPosition),
child: Container(
height: 500,
color: _isMouseOver ? Colors.blue : Colors.black,
),
);
// #enddocregion MouseOver
}
}
| website/examples/ui/layout/adaptive_app_demos/lib/pages/focus_examples_page.dart/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/lib/pages/focus_examples_page.dart",
"repo_id": "website",
"token_count": 3120
} | 1,367 |
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
title: 'Flutter Tutorial',
home: TutorialHome(),
),
);
}
class TutorialHome extends StatelessWidget {
const TutorialHome({super.key});
@override
Widget build(BuildContext context) {
// Scaffold is a layout for
// the major Material Components.
return Scaffold(
appBar: AppBar(
leading: const IconButton(
icon: Icon(Icons.menu),
tooltip: 'Navigation menu',
onPressed: null,
),
title: const Text('Example title'),
actions: const [
IconButton(
icon: Icon(Icons.search),
tooltip: 'Search',
onPressed: null,
),
],
),
// body is the majority of the screen.
body: const Center(
child: Text('Hello, world!'),
),
floatingActionButton: const FloatingActionButton(
tooltip: 'Add', // used by assistive technologies
onPressed: null,
child: Icon(Icons.add),
),
);
}
}
| website/examples/ui/widgets_intro/lib/main_tutorial.dart/0 | {
"file_path": "website/examples/ui/widgets_intro/lib/main_tutorial.dart",
"repo_id": "website",
"token_count": 476
} | 1,368 |
{% for section in site.data.catalog.index %}
{% if section.name == include.category %}
{% assign category = section %}
{% break %}
{% endif %}
{% endfor %}
<div class="catalog">
<div class="category-description">
<p>{{category.description}}</p>
</div>
{% if category.subcategories and category.subcategories.size != 0 -%}
<ul>
{% for sub in category.subcategories -%}
<li><a href="#{{sub.name}}">{{sub.name}}</a></li>
{% endfor -%}
</ul>
{% endif -%}
<p>See more widgets in the <a href="/ui/widgets">widget catalog</a>.</p>
{% assign components = site.data.catalog.widgets | where_exp:"comp","comp.categories contains include.category" -%}
{% if components.size != 0 -%}
<div class="card-deck card-deck--responsive">
{% for comp in components -%}
<div class="card">
<a href="{{comp.link}}">
<div class="card-image-holder">
{{comp.image}}
</div>
</a>
<div class="card-body">
<a href="{{comp.link}}"><header class="card-title">{{comp.name}}</header></a>
<p class="card-text">{{ comp.description | truncatewords: 25 }}</p>
</div>
</div>
{% endfor -%}
</div>
{% endif -%}
{% if category.subcategories and category.subcategories.size != 0 -%}
{% for sub in category.subcategories -%}
{% assign components = site.data.catalog.widgets | where_exp:"comp","comp.subcategories contains sub.name" -%}
{% if components.size != 0 -%}
<h2 id="{{sub.name}}">{{sub.name}}</h2>
<div class="card-deck card-deck--responsive">
{% for comp in components -%}
<div class="card">
<a href="{{comp.link}}">
<div class="card-image-holder">
{{comp.image}}
</div>
</a>
<div class="card-body">
<a href="{{comp.link}}"><header class="card-title">{{comp.name}}</header></a>
<p class="card-text">{{ comp.description | truncatewords: 25 }}</p>
</div>
</div>
{% endfor -%}
</div>
{% endif -%}
{% endfor -%}
{% endif -%}
<p>See more widgets in the <a href="/ui/widgets">widget catalog</a>.</p>
</div>
| website/src/_includes/docs/catalogpage.html/0 | {
"file_path": "website/src/_includes/docs/catalogpage.html",
"repo_id": "website",
"token_count": 1349
} | 1,369 |
<?code-excerpt "animation/implicit/opacity5/lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:split-60:width-100%:height-532px:ga_id-fade_in_complete
// Copyright 2019 the Dart project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
import 'package:flutter/material.dart';
const owlUrl =
'https://raw.githubusercontent.com/flutter/website/main/src/assets/images/docs/owl.jpg';
class FadeInDemo extends StatefulWidget {
const FadeInDemo({super.key});
@override
State<FadeInDemo> createState() => _FadeInDemoState();
}
class _FadeInDemoState extends State<FadeInDemo> {
double opacity = 0;
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
return Column(children: <Widget>[
Image.network(owlUrl, height: height * 0.8),
TextButton(
child: const Text(
'Show Details',
style: TextStyle(color: Colors.blueAccent),
),
onPressed: () => setState(() {
opacity = 1;
}),
),
AnimatedOpacity(
duration: const Duration(seconds: 2),
opacity: opacity,
child: const Column(
children: [
Text('Type: Owl'),
Text('Age: 39'),
Text('Employment: None'),
],
),
)
]);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: FadeInDemo(),
),
),
);
}
}
void main() {
runApp(
const MyApp(),
);
}
```
| website/src/_includes/docs/implicit-animations/fade-in-complete.md/0 | {
"file_path": "website/src/_includes/docs/implicit-animations/fade-in-complete.md",
"repo_id": "website",
"token_count": 727
} | 1,370 |
{% assign terminal=include.terminal %}
### Download then install Flutter
{:.no_toc}
{% assign os = include.os %}
{% assign osl = os | downcase | replace: "chromeos","linux" %}
{% assign target = include.target %}
{% case os %}
{% when 'Windows' -%}
{% assign unzip='Expand-Archive .\' %}
{% assign path='C:\user\{username}\dev' %}
{% assign flutter-path='C:\user\{username}\dev\flutter' %}
{% assign terminal='PowerShell' %}
{% assign prompt='C:>' %}
{% assign prompt2=path | append: '>' %}
{% assign diroptions='`%USERPROFILE%` (`C:\Users\{username}`) or `%LOCALAPPDATA%` (`C:\Users\{username}\AppData\Local`)' %}
{% assign dirinstall='`%USERPROFILE%\dev\`' %}
{% assign dirdl='%USERPROFILE%\Downloads' %}
{% assign ps-dir-dl='$env:USERPROFILE\Downloads\' %}
{% assign ps-dir-target='$env:USERPROFILE\dev\' %}
{% capture uz -%}
{{prompt}} Expand-Archive `
–Path {{ps-dir-dl}}flutter_sdk_v1.0.0.zip `
-Destination {{ps-dir-target}}
{%- endcapture %}
{% when "macOS" -%}
{% assign diroptions='`~/development/`' %}
{% assign dirinstall='`~/development/`' %}
{% assign unzip='unzip' %}
{% assign path='~/development/' %}
{% assign flutter-path='~/development/flutter' %}
{% assign terminal='the Terminal' %}
{% assign prompt='$' %}
{% assign dirdl='~/Downloads/' %}
{% capture uz -%}
{{prompt}} {{unzip}} {{dirdl}}flutter_sdk_v1.0.0.zip -d {{path}}
{%- endcapture %}
{% else -%}
{% assign diroptions='`/usr/bin/`' %}
{% assign dirinstall='`/usr/bin/`' %}
{% assign unzip='unzip' %}
{% assign path='/usr/bin/' %}
{% assign flutter-path='/usr/bin/flutter' %}
{% assign terminal='a shell' %}
{% assign prompt='$' %}
{% assign dirdl='~/Downloads/' %}
{% capture uz -%}
{{prompt}} {{dirdl}}flutter_sdk_v1.0.0.zip {{path}}
{%- endcapture %}
{% endcase -%}
To install Flutter,
download the Flutter SDK bundle from its archive,
move the bundle to where you want it stored,
then extract the SDK.
1. Download the following installation bundle to get the latest
{{site.sdk.channel}} release of the Flutter SDK.
{% if os=='macOS' %}
| Intel Processor | | Apple Silicon |
|-----------------|-|---------------|
| [(loading...)](#){:.download-latest-link-{{osl}}.btn.btn-primary} | | [(loading...)](#){:.download-latest-link-{{osl}}-arm64.apple-silicon.btn.btn-primary} |
{% else %}
[(loading...)](#){:.download-latest-link-{{osl}}.btn.btn-primary}
{% endif -%}
For other release channels, and older builds, check out the [SDK archive][].
The Flutter SDK should download to the {{os}} default download directory:
`{{dirdl}}`.
{% if os=='Windows' %}
If you changed the location of the Downloads directory,
replace this path with that path.
To find your Downloads directory location,
check out this [Microsoft Community post][move-dl].
{% endif %}
1. Create a folder where you can install Flutter.
Consider creating a directory at {{diroptions}}.
{% if os == "Windows" -%}
{% include docs/install/admonitions/install-paths.md %}
{% endif %}
1. Extract the zip file into the directory you want to store the Flutter SDK.
```terminal
{{uz}}
```
When finished, the Flutter SDK should be in the `{{flutter-path}}` directory.
[SDK archive]: /release/archive
[move-dl]: https://answers.microsoft.com/en-us/windows/forum/all/move-download-folder-to-other-drive-in-windows-10/67d58118-4ccd-473e-a3da-4e79fdb4c878
{% case os %}
{% when 'Windows' %}
{% include docs/install/reqs/windows/set-path.md terminal=terminal target=target %}
{% when 'macOS' %}
{% include docs/install/reqs/macos/set-path.md terminal=terminal
target=target dir=dirinstall %}
{% else %}
{% include docs/install/reqs/linux/set-path.md terminal=terminal target=target %}
{% endcase %}
| website/src/_includes/docs/install/flutter/download.md/0 | {
"file_path": "website/src/_includes/docs/install/flutter/download.md",
"repo_id": "website",
"token_count": 1488
} | 1,371 |
{% assign terminal=include.terminal %}
### Remove Flutter from your macOS PATH
{:.no_toc}
To remove Flutter commands from {{terminal}},
remove Flutter to the `PATH` environment variable.
This guide presumes your [Mac runs the latest default shell][zsh-mac], `zsh`.
Zsh uses the `.zshenv` file for [environment variables][envvar].
1. Launch your preferred text editor.
1. Open the Zsh environmental variable file `~/.zshenv`
1. Remove the following line at the end of your `~/.zshenv` file.
```conf
export PATH=$HOME/development/flutter/bin:$PATH
```
1. Save your `~/.zshenv` file.
1. To apply this change, restart all open terminal sessions.
If you use another shell,
check out [this tutorial on removing a directory from your PATH][other-path].
[zsh-mac]: https://support.apple.com/en-us/102360
[envvar]: https://zsh.sourceforge.io/Intro/intro_3.html
[other-path]: https://phoenixnap.com/kb/linux-add-to-path
| website/src/_includes/docs/install/reqs/macos/unset-path.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/macos/unset-path.md",
"repo_id": "website",
"token_count": 307
} | 1,372 |
## Performance
Platform views in Flutter come with performance trade-offs.
For example, in a typical Flutter app, the Flutter UI is composed
on a dedicated raster thread. This allows Flutter apps to be fast,
as the main platform thread is rarely blocked.
While a platform view is rendered with hybrid composition,
the Flutter UI is composed from the platform thread,
which competes with other tasks like handling OS or plugin messages.
Prior to Android 10, hybrid composition copied each Flutter frame
out of the graphic memory into main memory, and then copied it back
to a GPU texture. As this copy happens per frame, the performance of
the entire Flutter UI might be impacted. In Android 10 or above, the
graphics memory is copied only once.
Virtual display, on the other hand,
makes each pixel of the native view
flow through additional intermediate graphic buffers,
which cost graphic memory and drawing performance.
For complex cases, there are some techniques that
can be used to mitigate these issues.
For example, you could use a placeholder texture
while an animation is happening in Dart.
In other words, if an animation is slow while a
platform view is rendered,
then consider taking a screenshot of the
native view and rendering it as a texture.
For more information, see:
* [`TextureLayer`][]
* [`TextureRegistry`][]
* [`FlutterTextureRegistry`][]
* [`FlutterImageView`][]
[`FlutterImageView`]: {{site.api}}/javadoc/io/flutter/embedding/android/FlutterImageView.html
[`FlutterTextureRegistry`]: {{site.api}}/ios-embedder/protocol_flutter_texture_registry-p.html
[`TextureLayer`]: {{site.api}}/flutter/rendering/TextureLayer-class.html
[`TextureRegistry`]: {{site.api}}/javadoc/io/flutter/view/TextureRegistry.html
| website/src/_includes/docs/platform-view-perf.md/0 | {
"file_path": "website/src/_includes/docs/platform-view-perf.md",
"repo_id": "website",
"token_count": 461
} | 1,373 |
<div class="snackbar {{ include.class }}">
<div class="snackbar__container">
<div class="snackbar__label">
{{ include.label }}
</div>
{% if include.action -%}
<button class="snackbar__action btn btn-link">{{ include.action }}</button>
{% endif -%}
</div>
</div>
| website/src/_includes/snackbar.html/0 | {
"file_path": "website/src/_includes/snackbar.html",
"repo_id": "website",
"token_count": 118
} | 1,374 |
module Jekyll
module Tags
# A block that preserves the indentation of its content.
#
# This is useful for use in markdown where indentation can be significant.
class Indent < Liquid::Block
# def initialize(tag_name, tag_arg_raw, liquid_parse_context) end
def render(liquid_context)
content = super
lines = content.split(/\n/);
return content if lines.length <= 1
# Get the indentation before the closing tag.
indentation = lines.last.match(/^[ \t]*/)[0]
lines = _trimLeadingWhitespace(lines)
indented_lines = lines.map{|s| indentation + s}
# Actually, don't indent the first line since it will be
# indented by the amount of the opening tag
indented_lines[0].sub!(/^[ \t]+/, '')
indented_lines.join("\n")
end
# @return a copy of the input lines array, with lines unindented by the maximal amount of whitespace possible
# without affecting relative (non-whitespace) line indentation.
def _trimLeadingWhitespace(lines)
# 1. Trim leading blank lines
while lines.first =~ /^\s*$/ do lines.shift; end
# 2. Trim trailing blank lines. Also determine minimal
# indentation for the entire block.
# Last line should consist of the indentation of the end tag
# (when it is on a separate line).
last_line = lines.last =~ /^\s*$/ ? lines.pop : ''
while lines.last =~ /^\s*$/ do lines.pop end
min_len = last_line.length
non_blank_lines = lines.reject { |s| s.match(/^\s*$/) }
# 3. Determine length of leading spaces to be trimmed
len = non_blank_lines.map{ |s|
matches = s.match(/^[ \t]*/)
matches ? matches[0].length : 0 }.min
# Only trim the excess relative to min_len
len = len < min_len ? min_len : len - min_len
len == 0 ? lines : lines.map{|s| s.length < len ? s : s.sub(/^[ \t]{#{len}}/, '')}
end
end
end
end
Liquid::Template.register_tag('indent'.freeze, Jekyll::Tags::Indent)
| website/src/_plugins/indent.rb/0 | {
"file_path": "website/src/_plugins/indent.rb",
"repo_id": "website",
"token_count": 842
} | 1,375 |
@use '../vendor/bootstrap';
#cookie-notice {
background-color: white;
padding: 2.5rem 0;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
box-shadow: -1px 1px 4px rgba(0, 0, 0, 0.3);
opacity: 0;
display: none;
z-index: bootstrap.$zindex-popover;
@keyframes fadein {
0% { opacity: 0; }
100% { opacity: 1; }
}
a.btn {
padding-left: 1.5rem;
padding-right: 1.5rem;
}
&.show {
display: block;
animation-duration: 500ms;
animation-delay: 200ms;
animation-name: fadein;
animation-iteration-count: 1;
animation-timing-function: ease;
animation-fill-mode: forwards;
}
.container {
display: flex;
justify-content: space-between;
align-items: center;
max-width: 1080px;
p {
font-size: 1rem;
line-height: 1.6;
margin-right: 2rem;
margin-bottom: 0;
}
}
}
| website/src/_sass/components/_cookie-notice.scss/0 | {
"file_path": "website/src/_sass/components/_cookie-notice.scss",
"repo_id": "website",
"token_count": 387
} | 1,376 |
---
title: Add a Flutter screen to an Android app
short-title: Add a Flutter screen
description: >
Learn how to add a single Flutter screen to your existing Android app.
---
This guide describes how to add a single Flutter screen to an
existing Android app. A Flutter screen can be added as a normal,
opaque screen, or as a see-through, translucent screen.
Both options are described in this guide.
## Add a normal Flutter screen
<img src='/assets/images/docs/development/add-to-app/android/add-flutter-screen/add-single-flutter-screen_header.png'
class="mw-100" alt="Add Flutter Screen Header">
### Step 1: Add FlutterActivity to AndroidManifest.xml
Flutter provides [`FlutterActivity`][] to display a Flutter
experience within an Android app. Like any other [`Activity`][],
`FlutterActivity` must be registered in your
`AndroidManifest.xml`. Add the following XML to your
`AndroidManifest.xml` file under your `application` tag:
```xml
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
/>
```
The reference to `@style/LaunchTheme` can be replaced
by any Android theme that want to apply to your `FlutterActivity`.
The choice of theme dictates the colors applied to
Android's system chrome, like Android's navigation bar, and to
the background color of the `FlutterActivity` just before
the Flutter UI renders itself for the first time.
### Step 2: Launch FlutterActivity
With `FlutterActivity` registered in your manifest file,
add code to launch `FlutterActivity` from whatever point
in your app that you'd like. The following example shows
`FlutterActivity` being launched from an `OnClickListener`.
{{site.alert.note}}
Make sure to use the following import:
```java
import io.flutter.embedding.android.FlutterActivity;
```
{{site.alert.end}}
{% samplecode default-activity-launch %}
{% sample Java %}
<?code-excerpt title="ExistingActivity.java"?>
```java
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
FlutterActivity.createDefaultIntent(currentActivity)
);
}
});
```
{% sample Kotlin %}
<?code-excerpt title="ExistingActivity.kt"?>
```kotlin
myButton.setOnClickListener {
startActivity(
FlutterActivity.createDefaultIntent(this)
)
}
```
{% endsamplecode %}
The previous example assumes that your Dart entrypoint
is called `main()`, and your initial Flutter route is '/'.
The Dart entrypoint can't be changed using `Intent`,
but the initial route can be changed using `Intent`.
The following example demonstrates how to launch a
`FlutterActivity` that initially renders a custom
route in Flutter.
{% samplecode custom-activity-launch %}
{% sample Java %}
<?code-excerpt title="ExistingActivity.java"?>
```java
myButton.addOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("/my_route")
.build(currentActivity)
);
}
});
```
{% sample Kotlin %}
<?code-excerpt title="ExistingActivity.kt"?>
```kotlin
myButton.setOnClickListener {
startActivity(
FlutterActivity
.withNewEngine()
.initialRoute("/my_route")
.build(this)
)
}
```
{% endsamplecode %}
Replace `"/my_route"` with your desired initial route.
The use of the `withNewEngine()` factory method
configures a `FlutterActivity` that internally create
its own [`FlutterEngine`][] instance. This comes with a
non-trivial initialization time. The alternative approach
is to instruct `FlutterActivity` to use a pre-warmed,
cached `FlutterEngine`, which minimizes Flutter's
initialization time. That approach is discussed next.
### Step 3: (Optional) Use a cached FlutterEngine
Every `FlutterActivity` creates its own `FlutterEngine`
by default. Each `FlutterEngine` has a non-trivial
warm-up time. This means that launching a standard
`FlutterActivity` comes with a brief delay before your Flutter
experience becomes visible. To minimize this delay,
you can warm up a `FlutterEngine` before arriving at
your `FlutterActivity`, and then you can use
your pre-warmed `FlutterEngine` instead.
To pre-warm a `FlutterEngine`, find a reasonable
location in your app to instantiate a `FlutterEngine`.
The following example arbitrarily pre-warms a
`FlutterEngine` in the `Application` class:
{% samplecode prewarm-engine %}
{% sample Java %}
<?code-excerpt title="MyApplication.java"?>
```java
public class MyApplication extends Application {
public FlutterEngine flutterEngine;
@Override
public void onCreate() {
super.onCreate();
// Instantiate a FlutterEngine.
flutterEngine = new FlutterEngine(this);
// Start executing Dart code to pre-warm the FlutterEngine.
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartEntrypoint.createDefault()
);
// Cache the FlutterEngine to be used by FlutterActivity.
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine);
}
}
```
{% sample Kotlin %}
<?code-excerpt title="MyApplication.kt"?>
```kotlin
class MyApplication : Application() {
lateinit var flutterEngine : FlutterEngine
override fun onCreate() {
super.onCreate()
// Instantiate a FlutterEngine.
flutterEngine = FlutterEngine(this)
// Start executing Dart code to pre-warm the FlutterEngine.
flutterEngine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
)
// Cache the FlutterEngine to be used by FlutterActivity.
FlutterEngineCache
.getInstance()
.put("my_engine_id", flutterEngine)
}
}
```
{% endsamplecode %}
The ID passed to the [`FlutterEngineCache`][] can be whatever you want.
Make sure that you pass the same ID to any `FlutterActivity`
or [`FlutterFragment`][] that should use the cached `FlutterEngine`.
Using `FlutterActivity` with a cached `FlutterEngine`
is discussed next.
{{site.alert.note}}
To warm up a `FlutterEngine`, you must execute a Dart
entrypoint. Keep in mind that the moment
`executeDartEntrypoint()` is invoked,
your Dart entrypoint method begins executing.
If your Dart entrypoint invokes `runApp()`
to run a Flutter app, then your Flutter app behaves as if it
were running in a window of zero size until this
`FlutterEngine` is attached to a `FlutterActivity`,
`FlutterFragment`, or `FlutterView`. Make sure that your app
behaves appropriately between the time you warm it up and
the time you display Flutter content.
{{site.alert.end}}
With a pre-warmed, cached `FlutterEngine`, you now need
to instruct your `FlutterActivity` to use the cached
`FlutterEngine` instead of creating a new one.
To accomplish this, use `FlutterActivity`'s `withCachedEngine()`
builder:
{% samplecode cached-engine-activity-launch %}
{% sample Java %}
<?code-excerpt title="ExistingActivity.java"?>
```java
myButton.addOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.build(currentActivity)
);
}
});
```
{% sample Kotlin %}
<?code-excerpt title="ExistingActivity.kt"?>
```kotlin
myButton.setOnClickListener {
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.build(this)
)
}
```
{% endsamplecode %}
When using the `withCachedEngine()` factory method,
pass the same ID that you used when caching the desired
`FlutterEngine`.
Now, when you launch `FlutterActivity`,
there is significantly less delay in
the display of Flutter content.
{{site.alert.note}}
When using a cached `FlutterEngine`, that `FlutterEngine` outlives any
`FlutterActivity` or `FlutterFragment` that displays it. Keep in
mind that Dart code begins executing as soon as you pre-warm the
`FlutterEngine`, and continues executing after the destruction of your
`FlutterActivity`/`FlutterFragment`. To stop executing and clear resources,
obtain your `FlutterEngine` from the `FlutterEngineCache` and destroy the
`FlutterEngine` with `FlutterEngine.destroy()`.
{{site.alert.end}}
{{site.alert.note}}
Runtime performance isn't the only reason that you might
pre-warm and cache a `FlutterEngine`.
A pre-warmed `FlutterEngine` executes Dart code independent
from a `FlutterActivity`, which allows such a `FlutterEngine`
to be used to execute arbitrary Dart code at any moment.
Non-UI application logic can be executed in a `FlutterEngine`,
like networking and data caching, and in background behavior
within a `Service` or elsewhere. When using a `FlutterEngine`
to execute behavior in the background, be sure to adhere to all
Android restrictions on background execution.
{{site.alert.end}}
{{site.alert.note}}
Flutter's debug/release builds have drastically different
performance characteristics. To evaluate the performance
of Flutter, use a release build.
{{site.alert.end}}
#### Initial route with a cached engine
{% include_relative _initial-route-cached-engine.md %}
## Add a translucent Flutter screen
<img src='/assets/images/docs/development/add-to-app/android/add-flutter-screen/add-single-flutter-screen-transparent_header.png'
class="mw-100" alt="Add Flutter Screen With Translucency Header">
Most full-screen Flutter experiences are opaque.
However, some apps would like to deploy a Flutter
screen that looks like a modal, for example,
a dialog or bottom sheet. Flutter supports translucent
`FlutterActivity`s out of the box.
To make your `FlutterActivity` translucent,
make the following changes to the regular process of
creating and launching a `FlutterActivity`.
### Step 1: Use a theme with translucency
Android requires a special theme property for `Activity`s that render
with a translucent background. Create or update an Android theme with the
following property:
```xml
<style name="MyTheme" parent="@style/MyParentTheme">
<item name="android:windowIsTranslucent">true</item>
</style>
```
Then, apply the translucent theme to your `FlutterActivity`.
```xml
<activity
android:name="io.flutter.embedding.android.FlutterActivity"
android:theme="@style/MyTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
/>
```
Your `FlutterActivity` now supports translucency.
Next, you need to launch your `FlutterActivity`
with explicit transparency support.
### Step 2: Start FlutterActivity with transparency
To launch your `FlutterActivity` with a transparent background,
pass the appropriate `BackgroundMode` to the `IntentBuilder`:
{% samplecode transparent-activity-launch %}
{% sample Java %}
<?code-excerpt title="ExistingActivity.java"?>
```java
// Using a new FlutterEngine.
startActivity(
FlutterActivity
.withNewEngine()
.backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
.build(context)
);
// Using a cached FlutterEngine.
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
.build(context)
);
```
{% sample Kotlin %}
<?code-excerpt title="ExistingActivity.kt"?>
```kotlin
// Using a new FlutterEngine.
startActivity(
FlutterActivity
.withNewEngine()
.backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
.build(this)
);
// Using a cached FlutterEngine.
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent)
.build(this)
);
```
{% endsamplecode %}
You now have a `FlutterActivity` with a transparent background.
{{site.alert.note}}
Make sure that your Flutter content also includes a
translucent background. If your Flutter UI paints a
solid background color, then it still appears as
though your `FlutterActivity` has an opaque background.
{{site.alert.end}}
[`FlutterActivity`]: {{site.api}}/javadoc/io/flutter/embedding/android/FlutterActivity.html
[`Activity`]: {{site.android-dev}}/reference/android/app/Activity
[`FlutterEngine`]: {{site.api}}/javadoc/io/flutter/embedding/engine/FlutterEngine.html
[`FlutterEngineCache`]: {{site.api}}/javadoc/io/flutter/embedding/engine/FlutterEngineCache.html
[`FlutterFragment`]: {{site.api}}/javadoc/io/flutter/embedding/android/FlutterFragment.html
| website/src/add-to-app/android/add-flutter-screen.md/0 | {
"file_path": "website/src/add-to-app/android/add-flutter-screen.md",
"repo_id": "website",
"token_count": 3841
} | 1,377 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="1.9999179in"
height="1.9999999in"
version="1.1"
viewBox="0 0 50.796725 50.798808"
id="svg11"
sodipodi:docname="windows-bug.svg"
inkscape:version="1.3.2 (091e20e, 2023-11-25)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs11" />
<sodipodi:namedview
id="namedview11"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="0.865"
inkscape:cx="245.66474"
inkscape:cy="90.751445"
inkscape:window-width="1392"
inkscape:window-height="942"
inkscape:window-x="1240"
inkscape:window-y="25"
inkscape:window-maximized="0"
inkscape:current-layer="svg11"
inkscape:document-units="in" />
<rect
x="1.4556705"
y="1.4556705"
width="21.166172"
height="21.166172"
id="rect8"
style="fill:#027dfd;stroke-width:0.916085;fill-opacity:1" />
<rect
x="28.174885"
y="1.4556705"
width="21.166172"
height="21.166172"
id="rect9"
style="fill:#027dfd;stroke-width:0.916085;fill-opacity:1" />
<rect
x="1.4556705"
y="28.17697"
width="21.166172"
height="21.166172"
id="rect10"
style="fill:#027dfd;stroke-width:0.916085;fill-opacity:1" />
<rect
x="28.174885"
y="28.17697"
width="21.166172"
height="21.166172"
id="rect11"
style="fill:#027dfd;stroke-width:0.916085;fill-opacity:1" />
</svg>
| website/src/assets/images/docs/brand-svg/windows-bug.svg/0 | {
"file_path": "website/src/assets/images/docs/brand-svg/windows-bug.svg",
"repo_id": "website",
"token_count": 921
} | 1,378 |
---
title: Update the UI based on orientation
description: Respond to a change in the screen's orientation.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/design/orientation"?>
In some situations,
you want to update the display of an app when the user
rotates the screen from portrait mode to landscape mode. For example,
the app might show one item after the next in portrait mode,
yet put those same items side-by-side in landscape mode.
In Flutter, you can build different layouts depending
on a given [`Orientation`][].
In this example, build a list that displays two columns in
portrait mode and three columns in landscape mode using the
following steps:
1. Build a `GridView` with two columns.
2. Use an `OrientationBuilder` to change the number of columns.
## 1. Build a `GridView` with two columns
First, create a list of items to work with.
Rather than using a normal list,
create a list that displays items in a grid.
For now, create a grid with two columns.
<?code-excerpt "lib/partials.dart (GridViewCount)"?>
```dart
return GridView.count(
// A list with 2 columns
crossAxisCount: 2,
// ...
);
```
To learn more about working with `GridViews`,
see the [Creating a grid list][] recipe.
## 2. Use an `OrientationBuilder` to change the number of columns
To determine the app's current `Orientation`, use the
[`OrientationBuilder`][] widget.
The `OrientationBuilder` calculates the current `Orientation` by
comparing the width and height available to the parent widget,
and rebuilds when the size of the parent changes.
Using the `Orientation`, build a list that displays two columns in portrait
mode, or three columns in landscape mode.
<?code-excerpt "lib/partials.dart (OrientationBuilder)"?>
```dart
body: OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
// Create a grid with 2 columns in portrait mode,
// or 3 columns in landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
);
},
),
```
{{site.alert.note}}
If you're interested in the orientation of the screen,
rather than the amount of space available to the parent,
use `MediaQuery.of(context).orientation` instead of an
`OrientationBuilder` widget.
{{site.alert.end}}
## Interactive example
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-500px:split-60:ga_id-interactive_example
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const appTitle = 'Orientation Demo';
return const MaterialApp(
title: appTitle,
home: OrientationList(
title: appTitle,
),
);
}
}
class OrientationList extends StatelessWidget {
final String title;
const OrientationList({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: OrientationBuilder(
builder: (context, orientation) {
return GridView.count(
// Create a grid with 2 columns in portrait mode, or 3 columns in
// landscape mode.
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
// Generate 100 widgets that display their index in the List.
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.displayLarge,
),
);
}),
);
},
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/orientation.gif" alt="Orientation Demo" class="site-mobile-screenshot" />
</noscript>
## Locking device orientation
In the previous section, you learned
how to adapt the app UI to device orientation changes.
Flutter also allows you to specify the orientations your app supports
using the values of [`DeviceOrientation`]. You can either:
- Lock the app to a single orientation, like only the `portraitUp` position, or...
- Allow multiple orientations, like both `portraitUp` and `portraitDown`, but not landscape.
In the application `main()` method,
call [`SystemChrome.setPreferredOrientations()`]
with the list of preferred orientations that your app supports.
To lock the device to a single orientation,
you can pass a list with a single item.
For a list of all the possible values, check out [`DeviceOrientation`].
<?code-excerpt "lib/orientation.dart (PreferredOrientations)"?>
```dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(const MyApp());
}
```
[Creating a grid list]: /cookbook/lists/grid-lists
[`DeviceOrientation`]: {{site.api}}/flutter/services/DeviceOrientation.html
[`OrientationBuilder`]: {{site.api}}/flutter/widgets/OrientationBuilder-class.html
[`Orientation`]: {{site.api}}/flutter/widgets/Orientation.html
[`SystemChrome.setPreferredOrientations()`]: {{site.api}}/flutter/services/SystemChrome/setPreferredOrientations.html
| website/src/cookbook/design/orientation.md/0 | {
"file_path": "website/src/cookbook/design/orientation.md",
"repo_id": "website",
"token_count": 1782
} | 1,379 |
---
title: Focus and text fields
description: How focus works with text fields.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/forms/focus/"?>
When a text field is selected and accepting input,
it is said to have "focus."
Generally, users shift focus to a text field by tapping,
and developers shift focus to a text field programmatically by
using the tools described in this recipe.
Managing focus is a fundamental tool for creating forms with an intuitive
flow. For example, say you have a search screen with a text field.
When the user navigates to the search screen,
you can set the focus to the text field for the search term.
This allows the user to start typing as soon as the screen
is visible, without needing to manually tap the text field.
In this recipe, learn how to give the focus
to a text field as soon as it's visible,
as well as how to give focus to a text field
when a button is tapped.
## Focus a text field as soon as it's visible
To give focus to a text field as soon as it's visible,
use the `autofocus` property.
```dart
TextField(
autofocus: true,
);
```
For more information on handling input and creating text fields,
see the [Forms][] section of the cookbook.
## Focus a text field when a button is tapped
Rather than immediately shifting focus to a specific text field,
you might need to give focus to a text field at a later point in time.
In the real world, you might also need to give focus to a specific
text field in response to an API call or a validation error.
In this example, give focus to a text field after the user
presses a button using the following steps:
1. Create a `FocusNode`.
2. Pass the `FocusNode` to a `TextField`.
3. Give focus to the `TextField` when a button is tapped.
### 1. Create a `FocusNode`
First, create a [`FocusNode`][].
Use the `FocusNode` to identify a specific `TextField` in Flutter's
"focus tree." This allows you to give focus to the `TextField`
in the next steps.
Since focus nodes are long-lived objects, manage the lifecycle
using a `State` object. Use the following instructions to create
a `FocusNode` instance inside the `initState()` method of a
`State` class, and clean it up in the `dispose()` method:
<?code-excerpt "lib/starter.dart (Starter)" 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> {
// Define the focus node. To manage the lifecycle, create the FocusNode in
// the initState method, and clean it up in the dispose method.
late FocusNode myFocusNode;
@override
void initState() {
super.initState();
myFocusNode = FocusNode();
}
@override
void dispose() {
// Clean up the focus node when the Form is disposed.
myFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Fill this out in the next step.
}
}
```
### 2. Pass the `FocusNode` to a `TextField`
Now that you have a `FocusNode`,
pass it to a specific `TextField` in the `build()` method.
<?code-excerpt "lib/step2.dart (Build)"?>
```dart
@override
Widget build(BuildContext context) {
return TextField(
focusNode: myFocusNode,
);
}
```
### 3. Give focus to the `TextField` when a button is tapped
Finally, focus the text field when the user taps a floating
action button. Use the [`requestFocus()`][] method to perform
this task.
<?code-excerpt "lib/step3.dart (FloatingActionButton)" replace="/^floatingActionButton\: //g"?>
```dart
FloatingActionButton(
// When the button is pressed,
// give focus to the text field using myFocusNode.
onPressed: () => myFocusNode.requestFocus(),
),
```
## 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: 'Text Field Focus',
home: MyCustomForm(),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds data related to the form.
class _MyCustomFormState extends State<MyCustomForm> {
// Define the focus node. To manage the lifecycle, create the FocusNode in
// the initState method, and clean it up in the dispose method.
late FocusNode myFocusNode;
@override
void initState() {
super.initState();
myFocusNode = FocusNode();
}
@override
void dispose() {
// Clean up the focus node when the Form is disposed.
myFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Text Field Focus'),
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
// The first text field is focused on as soon as the app starts.
const TextField(
autofocus: true,
),
// The second text field is focused on when a user taps the
// FloatingActionButton.
TextField(
focusNode: myFocusNode,
),
],
),
),
floatingActionButton: FloatingActionButton(
// When the button is pressed,
// give focus to the text field using myFocusNode.
onPressed: () => myFocusNode.requestFocus(),
tooltip: 'Focus Second Text Field',
child: const Icon(Icons.edit),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/focus.gif" alt="Text Field Focus Demo" class="site-mobile-screenshot" />
</noscript>
[fix has landed]: {{site.repo.flutter}}/pull/50372
[`FocusNode`]: {{site.api}}/flutter/widgets/FocusNode-class.html
[Forms]: /cookbook#forms
[flutter/flutter@bf551a3]: {{site.repo.flutter}}/commit/bf551a31fe7ef45c854a219686b6837400bfd94c
[Issue 52221]: {{site.repo.flutter}}/issues/52221
[`requestFocus()`]: {{site.api}}/flutter/widgets/FocusNode/requestFocus.html
[workaround]: {{site.repo.flutter}}/issues/52221#issuecomment-598244655
| website/src/cookbook/forms/focus.md/0 | {
"file_path": "website/src/cookbook/forms/focus.md",
"repo_id": "website",
"token_count": 2230
} | 1,380 |
These image files are used by the embedded DartPads
in the effects cookbook. DartPad can't extract
images from the _assets/image directory.
| website/src/cookbook/img-files/README/0 | {
"file_path": "website/src/cookbook/img-files/README",
"repo_id": "website",
"token_count": 34
} | 1,381 |
---
title: Pass arguments to a named route
description: How to pass arguments to a named route.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/navigation/navigate_with_arguments"?>
The [`Navigator`][] provides the ability to navigate
to a named route from any part of an app using
a common identifier.
In some cases, you might also need to pass arguments to a
named route. For example, you might wish to navigate to the `/user` route and
pass information about the user to that route.
{{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
You can accomplish this task using the `arguments` parameter of the
[`Navigator.pushNamed()`][] method. Extract the arguments using the
[`ModalRoute.of()`][] method or inside an [`onGenerateRoute()`][]
function provided to the [`MaterialApp`][] or [`CupertinoApp`][]
constructor.
This recipe demonstrates how to pass arguments to a named
route and read the arguments using `ModalRoute.of()`
and `onGenerateRoute()` using the following steps:
1. Define the arguments you need to pass.
2. Create a widget that extracts the arguments.
3. Register the widget in the `routes` table.
4. Navigate to the widget.
## 1. Define the arguments you need to pass
First, define the arguments you need to pass to the new route.
In this example, pass two pieces of data:
The `title` of the screen and a `message`.
To pass both pieces of data, create a class that stores this information.
<?code-excerpt "lib/main.dart (ScreenArguments)"?>
```dart
// You can pass any object to the arguments parameter.
// In this example, create a class that contains both
// a customizable title and message.
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}
```
## 2. Create a widget that extracts the arguments
Next, create a widget that extracts and displays the
`title` and `message` from the `ScreenArguments`.
To access the `ScreenArguments`,
use the [`ModalRoute.of()`][] method.
This method returns the current route with the arguments.
<?code-excerpt "lib/main.dart (ExtractArgumentsScreen)"?>
```dart
// A Widget that extracts the necessary arguments from
// the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
const ExtractArgumentsScreen({super.key});
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
// Extract the arguments from the current ModalRoute
// settings and cast them as ScreenArguments.
final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
```
## 3. Register the widget in the `routes` table
Next, add an entry to the `routes` provided to the `MaterialApp` widget. The
`routes` define which widget should be created based on the name of the route.
{% comment %}
RegEx removes the return statement and adds the closing parenthesis at the end
{% endcomment %}
<?code-excerpt "lib/main.dart (Routes)" replace="/return //g;/$/\n)/g"?>
```dart
MaterialApp(
routes: {
ExtractArgumentsScreen.routeName: (context) =>
const ExtractArgumentsScreen(),
},
)
```
## 4. Navigate to the widget
Finally, navigate to the `ExtractArgumentsScreen`
when a user taps a button using [`Navigator.pushNamed()`][].
Provide the arguments to the route via the `arguments` property. The
`ExtractArgumentsScreen` extracts the `title` and `message` from these
arguments.
<?code-excerpt "lib/main.dart (PushNamed)"?>
```dart
// A button that navigates to a named route.
// The named route extracts the arguments
// by itself.
ElevatedButton(
onPressed: () {
// When the user taps the button,
// navigate to a named route and
// provide the arguments as an optional
// parameter.
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
},
child: const Text('Navigate to screen that extracts arguments'),
),
```
## Alternatively, extract the arguments using `onGenerateRoute`
Instead of extracting the arguments directly inside the widget, you can also
extract the arguments inside an [`onGenerateRoute()`][]
function and pass them to a widget.
The `onGenerateRoute()` function creates the correct route based on the given
[`RouteSettings`][].
{% comment %}
RegEx removes the return statement, removed "routes" property and adds the closing parenthesis at the end
{% endcomment %}
<?code-excerpt "lib/main.dart (OnGenerateRoute)" replace="/^return //g;/ routes:((.)*\n){4}//g;/$/\n)/g"?>
```dart
MaterialApp(
// Provide a function to handle named routes.
// Use this function to identify the named
// route being pushed, and create the correct
// Screen.
onGenerateRoute: (settings) {
// If you push the PassArguments route
if (settings.name == PassArgumentsScreen.routeName) {
// Cast the arguments to the correct
// type: ScreenArguments.
final args = settings.arguments as ScreenArguments;
// Then, extract the required data from
// the arguments and pass the data to the
// correct screen.
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
// The code only supports
// PassArgumentsScreen.routeName right now.
// Other values need to be implemented if we
// add them. The assertion here will help remind
// us of that higher up in the call stack, since
// this assertion would otherwise fire somewhere
// in the framework.
assert(false, 'Need to implement ${settings.name}');
return null;
},
)
```
## 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 MaterialApp(
routes: {
ExtractArgumentsScreen.routeName: (context) =>
const ExtractArgumentsScreen(),
},
// Provide a function to handle named routes.
// Use this function to identify the named
// route being pushed, and create the correct
// Screen.
onGenerateRoute: (settings) {
// If you push the PassArguments route
if (settings.name == PassArgumentsScreen.routeName) {
// Cast the arguments to the correct
// type: ScreenArguments.
final args = settings.arguments as ScreenArguments;
// Then, extract the required data from
// the arguments and pass the data to the
// correct screen.
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
message: args.message,
);
},
);
}
// The code only supports
// PassArgumentsScreen.routeName right now.
// Other values need to be implemented if we
// add them. The assertion here will help remind
// us of that higher up in the call stack, since
// this assertion would otherwise fire somewhere
// in the framework.
assert(false, 'Need to implement ${settings.name}');
return null;
},
title: 'Navigation with Arguments',
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// A button that navigates to a named route.
// The named route extracts the arguments
// by itself.
ElevatedButton(
onPressed: () {
// When the user taps the button,
// navigate to a named route and
// provide the arguments as an optional
// parameter.
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
},
child: const Text('Navigate to screen that extracts arguments'),
),
// A button that navigates to a named route.
// For this route, extract the arguments in
// the onGenerateRoute function and pass them
// to the screen.
ElevatedButton(
onPressed: () {
// When the user taps the button, navigate
// to a named route and provide the arguments
// as an optional parameter.
Navigator.pushNamed(
context,
PassArgumentsScreen.routeName,
arguments: ScreenArguments(
'Accept Arguments Screen',
'This message is extracted in the onGenerateRoute '
'function.',
),
);
},
child: const Text('Navigate to a named that accepts arguments'),
),
],
),
),
);
}
}
// A Widget that extracts the necessary arguments from
// the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
const ExtractArgumentsScreen({super.key});
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
// Extract the arguments from the current ModalRoute
// settings and cast them as ScreenArguments.
final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
// A Widget that accepts the necessary arguments via the
// constructor.
class PassArgumentsScreen extends StatelessWidget {
static const routeName = '/passArguments';
final String title;
final String message;
// This Widget accepts the arguments as constructor
// parameters. It does not extract the arguments from
// the ModalRoute.
//
// The arguments are extracted by the onGenerateRoute
// function provided to the MaterialApp widget.
const PassArgumentsScreen({
super.key,
required this.title,
required this.message,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(message),
),
);
}
}
// You can pass any object to the arguments parameter.
// In this example, create a class that contains both
// a customizable title and message.
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}
```
<noscript>
<img src="/assets/images/docs/cookbook/navigate-with-arguments.gif" alt="Demonstrates navigating to different routes with arguments" class="site-mobile-screenshot" />
</noscript>
[`CupertinoApp`]: {{site.api}}/flutter/cupertino/CupertinoApp-class.html
[`MaterialApp`]: {{site.api}}/flutter/material/MaterialApp-class.html
[`ModalRoute.of()`]: {{site.api}}/flutter/widgets/ModalRoute/of.html
[`Navigator`]: {{site.api}}/flutter/widgets/Navigator-class.html
[`Navigator.pushNamed()`]: {{site.api}}/flutter/widgets/Navigator/pushNamed.html
[`onGenerateRoute()`]: {{site.api}}/flutter/widgets/WidgetsApp/onGenerateRoute.html
[`RouteSettings`]: {{site.api}}/flutter/widgets/RouteSettings-class.html
| website/src/cookbook/navigation/navigate-with-arguments.md/0 | {
"file_path": "website/src/cookbook/navigation/navigate-with-arguments.md",
"repo_id": "website",
"token_count": 4544
} | 1,382 |
---
title: Read and write files
description: How to read from and write to files on disk.
---
<?code-excerpt path-base="cookbook/persistence/reading_writing_files/"?>
In some cases, you need to read and write files to disk.
For example, you might need to persist data across app launches,
or download data from the internet and save it for later offline use.
To save files to disk on mobile or desktop apps,
combine the [`path_provider`][] plugin with the [`dart:io`][] library.
This recipe uses the following steps:
1. Find the correct local path.
2. Create a reference to the file location.
3. Write data to the file.
4. Read data from the file.
To learn more, watch this Package of the Week video
on the `path_provider` package:
<iframe class="full-width" src="{{site.yt.embed}}/Ci4t-NkOY3I" title="Learn about the path_provider Flutter Package" {{site.yt.set}}></iframe>
{{site.alert.note}}
This recipe doesn't work with web apps at this time.
To follow the discussion on this issue,
check out `flutter/flutter` [issue #45296]({{site.repo.flutter}}/issues/45296).
{{site.alert.end}}
## 1. Find the correct local path
This example displays a counter. When the counter changes,
write data on disk so you can read it again when the app loads.
Where should you store this data?
The [`path_provider`][] package
provides a platform-agnostic way to access commonly used locations on the
device's file system. The plugin currently supports access to
two file system locations:
*Temporary directory*
: A temporary directory (cache) that the system can
clear at any time. On iOS, this corresponds to the
[`NSCachesDirectory`][]. On Android, this is the value that
[`getCacheDir()`][] returns.
*Documents directory*
: A directory for the app to store files that only
it can access. The system clears the directory only when the app
is deleted.
On iOS, this corresponds to the `NSDocumentDirectory`.
On Android, this is the `AppData` directory.
This example stores information in the documents directory.
You can find the path to the documents directory as follows:
<?code-excerpt "lib/main.dart (localPath)"?>
```dart
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
```
## 2. Create a reference to the file location
Once you know where to store the file, create a reference to the
file's full location. You can use the [`File`][]
class from the [`dart:io`][] library to achieve this.
<?code-excerpt "lib/main.dart (localFile)"?>
```dart
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
```
## 3. Write data to the file
Now that you have a `File` to work with,
use it to read and write data.
First, write some data to the file.
The counter is an integer, but is written to the
file as a string using the `'$counter'` syntax.
<?code-excerpt "lib/main.dart (writeCounter)"?>
```dart
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
```
## 4. Read data from the file
Now that you have some data on disk, you can read it.
Once again, use the `File` class.
<?code-excerpt "lib/main.dart (readCounter)"?>
```dart
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
```
## Complete example
<?code-excerpt "lib/main.dart"?>
```dart
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
MaterialApp(
title: 'Reading and Writing Files',
home: FlutterDemo(storage: CounterStorage()),
),
);
}
class CounterStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}
class FlutterDemo extends StatefulWidget {
const FlutterDemo({super.key, required this.storage});
final CounterStorage storage;
@override
State<FlutterDemo> createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
int _counter = 0;
@override
void initState() {
super.initState();
widget.storage.readCounter().then((value) {
setState(() {
_counter = value;
});
});
}
Future<File> _incrementCounter() {
setState(() {
_counter++;
});
// Write the variable as a string to the file.
return widget.storage.writeCounter(_counter);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Reading and Writing Files'),
),
body: Center(
child: Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
```
[`dart:io`]: {{site.api}}/flutter/dart-io/dart-io-library.html
[`File`]: {{site.api}}/flutter/dart-io/File-class.html
[`getCacheDir()`]: {{site.android-dev}}/reference/android/content/Context#getCacheDir()
[`NSCachesDirectory`]: {{site.apple-dev}}/documentation/foundation/nssearchpathdirectory/nscachesdirectory
[`path_provider`]: {{site.pub-pkg}}/path_provider
| website/src/cookbook/persistence/reading-writing-files.md/0 | {
"file_path": "website/src/cookbook/persistence/reading-writing-files.md",
"repo_id": "website",
"token_count": 2036
} | 1,383 |
---
title: Handle scrolling
description: How to handle scrolling in a widget test.
---
<?code-excerpt path-base="cookbook/testing/widget/scrolling/"?>
Many apps feature lists of content,
from email clients to music apps and beyond.
To verify that lists contain the expected content
using widget tests,
you need a way to scroll through lists to search for particular items.
To scroll through lists via integration tests,
use the methods provided by the [`WidgetTester`][] class,
which is included in the [`flutter_test`][] package:
In this recipe, learn how to scroll through a list of items to
verify a specific widget is being displayed,
and the pros and cons of different approaches.
This recipe uses the following steps:
1. Create an app with a list of items.
2. Write a test that scrolls through the list.
3. Run the test.
### 1. Create an app with a list of items
This recipe builds an app that shows a long list of items.
To keep this recipe focused on testing, use the app created in the
[Work with long lists][] recipe.
If you're unsure of how to work with long lists,
see that recipe for an introduction.
Add keys to the widgets you want to interact with
inside the integration tests.
<?code-excerpt "lib/main.dart"?>
```dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
));
}
class MyApp extends StatelessWidget {
final List<String> items;
const MyApp({super.key, required this.items});
@override
Widget build(BuildContext context) {
const title = 'Long List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: ListView.builder(
// Add a key to the ListView. This makes it possible to
// find the list and scroll through it in the tests.
key: const Key('long_list'),
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
items[index],
// Add a key to the Text widget for each item. This makes
// it possible to look for a particular item in the list
// and verify that the text is correct
key: Key('item_${index}_text'),
),
);
},
),
),
);
}
}
```
### 2. Write a test that scrolls through the list
Now, you can write a test. In this example, scroll through the list of items and
verify that a particular item exists in the list. The [`WidgetTester`][] class
provides the [`scrollUntilVisible()`][] method, which scrolls through a list
until a specific widget is visible. This is useful because the height of the
items in the list can change depending on the device.
Rather than assuming that you know the height of all the items
in a list, or that a particular widget is rendered on all devices,
the `scrollUntilVisible()` method repeatedly scrolls through
a list of items until it finds what it's looking for.
The following code shows how to use the `scrollUntilVisible()` method
to look through the list for a particular item. This code lives in a
file called `test/widget_test.dart`.
<?code-excerpt "test/widget_test.dart (ScrollWidgetTest)"?>
```dart
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:scrolling/main.dart';
void main() {
testWidgets('finds a deep item in a long list', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
));
final listFinder = find.byType(Scrollable);
final itemFinder = find.byKey(const ValueKey('item_50_text'));
// Scroll until the item to be found appears.
await tester.scrollUntilVisible(
itemFinder,
500.0,
scrollable: listFinder,
);
// Verify that the item contains the correct text.
expect(itemFinder, findsOneWidget);
});
}
```
### 3. Run the test
Run the test using the following command from the root of the project:
```
flutter test test/widget_test.dart
```
[`flutter_test`]: {{site.api}}/flutter/flutter_test/flutter_test-library.html
[`WidgetTester`]: {{site.api}}/flutter/flutter_test/WidgetTester-class.html
[`ListView.builder`]: {{site.api}}/flutter/widgets/ListView/ListView.builder.html
[`scrollUntilVisible()`]: {{site.api}}/flutter/flutter_test/WidgetController/scrollUntilVisible.html
[Work with long lists]: /cookbook/lists/long-lists
| website/src/cookbook/testing/widget/scrolling.md/0 | {
"file_path": "website/src/cookbook/testing/widget/scrolling.md",
"repo_id": "website",
"token_count": 1646
} | 1,384 |
---
title: Build and release an Android app
description: How to prepare for and release an Android app to the Play store.
short-title: Android
---
During a typical development cycle,
you test an app using `flutter run` at the command line,
or by using the **Run** and **Debug**
options in your IDE. By default,
Flutter builds a _debug_ version of your app.
When you're ready to prepare a _release_ version of your app,
for example to [publish to the Google Play Store][play],
this page can help. Before publishing,
you might want to put some finishing touches on your app.
This page covers the following topics:
* [Adding a launcher icon](#adding-a-launcher-icon)
* [Enabling Material Components](#enabling-material-components)
* [Signing the app](#signing-the-app)
* [Shrinking your code with R8](#shrinking-your-code-with-r8)
* [Enabling multidex support](#enabling-multidex-support)
* [Reviewing the app manifest](#reviewing-the-app-manifest)
* [Reviewing the build configuration](#reviewing-the-gradle-build-configuration)
* [Building the app for release](#building-the-app-for-release)
* [Publishing to the Google Play Store](#publishing-to-the-google-play-store)
* [Updating the app's version number](#updating-the-apps-version-number)
* [Android release FAQ](#android-release-faq)
{{site.alert.note}}
Throughout this page, `[project]` refers to
the directory that your application is in. While following
these instructions, substitute `[project]` with
your app's directory.
{{site.alert.end}}
## Adding a launcher icon
When a new Flutter app is created, it has a default launcher icon.
To customize this icon, you might want to check out the
[flutter_launcher_icons][] package.
Alternatively, you can do it manually using the following steps:
1. Review the [Material Design product
icons][launchericons] guidelines for icon design.
1. In the `[project]/android/app/src/main/res/` directory,
place your icon files in folders named using
[configuration qualifiers][].
The default `mipmap-` folders demonstrate the correct
naming convention.
1. In `AndroidManifest.xml`, update the
[`application`][applicationtag] tag's `android:icon`
attribute to reference icons from the previous
step (for example,
`<application android:icon="@mipmap/ic_launcher" ...`).
1. To verify that the icon has been replaced,
run your app and inspect the app icon in the Launcher.
## Enabling Material Components
If your app uses [Platform Views][], you might want to enable
Material Components by following the steps described in the
[Getting Started guide for Android][].
For example:
1. Add the dependency on Android's Material in `<my-app>/android/app/build.gradle`:
```groovy
dependencies {
// ...
implementation 'com.google.android.material:material:<version>'
// ...
}
```
To find out the latest version, visit [Google Maven][].
2. Set the light theme in `<my-app>/android/app/src/main/res/values/styles.xml`:
```diff
-<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
+<style name="NormalTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
```
3. Set the dark theme in `<my-app>/android/app/src/main/res/values-night/styles.xml`
```diff
-<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
+<style name="NormalTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
```
<a id="signing-the-app"></a>
## Sign the app
To publish on the Play Store, you need to
sign your app with a digital certificate.
Android uses two signing keys: _upload_ and _app signing_.
* Developers upload an `.aab` or `.apk` file signed with
an _upload key_ to the Play Store.
* The end-users download the `.apk` file signed with an _app signing key_.
To create your app signing key, use Play App Signing
as described in the [official Play Store documentation][].
To sign your app, use the following instructions.
### Create an upload keystore
If you have an existing keystore, skip to the next step.
If not, create one using one of the following methods:
1. Follow the [Android Studio key generation steps]({{site.android-dev}}/studio/publish/app-signing#generate-key)
1. Run the following command at the command line:
On macOS or Linux, use the following command:
```terminal
keytool -genkey -v -keystore ~/upload-keystore.jks -keyalg RSA \
-keysize 2048 -validity 10000 -alias upload
```
On Windows, use the following command in PowerShell:
```powershell
keytool -genkey -v -keystore %userprofile%\upload-keystore.jks ^
-storetype JKS -keyalg RSA -keysize 2048 -validity 10000 ^
-alias upload
```
This command stores the `upload-keystore.jks` file in your home
directory. If you want to store it elsewhere, change
the argument you pass to the `-keystore` parameter.
**However, keep the `keystore` file private;
don't check it into public source control!**
{{site.alert.note}}
* The `keytool` command might not be in your path—it's
part of Java, which is installed as part of
Android Studio. For the concrete path,
run `flutter doctor -v` and locate the path printed after
'Java binary at:'. Then use that fully qualified path
replacing `java` (at the end) with `keytool`.
If your path includes space-separated names,
such as `Program Files`, use platform-appropriate
notation for the names. For example, on Mac/Linux
use `Program\ Files`, and on Windows use
`"Program Files"`.
* The `-storetype JKS` tag is only required for Java 9
or newer. As of the Java 9 release,
the keystore type defaults to PKS12.
{{site.alert.end}}
### Reference the keystore from the app
Create a file named `[project]/android/key.properties`
that contains a reference to your keystore.
Don't include the angle brackets (`< >`).
They indicate that the text serves as a placeholder for your values.
```properties
storePassword=<password-from-previous-step>
keyPassword=<password-from-previous-step>
keyAlias=upload
storeFile=<keystore-file-location>
```
The `storeFile` might be located at
`/Users/<user name>/upload-keystore.jks` on macOS
or `C:\\Users\\<user name>\\upload-keystore.jks` on Windows.
{{site.alert.warning}}
Keep the `key.properties` file private;
don't check it into public source control.
{{site.alert.end}}
### Configure signing in gradle
Configure gradle to use your upload key when building your app in release mode
by editing the `[project]/android/app/build.gradle` file.
<ol markdown="1">
<li markdown="1"> Add the keystore information from your properties file before the `android` block:
```
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
...
}
```
Load the `key.properties` file into the `keystoreProperties` object.
</li>
<li markdown="1"> Find the `buildTypes` block:
```
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now,
// so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
```
And replace it with the following signing configuration info:
```
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
```
</li>
</ol>
Release builds of your app will now be signed automatically.
{{site.alert.note}}
You might need to run `flutter clean` after changing the gradle file.
This prevents cached builds from affecting the signing process.
{{site.alert.end}}
For more information on signing your app, check out
[Sign your app][] on developer.android.com.
## Shrinking your code with R8
[R8][] is the new code shrinker from Google, and it's enabled by default
when you build a release APK or AAB. To disable R8, pass the `--no-shrink`
flag to `flutter build apk` or `flutter build appbundle`.
{{site.alert.note}}
Obfuscation and minification can considerably extend compile time
of the Android application.
{{site.alert.end}}
## Enabling multidex support
When writing large apps or making use of large plugins,
you might encounter Android's dex limit of 64k methods
when targeting a minimum API of 20 or below.
This might also be encountered when running debug versions of your app
using `flutter run` that does not have shrinking enabled.
Flutter tool supports easily enabling multidex. The simplest way is to
opt into multidex support when prompted. The tool detects multidex build errors
and asks before making changes to your Android project.
Opting in allows Flutter to automatically depend on
`androidx.multidex:multidex` and use a generated
`FlutterMultiDexApplication` as the project's application.
When you try to build and run your app with the **Run** and **Debug**
options in your IDE, your build might fail with the following message:
<img src='/assets/images/docs/deployment/android/ide-build-failure-multidex.png' width="100%" alt='screenshot of build failure because Multidex support is required'>
To enable multidex from the command line,
run `flutter run --debug` and select an Android device:
<img src='/assets/images/docs/deployment/android/cli-select-device.png' width="100%" alt='screenshot of selecting an Android device'>
When prompted, enter `y`.
The Flutter tool enables multidex support and retries the build:
<img src='/assets/images/docs/deployment/android/cli-multidex-added-build.png' width="100%" alt='screenshot of a successful build after adding multidex'>
{{site.alert.note}}
Multidex support is natively included when targeting
Android SDK 21 or later. However, we don't recommend
targeting API 21+ purely to resolve the multidex issue
as this might inadvertently exclude users running older devices.
{{site.alert.end}}
You might also choose to manually support multidex by following Android's guides
and modifying your project's Android directory configuration.
A [multidex keep file][multidex-keep] must be specified to include:
```
io/flutter/embedding/engine/loader/FlutterLoader.class
io/flutter/util/PathUtils.class
```
Also, include any other classes used in app startup.
For more detailed guidance on adding multidex support manually,
check out the official [Android documentation][multidex-docs].
## Reviewing the app manifest
Review the default [App Manifest][manifest] file, `AndroidManifest.xml`.
This file is located in `[project]/android/app/src/main`.
Verify the following values:
`application`
: Edit the `android:label` in the
[`application`][applicationtag] tag to reflect
the final name of the app.
`uses-permission`
: Add the `android.permission.INTERNET`
[permission][permissiontag] if your application code needs Internet
access. The standard template doesn't include this tag but allows
Internet access during development to enable communication between
Flutter tools and a running app.
## Reviewing the Gradle build configuration
Review the default [Gradle build file][gradlebuild]
(`build.gradle`, located in `[project]/android/app`),
to verify that the values are correct.
#### Under the `defaultConfig` block
`applicationId`
: Specify the final, unique [application ID][].
`minSdkVersion`
: Specify the [minimum API level][] on which you designed the app to run.
Defaults to `flutter.minSdkVersion`.
`targetSdkVersion`
: Specify the target API level on which you designed the app to run.
Defaults to `flutter.targetSdkVersion`.
`versionCode`
: A positive integer used as an [internal version number][].
This number is used only to determine whether one version is more recent
than another, with higher numbers indicating more recent versions.
This version isn't shown to users.
`versionName`
: A string used as the version number shown to users.
This setting can be specified as a raw string or as
a reference to a string resource.
`buildToolsVersion`
: The Gradle plugin specifies the default version of the
build tools that your project uses.
You can use this option to specify a different version of the build tools.
#### Under the `android` block
`compileSdkVersion`
: Specify the API level Gradle should use to compile your app.
Defaults to `flutter.compileSdkVersion`.
For more information, check out the module-level build
section in the [Gradle build file][gradlebuild].
## Building the app for release
You have two possible release formats when publishing to
the Play Store.
* App bundle (preferred)
* APK
{{site.alert.note}}
The Google Play Store prefers the app bundle format.
For more information, check out
[About Android App Bundles][bundle].
{{site.alert.end}}
### Build an app bundle
This section describes how to build a release app bundle.
If you completed the signing steps,
the app bundle will be signed.
At this point, you might consider [obfuscating your Dart code][]
to make it more difficult to reverse engineer. Obfuscating
your code involves adding a couple flags to your build command,
and maintaining additional files to de-obfuscate stack traces.
From the command line:
1. Enter `cd [project]`<br>
1. Run `flutter build appbundle`<br>
(Running `flutter build` defaults to a release build.)
The release bundle for your app is created at
`[project]/build/app/outputs/bundle/release/app.aab`.
By default, the app bundle contains your Dart code and the Flutter
runtime compiled for [armeabi-v7a][] (ARM 32-bit), [arm64-v8a][]
(ARM 64-bit), and [x86-64][] (x86 64-bit).
### Test the app bundle
An app bundle can be tested in multiple ways.
This section describes two.
#### Offline using the bundle tool
1. If you haven't done so already, download `bundletool` from the
[GitHub repository][].
1. [Generate a set of APKs][apk-set] from your app bundle.
1. [Deploy the APKs][apk-deploy] to connected devices.
#### Online using Google Play
1. Upload your bundle to Google Play to test it.
You can use the internal test track,
or the alpha or beta channels to test the bundle before
releasing it in production.
2. Follow [these steps to upload your bundle][upload-bundle]
to the Play Store.
### Build an APK
Although app bundles are preferred over APKs, there are stores
that don't yet support app bundles. In this case, build a release
APK for each target ABI (Application Binary Interface).
If you completed the signing steps, the APK will be signed.
At this point, you might consider [obfuscating your Dart code][]
to make it more difficult to reverse engineer. Obfuscating
your code involves adding a couple flags to your build command.
From the command line:
1. Enter `cd [project]`.
1. Run `flutter build apk --split-per-abi`.
(The `flutter build` command defaults to `--release`.)
This command results in three APK files:
* `[project]/build/app/outputs/apk/release/app-armeabi-v7a-release.apk`
* `[project]/build/app/outputs/apk/release/app-arm64-v8a-release.apk`
* `[project]/build/app/outputs/apk/release/app-x86_64-release.apk`
Removing the `--split-per-abi` flag results in a fat APK that contains
your code compiled for _all_ the target ABIs. Such APKs are larger in
size than their split counterparts, causing the user to download
native binaries that are not applicable to their device's architecture.
### Install an APK on a device
Follow these steps to install the APK on a connected Android device.
From the command line:
1. Connect your Android device to your computer with a USB cable.
1. Enter `cd [project]`.
1. Run `flutter install`.
## Publishing to the Google Play Store
For detailed instructions on publishing your app to the Google Play Store,
check out the [Google Play launch][play] documentation.
## Updating the app's version number
The default version number of the app is `1.0.0`.
To update it, navigate to the `pubspec.yaml` file
and update the following line:
`version: 1.0.0+1`
The version number is three numbers separated by dots,
such as `1.0.0` in the example above, followed by an optional
build number such as `1` in the example above, separated by a `+`.
Both the version and the build number can be overridden in Flutter's
build by specifying `--build-name` and `--build-number`, respectively.
In Android, `build-name` is used as `versionName` while
`build-number` used as `versionCode`. For more information,
check out [Version your app][] in the Android documentation.
When you rebuild the app for Android, any updates in the version number
from the pubspec file will update the `versionName` and `versionCode`
in the `local.properties` file.
## Android release FAQ
Here are some commonly asked questions about deployment for
Android apps.
### When should I build app bundles versus APKs?
The Google Play Store recommends that you deploy app bundles
over APKs because they allow a more efficient delivery of the
application to your users. However, if you're distributing
your application by means other than the Play Store,
an APK might be your only option.
### What is a fat APK?
A [fat APK][] is a single APK that contains binaries for multiple
ABIs embedded within it. This has the benefit that the single APK
runs on multiple architectures and thus has wider compatibility,
but it has the drawback that its file size is much larger,
causing users to download and store more bytes when installing
your application. When building APKs instead of app bundles,
it is strongly recommended to build split APKs,
as described in [build an APK](#build-an-apk) using the
`--split-per-abi` flag.
### What are the supported target architectures?
When building your application in release mode,
Flutter apps can be compiled for [armeabi-v7a][] (ARM 32-bit),
[arm64-v8a][] (ARM 64-bit), and [x86-64][] (x86 64-bit).
Flutter supports building for x86 Android through ARM emulation.
### How do I sign the app bundle created by `flutter build appbundle`?
See [Signing the app](#signing-the-app).
### How do I build a release from within Android Studio?
In Android Studio, open the existing `android/`
folder under your app's folder. Then,
select **build.gradle (Module: app)** in the project panel:
<img src='/assets/images/docs/deployment/android/gradle-script-menu.png' width="100%" alt='screenshot of gradle build script menu'>
Next, select the build variant. Click **Build > Select Build Variant**
in the main menu. Select any of the variants in the **Build Variants**
panel (debug is the default):
<img src='/assets/images/docs/deployment/android/build-variant-menu.png' width="100%" alt='screenshot of build variant menu'>
The resulting app bundle or APK files are located in
`build/app/outputs` within your app's folder.
{% comment %}
### Are there any special considerations with add-to-app?
{% endcomment %}
[apk-deploy]: {{site.android-dev}}/studio/command-line/bundletool#deploy_with_bundletool
[apk-set]: {{site.android-dev}}/studio/command-line/bundletool#generate_apks
[application ID]: {{site.android-dev}}/studio/build/application-id
[applicationtag]: {{site.android-dev}}/guide/topics/manifest/application-element
[arm64-v8a]: {{site.android-dev}}/ndk/guides/abis#arm64-v8a
[armeabi-v7a]: {{site.android-dev}}/ndk/guides/abis#v7a
[bundle]: {{site.android-dev}}/guide/app-bundle
[configuration qualifiers]: {{site.android-dev}}/guide/topics/resources/providing-resources#AlternativeResources
[fat APK]: https://en.wikipedia.org/wiki/Fat_binary
[flutter_launcher_icons]: {{site.pub}}/packages/flutter_launcher_icons
[Getting Started guide for Android]: {{site.material}}/develop/android/mdc-android
[GitHub repository]: {{site.github}}/google/bundletool/releases/latest
[Google Maven]: https://maven.google.com/web/index.html#com.google.android.material:material
[gradlebuild]: {{site.android-dev}}/studio/build/#module-level
[internal version number]: {{site.android-dev}}/studio/publish/versioning
[launchericons]: {{site.material}}/styles/icons
[manifest]: {{site.android-dev}}/guide/topics/manifest/manifest-intro
[minimum API level]: {{site.android-dev}}/studio/publish/versioning#minsdk
[multidex-docs]: {{site.android-dev}}/studio/build/multidex
[multidex-keep]: {{site.android-dev}}/studio/build/multidex#keep
[obfuscating your Dart code]: /deployment/obfuscate
[official Play Store documentation]: https://support.google.com/googleplay/android-developer/answer/7384423?hl=en
[permissiontag]: {{site.android-dev}}/guide/topics/manifest/uses-permission-element
[Platform Views]: /platform-integration/android/platform-views
[play]: {{site.android-dev}}/distribute
[R8]: {{site.android-dev}}/studio/build/shrink-code
[Sign your app]: {{site.android-dev}}/studio/publish/app-signing.html#generate-key
[upload-bundle]: {{site.android-dev}}/studio/publish/upload-bundle
[Version your app]: {{site.android-dev}}/studio/publish/versioning
[x86-64]: {{site.android-dev}}/ndk/guides/abis#86-64
| website/src/deployment/android.md/0 | {
"file_path": "website/src/deployment/android.md",
"repo_id": "website",
"token_count": 6429
} | 1,385 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.