text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
# linting_tool
A desktop tool that helps you manage [linter rules](https://dart.dev/guides/language/analysis-options#enabling-linter-rules)
for your Flutter project.
## Goals for this sample
* Show how to read and write files on Desktop
* Show how to create, parse and use yaml files
* Show how to implement basic navigation in Desktop apps
* Show how to implement right-click popup menus
## Questions/issues
If you have a general question about Flutter, the best places to go are:
* [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev)
* [The Flutter Gitter channel](https://gitter.im/flutter/flutter)
* [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
If you run into an issue with the sample itself, please [file an issue](https://github.com/flutter/samples/issues).
| samples/experimental/linting_tool/README.md/0 | {
"file_path": "samples/experimental/linting_tool/README.md",
"repo_id": "samples",
"token_count": 240
} | 1,320 |
// 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';
import 'package:linting_tool/layout/adaptive.dart';
import 'package:linting_tool/model/editing_controller.dart';
import 'package:linting_tool/model/profiles_store.dart';
import 'package:linting_tool/pages/rules_page.dart';
import 'package:linting_tool/theme/colors.dart';
import 'package:provider/provider.dart';
class SavedLintsPage extends StatefulWidget {
const SavedLintsPage({super.key});
@override
State<SavedLintsPage> createState() => _SavedLintsPageState();
}
class _SavedLintsPageState extends State<SavedLintsPage> {
@override
Widget build(BuildContext context) {
return Consumer<ProfilesStore>(
builder: (context, profilesStore, child) {
if (profilesStore.isLoading) {
return const CircularProgressIndicator.adaptive();
}
if (!profilesStore.isLoading) {
if (profilesStore.savedProfiles.isNotEmpty) {
final isDesktop = isDisplayLarge(context);
final isTablet = isDisplayMedium(context);
final startPadding = isTablet
? 60.0
: isDesktop
? 120.0
: 16.0;
final endPadding = isTablet
? 60.0
: isDesktop
? 120.0
: 16.0;
return ListView.separated(
padding: EdgeInsetsDirectional.only(
start: startPadding,
end: endPadding,
top: isDesktop ? 28 : 16,
bottom: isDesktop ? kToolbarHeight : 16,
),
itemCount: profilesStore.savedProfiles.length,
cacheExtent: 5,
itemBuilder: (itemBuilderContext, index) {
var profile = profilesStore.savedProfiles[index];
return ListTile(
title: Text(
profile.name,
),
tileColor: AppColors.white50,
onTap: () {
Navigator.push<void>(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => EditingController(),
child: RulesPage(selectedProfileIndex: index),
),
),
);
},
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: () {
Navigator.push<void>(
context,
MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => EditingController(
isEditing: true,
),
child: RulesPage(selectedProfileIndex: index),
),
),
);
},
),
const SizedBox(
width: 8.0,
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
onSelected: (value) async {
switch (value) {
case 'Export file':
// ignore: todo
// TODO(abd99): Add option to select formatting style.
var saved = await profilesStore
.exportProfileFile(profile);
if (!context.mounted) return;
if (!saved) {
_showSnackBar(
context,
profilesStore.error ?? 'Failed to save file.',
);
}
case 'Delete':
await profilesStore.deleteProfile(profile);
default:
}
},
itemBuilder: (context) {
return [
const PopupMenuItem(
value: 'Export file',
child: Text('Export file'),
),
const PopupMenuItem(
value: 'Delete',
child: Text('Delete'),
),
];
},
),
],
),
);
},
separatorBuilder: (context, index) => const SizedBox(height: 4),
);
}
}
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(profilesStore.error ?? 'No saved profiles found.'),
const SizedBox(
height: 16.0,
),
IconButton(
onPressed: () => profilesStore.fetchSavedProfiles(),
icon: const Icon(Icons.refresh),
),
],
);
},
);
}
void _showSnackBar(BuildContext context, String data) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(data),
),
);
}
}
| samples/experimental/linting_tool/lib/pages/saved_lints_page.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/pages/saved_lints_page.dart",
"repo_id": "samples",
"token_count": 3573
} | 1,321 |
// 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 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:http/http.dart' as http;
import 'package:linting_tool/app.dart';
import 'package:linting_tool/model/profile.dart';
import 'package:linting_tool/model/profiles_store.dart';
import 'package:linting_tool/model/rule.dart';
import 'package:linting_tool/model/rules_store.dart';
import 'package:linting_tool/pages/default_lints_page.dart';
import 'package:linting_tool/pages/home_page.dart';
import 'package:linting_tool/pages/saved_lints_page.dart';
import 'package:linting_tool/theme/app_theme.dart';
import 'package:linting_tool/widgets/adaptive_nav.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:provider/provider.dart';
import 'widget_test.mocks.dart';
late MockClient _mockClient;
class _TestApp extends StatelessWidget {
const _TestApp();
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<RuleStore>(
create: (context) => RuleStore(_mockClient),
),
ChangeNotifierProvider<ProfilesStore>(
create: (context) => ProfilesStore(_mockClient),
),
],
child: MaterialApp(
title: 'Flutter Linting Tool',
initialRoute: LintingTool.homeRoute,
theme: AppTheme.buildReplyLightTheme(context),
onGenerateRoute: (settings) {
switch (settings.name) {
case LintingTool.homeRoute:
return MaterialPageRoute<void>(
builder: (context) => const AdaptiveNav(),
settings: settings,
);
}
return null;
},
),
);
}
}
@GenerateMocks([http.Client])
void main() {
setUp(() async {
final tempDir = await Directory.systemTemp.createTemp();
Hive.init(tempDir.path);
Hive.registerAdapter(RuleAdapter());
Hive.registerAdapter(RulesProfileAdapter());
await Hive.openLazyBox<RulesProfile>('rules_profile');
_mockClient = MockClient();
});
testWidgets('NavigationRail smoke test', (tester) async {
var responseBody =
'''[{"name": "always_use_package_imports","description": "Avoid relative imports for files in `lib/`.","group": "errors","state": "stable","incompatible": [],"sets": [],"details": "*DO* avoid relative imports for files in `lib/`.\n\nWhen mixing relative and absolute imports it's possible to create confusion\nwhere the same member gets imported in two different ways. One way to avoid\nthat is to ensure you consistently use absolute imports for files withing the\n`lib/` directory.\n\nThis is the opposite of 'prefer_relative_imports'.\nMight be used with 'avoid_relative_lib_imports' to avoid relative imports of\nfiles within `lib/` directory outside of it. (for example `test/`)\n\n**GOOD:**\n\n```dart\nimport 'package:foo/bar.dart';\n\nimport 'package:foo/baz.dart';\n\nimport 'package:foo/src/baz.dart';\n...\n```\n\n**BAD:**\n\n```dart\nimport 'baz.dart';\n\nimport 'src/bag.dart'\n\nimport '../lib/baz.dart';\n\n...\n```\n\n"}]''';
when(_mockClient.get(Uri.parse(
'https://raw.githubusercontent.com/dart-lang/site-www/main/src/_data/linter_rules.json',
))).thenAnswer(
(_) async => http.Response(responseBody, 400),
);
await tester.pumpWidget(const _TestApp());
expect(find.byType(HomePage), findsOneWidget);
expect(find.byType(SavedLintsPage), findsNothing);
var offset = tester.getCenter(find.text('Saved Profiles').first);
await tester.tapAt(offset);
await tester.pumpAndSettle();
expect(find.byType(SavedLintsPage), findsOneWidget);
expect(find.byType(DefaultLintsPage), findsNothing);
offset = tester.getCenter(find.text('Default Profiles').first);
await tester.tapAt(offset);
await tester.pumpAndSettle();
expect(find.byType(DefaultLintsPage), findsOneWidget);
expect(find.byType(HomePage), findsNothing);
offset = tester.getCenter(find.text('Home').first);
await tester.tapAt(offset);
await tester.pumpAndSettle();
expect(find.byType(HomePage), findsOneWidget);
});
}
| samples/experimental/linting_tool/test/widget_test.dart/0 | {
"file_path": "samples/experimental/linting_tool/test/widget_test.dart",
"repo_id": "samples",
"token_count": 1665
} | 1,322 |
/*
* Copyright (c) 2020, 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.
*/
#include "dart_api_dl.h" /* NOLINT */
#include "dart_version.h" /* NOLINT */
#include "internal/dart_api_dl_impl.h" /* NOLINT */
#include <string.h>
#define DART_API_DL_DEFINITIONS(name, R, A) name##_Type name##_DL = NULL;
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DEFINITIONS)
#undef DART_API_DL_DEFINITIONS
typedef void* DartApiEntry_function;
DartApiEntry_function FindFunctionPointer(const DartApiEntry* entries,
const char* name) {
while (entries->name != NULL) {
if (strcmp(entries->name, name) == 0) return entries->function;
entries++;
}
return NULL;
}
intptr_t Dart_InitializeApiDL(void* data) {
DartApi* dart_api_data = (DartApi*)data;
if (dart_api_data->major != DART_API_DL_MAJOR_VERSION) {
// If the DartVM we're running on does not have the same version as this
// file was compiled against, refuse to initialize. The symbols are not
// compatible.
return -1;
}
// Minor versions are allowed to be different.
// If the DartVM has a higher minor version, it will provide more symbols
// than we initialize here.
// If the DartVM has a lower minor version, it will not provide all symbols.
// In that case, we leave the missing symbols un-initialized. Those symbols
// should not be used by the Dart and native code. The client is responsible
// for checking the minor version number himself based on which symbols it
// is using.
// (If we would error out on this case, recompiling native code against a
// newer SDK would break all uses on older SDKs, which is too strict.)
const DartApiEntry* dart_api_function_pointers = dart_api_data->functions;
#define DART_API_DL_INIT(name, R, A) \
name##_DL = \
(name##_Type)(FindFunctionPointer(dart_api_function_pointers, #name));
DART_API_ALL_DL_SYMBOLS(DART_API_DL_INIT)
#undef DART_API_DL_INIT
return 0;
}
| samples/experimental/pedometer/src/dart-sdk/include/dart_api_dl.c/0 | {
"file_path": "samples/experimental/pedometer/src/dart-sdk/include/dart_api_dl.c",
"repo_id": "samples",
"token_count": 876
} | 1,323 |
org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true
android.enableJetifier=true
| samples/experimental/varfont_shader_puzzle/android/gradle.properties/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/android/gradle.properties",
"repo_id": "samples",
"token_count": 30
} | 1,324 |
// Copyright 2023 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import '../components/components.dart';
import '../page_content/pages_flow.dart';
import '../styles.dart';
class PageOpticalSize extends SinglePage {
const PageOpticalSize({
super.key,
required super.pageConfig,
});
@override
State<SinglePage> createState() => _PageOpticalSizeState();
}
class _PageOpticalSizeState extends SinglePageState {
@override
Widget createTopicIntro() {
return LightboxedPanel(
pageConfig: widget.pageConfig,
content: [
Text(
'Optical Size'.toUpperCase(),
style: TextStyles.headlineStyle(),
textAlign: TextAlign.left,
),
Text(
'Optical size adjusts the type according to how large it will be shown. '
'Smaller type usually calls for less contrast between the thin and thick '
'parts the letter, while larger type calls for more contrast. '
'Put this glitching letter back together and lock in the optical size!',
style: TextStyles.bodyStyle(),
textAlign: TextAlign.left,
),
],
);
}
@override
List<Widget> buildWonkyChars() {
return <Widget>[
Positioned(
left: widget.pageConfig.wonkyCharLargeSize * -0.13,
top: widget.pageConfig.wonkyCharLargeSize * -0.3,
child: WonkyChar(
text: 'O',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: 0.15 * pi,
animDurationMillis: 3200,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
curve: Curves.easeInOut,
),
WonkyAnimPalette.opticalSize(
from: 70,
to: 144,
)
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.37,
top: widget.pageConfig.wonkyCharLargeSize * 0.37,
child: WonkyChar(
text: '@',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.12 * pi,
animDurationMillis: 3200,
animationSettings: [
WonkyAnimPalette.weight(
from: PageConfig.baseWeight,
to: PageConfig.baseWeight,
curve: Curves.easeInOut,
),
WonkyAnimPalette.opticalSize(
from: 78,
to: 8,
),
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.57,
top: widget.pageConfig.wonkyCharSmallSize * -0.02,
child: WonkyChar(
text: 'r',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.15 * pi,
animationSettings: [
WonkyAnimPalette.opticalSize(
from: 32,
to: 106,
)
],
),
),
Positioned(
right: widget.pageConfig.wonkyCharLargeSize * 0.03,
top: widget.pageConfig.wonkyCharLargeSize * -0.26,
child: WonkyChar(
text: 'e',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -0.15 * pi,
animDurationMillis: 5000,
animationSettings: [
WonkyAnimPalette.opticalSize(
from: 70,
to: 144,
)
],
),
),
// lower half --------------------------------------
Positioned(
left: widget.pageConfig.wonkyCharLargeSize * 0.1,
bottom: widget.pageConfig.wonkyCharLargeSize * 0.05,
child: WonkyChar(
text: 'i',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -0.04 * pi,
animationSettings: [
WonkyAnimPalette.opticalSize(
from: 40,
to: 8,
),
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.37,
bottom: widget.pageConfig.wonkyCharLargeSize * -0.04,
child: WonkyChar(
text: 'Z',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.15 * pi,
animationSettings: [
WonkyAnimPalette.opticalSize(
from: 8,
to: 60,
),
],
),
),
Positioned(
right: widget.pageConfig.wonkyCharLargeSize * -0.14,
bottom: widget.pageConfig.wonkyCharLargeSize * -0.1,
child: WonkyChar(
text: 'A',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: 0.15 * pi,
animDurationMillis: 12000,
animationSettings: [
WonkyAnimPalette.opticalSize(
from: 80,
to: 20,
),
WonkyAnimPalette.rotation(
from: -0.01 * pi,
to: 0.01 * pi,
),
],
),
),
];
}
@override
Widget createPuzzle() {
return RotatorPuzzle(
pageConfig: widget.pageConfig,
numTiles: 16,
puzzleNum: 4,
shader: Shader.wavy,
shaderDuration: 5000,
tileShadedString: 'Z',
tileShadedStringPadding:
EdgeInsets.only(bottom: 0.349 * widget.pageConfig.puzzleSize),
tileScaleModifier: 2.6,
tileShadedStringSize: 2.79 * widget.pageConfig.puzzleSize,
tileShadedStringAnimDuration: 3000,
tileShadedStringAnimSettings: [
WonkyAnimPalette.weight(from: 1000, to: 1000),
WonkyAnimPalette.width(from: 125, to: 125),
WonkyAnimPalette.opticalSize(from: 8, to: 144)
],
);
}
}
| samples/experimental/varfont_shader_puzzle/lib/page_content/page_optical_size.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/page_optical_size.dart",
"repo_id": "samples",
"token_count": 2890
} | 1,325 |
// 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.
#define PI 3.1415926538
uniform float uTime;
uniform vec2 uSize;
uniform float uDampener;
out vec4 fragColor;
uniform sampler2D uTexture;
void main()
{
float piTime = uTime * PI * 2;
vec2 texCoord = gl_FragCoord.xy / uSize.xy;
fragColor = texture(uTexture, texCoord);
}
| samples/experimental/varfont_shader_puzzle/shaders/nothing.frag/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/shaders/nothing.frag",
"repo_id": "samples",
"token_count": 154
} | 1,326 |
// 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.
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'api.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Category _$CategoryFromJson(Map<String, dynamic> json) {
return Category(
json['name'] as String,
);
}
Map<String, dynamic> _$CategoryToJson(Category instance) => <String, dynamic>{
'name': instance.name,
};
Entry _$EntryFromJson(Map<String, dynamic> json) {
return Entry(
json['value'] as int,
Entry._timestampToDateTime(json['time'] as Timestamp),
);
}
Map<String, dynamic> _$EntryToJson(Entry instance) => <String, dynamic>{
'value': instance.value,
'time': Entry._dateTimeToTimestamp(instance.time),
};
| samples/experimental/web_dashboard/lib/src/api/api.g.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/api/api.g.dart",
"repo_id": "samples",
"token_count": 306
} | 1,327 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:web_dashboard/src/api/api.dart';
import 'package:web_dashboard/src/widgets/category_forms.dart';
import '../app.dart';
import 'edit_entry.dart';
class NewCategoryDialog extends StatelessWidget {
const NewCategoryDialog({super.key});
@override
Widget build(BuildContext context) {
return const SimpleDialog(
title: Text('New Category'),
children: [
NewCategoryForm(),
],
);
}
}
class EditCategoryDialog extends StatelessWidget {
final Category category;
const EditCategoryDialog({
required this.category,
super.key,
});
@override
Widget build(BuildContext context) {
var api = Provider.of<AppState>(context).api;
return SimpleDialog(
title: const Text('Edit Category'),
children: [
EditCategoryForm(
category: category,
onDone: (shouldUpdate) {
if (shouldUpdate) {
api!.categories.update(category, category.id!);
}
Navigator.of(context).pop();
},
),
],
);
}
}
class NewEntryDialog extends StatefulWidget {
const NewEntryDialog({super.key});
@override
State<NewEntryDialog> createState() => _NewEntryDialogState();
}
class _NewEntryDialogState extends State<NewEntryDialog> {
@override
Widget build(BuildContext context) {
return const SimpleDialog(
title: Text('New Entry'),
children: [
NewEntryForm(),
],
);
}
}
class EditEntryDialog extends StatelessWidget {
final Category? category;
final Entry? entry;
const EditEntryDialog({
this.category,
this.entry,
super.key,
});
@override
Widget build(BuildContext context) {
var api = Provider.of<AppState>(context).api;
return SimpleDialog(
title: const Text('Edit Entry'),
children: [
EditEntryForm(
entry: entry,
onDone: (shouldUpdate) {
if (shouldUpdate) {
api!.entries.update(category!.id!, entry!.id!, entry!);
}
Navigator.of(context).pop();
},
)
],
);
}
}
| samples/experimental/web_dashboard/lib/src/widgets/dialogs.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/widgets/dialogs.dart",
"repo_id": "samples",
"token_count": 937
} | 1,328 |
# Run with tooling from https://github.com/flutter/codelabs/tree/main/tooling/codelab_rebuild
name: Flutter Maps Firestore rebuild script
steps:
- name: Remove the runner
rmdirs:
- ios
- name: Recreate runner
flutter: create --platforms ios .
- name: Create GoogleService-Info.plist
path: ios/GoogleService-Info.plist
replace-contents: |
<?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>
<!--
TODO: Replace this file with credentials from Cloud Firestore.
See https://pub.dev/packages/cloud_firestore#setup for more detail.
-->
</dict>
</plist>
- name: Patch Podfile
path: ios/Podfile
patch-u: |
--- b/flutter_maps_firestore/ios/Podfile
+++ a/flutter_maps_firestore/ios/Podfile
@@ -1,5 +1,5 @@
# Uncomment this line to define a global platform for your project
-# platform :ios, '11.0'
+platform :ios, '14.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
@@ -37,5 +37,8 @@ end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
+ target.build_configurations.each do |config|
+ config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '14.0'
+ end
end
end
- name: Patch ios/Flutter/AppFrameworkInfo.plist
path: ios/Flutter/AppFrameworkInfo.plist
patch-u: |
--- b/flutter_maps_firestore/ios/Flutter/AppFrameworkInfo.plist
+++ a/flutter_maps_firestore/ios/Flutter/AppFrameworkInfo.plist
@@ -21,6 +21,6 @@
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
- <string>11.0</string>
+ <string>14.0</string>
</dict>
</plist>
- name: Patch ios/Runner/AppDelegate.swift
path: ios/Runner/AppDelegate.swift
patch-u: |
--- b/flutter_maps_firestore/ios/Runner/AppDelegate.swift
+++ a/flutter_maps_firestore/ios/Runner/AppDelegate.swift
@@ -1,5 +1,6 @@
import UIKit
import Flutter
+import GoogleMaps
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
@@ -7,7 +8,11 @@ import Flutter
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
+ // TODO: Replace this with an API key that has Google Maps for iOS enabled
+ // See https://developers.google.com/maps/documentation/ios-sdk/get-api-key
+ GMSServices.provideAPIKey("ADD_A_KEY_HERE")
GeneratedPluginRegistrant.register(with: self)
+
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
- name: Patch ios/Runner/Info.plist
path: ios/Runner/Info.plist
patch-u: |
--- b/flutter_maps_firestore/ios/Runner/Info.plist
+++ a/flutter_maps_firestore/ios/Runner/Info.plist
@@ -2,10 +2,12 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
+ <key>NSLocationWhenInUseUsageDescription</key>
+ <string>Finding Ice Cream stores near you</string>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
- <string>Flutter Maps Firestore</string>
+ <string>Find Ice Cream</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
- name: flutter pub upgrade
flutter: pub upgrade --major-versions
- name: flutter build ios
flutter: build ios --simulator
| samples/flutter_maps_firestore/codelab_rebuild.yaml/0 | {
"file_path": "samples/flutter_maps_firestore/codelab_rebuild.yaml",
"repo_id": "samples",
"token_count": 1798
} | 1,329 |
import UIKit
import Flutter
import GoogleMaps
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// TODO: Replace this with an API key that has Google Maps for iOS enabled
// See https://developers.google.com/maps/documentation/ios-sdk/get-api-key
GMSServices.provideAPIKey("ADD_A_KEY_HERE")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| samples/flutter_maps_firestore/ios/Runner/AppDelegate.swift/0 | {
"file_path": "samples/flutter_maps_firestore/ios/Runner/AppDelegate.swift",
"repo_id": "samples",
"token_count": 210
} | 1,330 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
// Demonstrates how to use autofill hints. The full list of hints is here:
// https://github.com/flutter/engine/blob/master/lib/web_ui/lib/src/engine/text_editing/autofill_hint.dart
class AutofillDemo extends StatefulWidget {
const AutofillDemo({super.key});
@override
State<AutofillDemo> createState() => _AutofillDemoState();
}
class _AutofillDemoState extends State<AutofillDemo> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Autofill'),
),
body: Form(
key: _formKey,
child: Scrollbar(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: AutofillGroup(
child: Column(
children: [
...[
const Text('This sample demonstrates autofill. '),
TextFormField(
autofocus: true,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(
hintText: 'Jane',
labelText: 'First Name',
),
autofillHints: const [AutofillHints.givenName],
),
TextFormField(
textInputAction: TextInputAction.next,
decoration: const InputDecoration(
hintText: 'Doe',
labelText: 'Last Name',
),
autofillHints: const [AutofillHints.familyName],
),
const TextField(
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: '[email protected]',
labelText: 'Email',
),
autofillHints: [AutofillHints.email],
),
const TextField(
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: '(123) 456-7890',
labelText: 'Telephone',
),
autofillHints: [AutofillHints.telephoneNumber],
),
const TextField(
keyboardType: TextInputType.streetAddress,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: '123 4th Ave',
labelText: 'Street Address',
),
autofillHints: [AutofillHints.streetAddressLine1],
),
const TextField(
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: '12345',
labelText: 'Postal Code',
),
autofillHints: [AutofillHints.postalCode],
),
const TextField(
textInputAction: TextInputAction.next,
decoration: InputDecoration(
hintText: 'United States',
labelText: 'Country',
),
autofillHints: [AutofillHints.countryName],
),
const TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: '1',
labelText: 'Country Code',
),
autofillHints: [AutofillHints.countryCode],
),
].expand(
(widget) => [
widget,
const SizedBox(
height: 24,
)
],
)
],
),
),
),
),
),
);
}
}
| samples/form_app/lib/src/autofill.dart/0 | {
"file_path": "samples/form_app/lib/src/autofill.dart",
"repo_id": "samples",
"token_count": 2728
} | 1,331 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/foundation.dart';
/// An extremely silly example of a game state.
///
/// Tracks only a single variable, [progress], and calls [onWin] when
/// the value of [progress] reaches [goal].
class LevelState extends ChangeNotifier {
final VoidCallback onWin;
final int goal;
LevelState({required this.onWin, this.goal = 100});
int _progress = 0;
int get progress => _progress;
void setProgress(int value) {
_progress = value;
notifyListeners();
}
void evaluate() {
if (_progress >= goal) {
onWin();
}
}
}
| samples/game_template/lib/src/game_internals/level_state.dart/0 | {
"file_path": "samples/game_template/lib/src/game_internals/level_state.dart",
"repo_id": "samples",
"token_count": 233
} | 1,332 |
// 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.
/// An interface of persistence stores for settings.
///
/// Implementations can range from simple in-memory storage through
/// local preferences to cloud-based solutions.
abstract class SettingsPersistence {
Future<bool> getMusicOn();
Future<bool> getMuted({required bool defaultValue});
Future<String> getPlayerName();
Future<bool> getSoundsOn();
Future<void> saveMusicOn(bool value);
Future<void> saveMuted(bool value);
Future<void> savePlayerName(String value);
Future<void> saveSoundsOn(bool value);
}
| samples/game_template/lib/src/settings/persistence/settings_persistence.dart/0 | {
"file_path": "samples/game_template/lib/src/settings/persistence/settings_persistence.dart",
"repo_id": "samples",
"token_count": 195
} | 1,333 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
import 'package:game_template/main.dart';
import 'package:game_template/src/player_progress/persistence/memory_player_progress_persistence.dart';
import 'package:game_template/src/settings/persistence/memory_settings_persistence.dart';
void main() {
testWidgets('smoke test', (tester) async {
// Build our game and trigger a frame.
await tester.pumpWidget(MyApp(
settingsPersistence: MemoryOnlySettingsPersistence(),
playerProgressPersistence: MemoryOnlyPlayerProgressPersistence(),
adsController: null,
gamesServicesController: null,
inAppPurchaseController: null,
));
// Verify that the 'Play' button is shown.
expect(find.text('Play'), findsOneWidget);
// Verify that the 'Settings' button is shown.
expect(find.text('Settings'), findsOneWidget);
// Go to 'Settings'.
await tester.tap(find.text('Settings'));
await tester.pumpAndSettle();
expect(find.text('Music'), findsOneWidget);
// Go back to main menu.
await tester.tap(find.text('Back'));
await tester.pumpAndSettle();
// Tap 'Play'.
await tester.tap(find.text('Play'));
await tester.pumpAndSettle();
expect(find.text('Select level'), findsOneWidget);
// Tap level 1.
await tester.tap(find.text('Level #1'));
await tester.pumpAndSettle();
// Find the first level's "tutorial" text.
expect(find.text('Drag the slider to 5% or above!'), findsOneWidget);
});
}
| samples/game_template/test/smoke_test.dart/0 | {
"file_path": "samples/game_template/test/smoke_test.dart",
"repo_id": "samples",
"token_count": 572
} | 1,334 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google_maps_in_flutter">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
| samples/google_maps/android/app/src/debug/AndroidManifest.xml/0 | {
"file_path": "samples/google_maps/android/app/src/debug/AndroidManifest.xml",
"repo_id": "samples",
"token_count": 135
} | 1,335 |
include: package:analysis_defaults/flutter.yaml
| samples/ios_app_clip/analysis_options.yaml/0 | {
"file_path": "samples/ios_app_clip/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,336 |
# Isolate Example
A sample application that demonstrate best practices when using [`isolates`](https://api.dartlang.org/stable/2.3.1/dart-isolate/Isolate-class.html).
## Goals
* Display the performance benefits of isolates when using them in the right situation.
* Show how to use the `compute` method for straightforward computations.
* Demonstrate how to initialize and use an isolate.
* Show the cost of moving data between isolates and provide alternatives.
## The important bits
### `performance_page.dart`
Compares running a large computation on the main isolate with running the same calculation
on a second isolate. When the main isolate is used, Flutter is unable to render new frames, and
the `SmoothAnimationWidget`'s animation freezes.
### `infinite_process_page.dart`
Creates an isolate used to run an infinite loop that sums batches of 100M randomly generated
numbers at a time. Users can start, terminate, pause, and resume the isolate, as well as modify
how the calculation is performed.
### `data_transfer_page.dart`
Demonstrates how expensive it is to move large amounts of data between isolates and a
better alternative to move data. This page creates an isolate that can add up a list of numbers
and gives users three options for how to provide it with input:
* Send values normally using a List
* Send the values using TransferableTypedData
* Generate the values on the second isolate, so no copying is necessary
Users can then compare the performance of each approach using the displayed timestamps.
## Questions/issues
If you have a general question about any of the techniques you see in
the sample, the best places to go are:
* [The FlutterDev Google Group](https://groups.google.com/forum/#!forum/flutter-dev)
* [The Flutter Gitter channel](https://gitter.im/flutter/flutter)
* [StackOverflow](https://stackoverflow.com/questions/tagged/flutter)
If you run into an issue with the sample itself, please file an issue
in the [main Flutter repo](https://github.com/flutter/flutter/issues).
| samples/isolate_example/README.md/0 | {
"file_path": "samples/isolate_example/README.md",
"repo_id": "samples",
"token_count": 524
} | 1,337 |
// Copyright 2019-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:window_size/window_size.dart';
import 'data_transfer_page.dart';
import 'infinite_process_page.dart';
import 'performance_page.dart';
void main() {
setupWindow();
runApp(
const MaterialApp(
home: HomePage(),
),
);
}
const double windowWidth = 1024;
const double windowHeight = 800;
void setupWindow() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowTitle('Isolate Example');
setWindowMinSize(const Size(windowWidth, windowHeight));
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light(),
home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(
icon: Icon(Icons.flash_on),
text: 'Performance',
),
Tab(
icon: Icon(Icons.sync),
text: 'Infinite Process',
),
Tab(
icon: Icon(Icons.storage),
text: 'Data Transfer',
),
],
),
title: const Text('Isolate Example'),
),
body: const TabBarView(
children: [
PerformancePage(),
InfiniteProcessPageStarter(),
DataTransferPageStarter(),
],
),
),
),
);
}
}
| samples/isolate_example/lib/main.dart/0 | {
"file_path": "samples/isolate_example/lib/main.dart",
"repo_id": "samples",
"token_count": 999
} | 1,338 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/isolate_example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/isolate_example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,339 |
include: package:analysis_defaults/flutter.yaml
| samples/material_3_demo/analysis_options.yaml/0 | {
"file_path": "samples/material_3_demo/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,340 |
// 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 ElevationScreen extends StatelessWidget {
const ElevationScreen({super.key});
@override
Widget build(BuildContext context) {
Color shadowColor = Theme.of(context).colorScheme.shadow;
Color surfaceTint = Theme.of(context).colorScheme.primary;
return Expanded(
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(16.0, 20, 16.0, 0),
child: Text(
'Surface Tint Color Only',
style: Theme.of(context).textTheme.titleLarge,
),
),
),
ElevationGrid(
surfaceTintColor: surfaceTint,
shadowColor: Colors.transparent,
),
SliverList(
delegate: SliverChildListDelegate(<Widget>[
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 0),
child: Text(
'Surface Tint Color and Shadow Color',
style: Theme.of(context).textTheme.titleLarge,
),
),
]),
),
ElevationGrid(
shadowColor: shadowColor,
surfaceTintColor: surfaceTint,
),
SliverList(
delegate: SliverChildListDelegate(<Widget>[
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 0),
child: Text(
'Shadow Color Only',
style: Theme.of(context).textTheme.titleLarge,
),
),
]),
),
ElevationGrid(shadowColor: shadowColor),
],
),
);
}
}
const double narrowScreenWidthThreshold = 450;
class ElevationGrid extends StatelessWidget {
const ElevationGrid({super.key, this.shadowColor, this.surfaceTintColor});
final Color? shadowColor;
final Color? surfaceTintColor;
List<ElevationCard> elevationCards(
Color? shadowColor, Color? surfaceTintColor) {
return elevations
.map(
(elevationInfo) => ElevationCard(
info: elevationInfo,
shadowColor: shadowColor,
surfaceTint: surfaceTintColor,
),
)
.toList();
}
@override
Widget build(BuildContext context) {
return SliverPadding(
padding: const EdgeInsets.all(8),
sliver: SliverLayoutBuilder(builder: (context, constraints) {
if (constraints.crossAxisExtent < narrowScreenWidthThreshold) {
return SliverGrid.count(
crossAxisCount: 3,
children: elevationCards(shadowColor, surfaceTintColor),
);
} else {
return SliverGrid.count(
crossAxisCount: 6,
children: elevationCards(shadowColor, surfaceTintColor),
);
}
}),
);
}
}
class ElevationCard extends StatefulWidget {
const ElevationCard(
{super.key, required this.info, this.shadowColor, this.surfaceTint});
final ElevationInfo info;
final Color? shadowColor;
final Color? surfaceTint;
@override
State<ElevationCard> createState() => _ElevationCardState();
}
class _ElevationCardState extends State<ElevationCard> {
late double _elevation;
@override
void initState() {
super.initState();
_elevation = widget.info.elevation;
}
@override
Widget build(BuildContext context) {
const BorderRadius borderRadius = BorderRadius.all(Radius.circular(4.0));
final Color color = Theme.of(context).colorScheme.surface;
return Padding(
padding: const EdgeInsets.all(8.0),
child: Material(
borderRadius: borderRadius,
elevation: _elevation,
color: color,
shadowColor: widget.shadowColor,
surfaceTintColor: widget.surfaceTint,
type: MaterialType.card,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Level ${widget.info.level}',
style: Theme.of(context).textTheme.labelMedium,
),
Text(
'${widget.info.elevation.toInt()} dp',
style: Theme.of(context).textTheme.labelMedium,
),
if (widget.surfaceTint != null)
Expanded(
child: Align(
alignment: Alignment.bottomRight,
child: Text(
'${widget.info.overlayPercent}%',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
],
),
),
),
);
}
}
class ElevationInfo {
const ElevationInfo(this.level, this.elevation, this.overlayPercent);
final int level;
final double elevation;
final int overlayPercent;
}
const List<ElevationInfo> elevations = <ElevationInfo>[
ElevationInfo(0, 0.0, 0),
ElevationInfo(1, 1.0, 5),
ElevationInfo(2, 3.0, 8),
ElevationInfo(3, 6.0, 11),
ElevationInfo(4, 8.0, 12),
ElevationInfo(5, 12.0, 14),
];
| samples/material_3_demo/lib/elevation_screen.dart/0 | {
"file_path": "samples/material_3_demo/lib/elevation_screen.dart",
"repo_id": "samples",
"token_count": 2619
} | 1,341 |
package dev.flutter.navigation_and_routing
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/navigation_and_routing/android/app/src/main/kotlin/dev/flutter/navigation_and_routing/MainActivity.kt/0 | {
"file_path": "samples/navigation_and_routing/android/app/src/main/kotlin/dev/flutter/navigation_and_routing/MainActivity.kt",
"repo_id": "samples",
"token_count": 43
} | 1,342 |
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import '../data/author.dart';
import '../data/library.dart';
import '../widgets/author_list.dart';
class AuthorsScreen extends StatelessWidget {
final String title;
final ValueChanged<Author> onTap;
const AuthorsScreen({
required this.onTap,
this.title = 'Authors',
super.key,
});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(title),
),
body: AuthorList(
authors: libraryInstance.allAuthors,
onTap: onTap,
),
);
}
| samples/navigation_and_routing/lib/src/screens/authors.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/screens/authors.dart",
"repo_id": "samples",
"token_count": 294
} | 1,343 |
// 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:bookstore/src/data/library.dart';
import 'package:test/test.dart';
void main() {
group('Library', () {
test('addBook', () {
final library = Library();
library.addBook(
title: 'Left Hand of Darkness',
authorName: 'Ursula K. Le Guin',
isPopular: true,
isNew: true);
library.addBook(
title: 'Too Like the Lightning',
authorName: 'Ada Palmer',
isPopular: false,
isNew: true);
library.addBook(
title: 'Kindred',
authorName: 'Octavia E. Butler',
isPopular: true,
isNew: false);
library.addBook(
title: 'The Lathe of Heaven',
authorName: 'Ursula K. Le Guin',
isPopular: false,
isNew: false);
expect(library.allAuthors.length, 3);
expect(library.allAuthors.first.books.length, 2);
expect(library.allBooks.length, 4);
expect(library.allBooks.first.author.name, startsWith('Ursula'));
});
});
}
| samples/navigation_and_routing/test/library_test.dart/0 | {
"file_path": "samples/navigation_and_routing/test/library_test.dart",
"repo_id": "samples",
"token_count": 535
} | 1,344 |
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
android {
namespace "dev.flutter.place_tracker"
compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "dev.flutter.place_tracker"
// Google Maps requires a minimum SDK version of 20
minSdkVersion 20
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
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
}
}
}
flutter {
source '../..'
}
dependencies {}
| samples/place_tracker/android/app/build.gradle/0 | {
"file_path": "samples/place_tracker/android/app/build.gradle",
"repo_id": "samples",
"token_count": 676
} | 1,345 |
// 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:google_maps_flutter/google_maps_flutter.dart';
class Place {
final String id;
final LatLng latLng;
final String name;
final PlaceCategory category;
final String? description;
final int starRating;
const Place({
required this.id,
required this.latLng,
required this.name,
required this.category,
this.description,
this.starRating = 0,
}) : assert(starRating >= 0 && starRating <= 5);
double get latitude => latLng.latitude;
double get longitude => latLng.longitude;
Place copyWith({
String? id,
LatLng? latLng,
String? name,
PlaceCategory? category,
String? description,
int? starRating,
}) {
return Place(
id: id ?? this.id,
latLng: latLng ?? this.latLng,
name: name ?? this.name,
category: category ?? this.category,
description: description ?? this.description,
starRating: starRating ?? this.starRating,
);
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Place &&
runtimeType == other.runtimeType &&
id == other.id &&
latLng == other.latLng &&
name == other.name &&
category == other.category &&
description == other.description &&
starRating == other.starRating;
@override
int get hashCode =>
id.hashCode ^
latLng.hashCode ^
name.hashCode ^
category.hashCode ^
description.hashCode ^
starRating.hashCode;
}
enum PlaceCategory {
favorite,
visited,
wantToGo,
}
| samples/place_tracker/lib/place.dart/0 | {
"file_path": "samples/place_tracker/lib/place.dart",
"repo_id": "samples",
"token_count": 652
} | 1,346 |
// 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:platform_channels/main.dart';
void main() {
group('HomePage tests', () {
testWidgets('HomePage has multiple Text widgets', (tester) async {
await tester.pumpWidget(const MaterialApp(
home: HomePage(),
));
expect(find.byType(Text), findsWidgets);
});
});
}
| samples/platform_channels/test/home_page_test.dart/0 | {
"file_path": "samples/platform_channels/test/home_page_test.dart",
"repo_id": "samples",
"token_count": 194
} | 1,347 |
// Copyright 2018, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const PlatformView());
}
class PlatformView extends StatelessWidget {
const PlatformView({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Platform View',
theme: ThemeData(
primarySwatch: Colors.grey,
),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static const MethodChannel _methodChannel =
MethodChannel('dev.flutter.sample/platform_view_swift');
int _counter = 0;
Future<void> _launchPlatformCount() async {
final platformCounter =
await _methodChannel.invokeMethod<int>('switchView', _counter);
setState(() => _counter = platformCounter ?? 0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home page'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 18),
ElevatedButton(
onPressed: _launchPlatformCount,
child: const Text('Continue in iOS view'),
),
],
),
),
),
Container(
padding: const EdgeInsets.only(bottom: 15, left: 5),
child: Row(
children: [
const FlutterLogo(),
Text(
'Flutter',
style: Theme.of(context).textTheme.headlineSmall,
),
],
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _counter++),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
| samples/platform_view_swift/lib/main.dart/0 | {
"file_path": "samples/platform_view_swift/lib/main.dart",
"repo_id": "samples",
"token_count": 1204
} | 1,348 |
#import "GeneratedPluginRegistrant.h"
| samples/provider_counter/ios/Runner/Runner-Bridging-Header.h/0 | {
"file_path": "samples/provider_counter/ios/Runner/Runner-Bridging-Header.h",
"repo_id": "samples",
"token_count": 13
} | 1,349 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/simplistic_calculator/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/simplistic_calculator/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,350 |
// 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 Driver Tests', () {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('Finding an item in the list', (tester) async {
await tester.pumpWidget(const TestingApp());
// Create variables for finders that are used multiple times.
final itemFinder = find.byKey(const ValueKey('text_25'));
// Scroll until the item to be found appears.
await tester.scrollUntilVisible(
itemFinder,
500.0,
);
// Check if the item contains the correct text.
expect(tester.widget<Text>(itemFinder).data, 'Item 25');
});
testWidgets('Testing IconButtons', (tester) async {
await tester.pumpWidget(const TestingApp());
// Create a finder for the icon.
final iconFinder = find.byKey(const ValueKey('icon_0'));
// Tap on the icon.
await tester.tap(iconFinder);
// Wait 1 second for the SnackBar to be displayed
await tester.pumpAndSettle(const Duration(seconds: 1));
// Verify if appropriate message appears.
expect(find.text('Added to favorites.'), findsOneWidget);
// Tap on the icon again.
await tester.tap(iconFinder);
// Wait 1 second for the SnackBar to be displayed
await tester.pumpAndSettle(const Duration(seconds: 1));
// Verify if appropriate message appears.
expect(find.text('Removed from favorites.'), findsOneWidget);
});
testWidgets('Verifying whether item gets added to favorites',
(tester) async {
await tester.pumpWidget(const TestingApp());
// Add item to favorites.
await tester.tap(find.byKey(const ValueKey('icon_5')));
await tester.pumpAndSettle();
// Tap on the favorites button on the AppBar.
// The Favorites List should appear.
await tester.tap(find.text('Favorites'));
await tester.pumpAndSettle();
// Check if the added item has appeared in the list.
expect(
tester
.widget<Text>(find.byKey(const ValueKey('favorites_text_5')))
.data,
equals('Item 5'),
);
});
testWidgets('Testing remove button', (tester) async {
await tester.pumpWidget(const TestingApp());
// Add item to favorites.
await tester.tap(find.byKey(const ValueKey('icon_5')));
await tester.pumpAndSettle();
// Navigate to Favorites screen.
await tester.tap(find.text('Favorites'));
await tester.pumpAndSettle();
// Tap on the remove icon.
await tester.tap(find.byKey(const ValueKey('remove_icon_5')));
// Wait 1 second for the SnackBar to be displayed
await tester.pumpAndSettle(const Duration(seconds: 1));
// Verify if it disappears.
expect(find.text('Item 5'), findsNothing);
// Verify if appropriate message appears.
expect(find.text('Removed from favorites.'), findsOneWidget);
});
});
}
| samples/testing_app/integration_test/app_test.dart/0 | {
"file_path": "samples/testing_app/integration_test/app_test.dart",
"repo_id": "samples",
"token_count": 1205
} | 1,351 |
// 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:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:testing_app/models/favorites.dart';
import 'package:testing_app/screens/favorites.dart';
class HomePage extends StatelessWidget {
static const routeName = '/';
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Testing Sample'),
actions: [
TextButton.icon(
onPressed: () {
context.go(FavoritesPage.fullPath);
},
icon: const Icon(Icons.favorite_border),
label: const Text('Favorites'),
),
],
),
body: ListView.builder(
itemCount: 100,
cacheExtent: 20.0,
controller: ScrollController(),
padding: const EdgeInsets.symmetric(vertical: 16),
itemBuilder: (context, index) => ItemTile(index),
),
);
}
}
class ItemTile extends StatelessWidget {
final int itemNo;
const ItemTile(this.itemNo, {super.key});
@override
Widget build(BuildContext context) {
final favoritesList = context.watch<Favorites>();
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.primaries[itemNo % Colors.primaries.length],
),
title: Text(
'Item $itemNo',
key: Key('text_$itemNo'),
),
trailing: IconButton(
key: Key('icon_$itemNo'),
icon: favoritesList.items.contains(itemNo)
? const Icon(Icons.favorite)
: const Icon(Icons.favorite_border),
onPressed: () {
!favoritesList.items.contains(itemNo)
? favoritesList.add(itemNo)
: favoritesList.remove(itemNo);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(favoritesList.items.contains(itemNo)
? 'Added to favorites.'
: 'Removed from favorites.'),
duration: const Duration(seconds: 1),
),
);
},
),
),
);
}
}
| samples/testing_app/lib/screens/home.dart/0 | {
"file_path": "samples/testing_app/lib/screens/home.dart",
"repo_id": "samples",
"token_count": 1108
} | 1,352 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/testing_app/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/testing_app/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,353 |
// Copyright 2018 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:veggieseasons/data/preferences.dart';
import 'package:veggieseasons/data/veggie.dart';
import 'package:veggieseasons/styles.dart';
import 'package:veggieseasons/widgets/settings_group.dart';
import 'package:veggieseasons/widgets/settings_item.dart';
class VeggieCategorySettingsScreen extends StatelessWidget {
const VeggieCategorySettingsScreen({super.key, this.restorationId});
final String? restorationId;
static Page<void> pageBuilder(BuildContext context) {
return const CupertinoPage(
restorationId: 'router.categories',
child: VeggieCategorySettingsScreen(restorationId: 'category'),
title: 'Preferred Categories',
);
}
@override
Widget build(BuildContext context) {
final model = Provider.of<Preferences>(context);
final currentPrefs = model.preferredCategories;
var brightness = CupertinoTheme.brightnessOf(context);
return RestorationScope(
restorationId: restorationId,
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Preferred Categories'),
previousPageTitle: 'Settings',
),
backgroundColor: Styles.scaffoldBackground(brightness),
child: FutureBuilder<Set<VeggieCategory>>(
future: currentPrefs,
builder: (context, snapshot) {
final items = <SettingsItem>[];
for (final category in VeggieCategory.values) {
CupertinoSwitch toggle;
// It's possible that category data hasn't loaded from shared prefs
// yet, so display it if possible and fall back to disabled switches
// otherwise.
if (snapshot.hasData) {
toggle = CupertinoSwitch(
value: snapshot.data!.contains(category),
onChanged: (value) {
if (value) {
model.addPreferredCategory(category);
} else {
model.removePreferredCategory(category);
}
},
);
} else {
toggle = const CupertinoSwitch(
value: false,
onChanged: null,
);
}
items.add(SettingsItem(
label: veggieCategoryNames[category]!,
content: toggle,
));
}
return ListView(
restorationId: 'list',
children: [
SettingsGroup(
items: items,
),
],
);
},
),
),
);
}
}
class CalorieSettingsScreen extends StatelessWidget {
const CalorieSettingsScreen({super.key, this.restorationId});
final String? restorationId;
static const max = 1000;
static const min = 2600;
static const step = 200;
static Page<void> pageBuilder(BuildContext context) {
return const CupertinoPage<void>(
restorationId: 'router.calorie',
child: CalorieSettingsScreen(restorationId: 'calorie'),
title: 'Calorie Target',
);
}
@override
Widget build(BuildContext context) {
final model = Provider.of<Preferences>(context);
var brightness = CupertinoTheme.brightnessOf(context);
return RestorationScope(
restorationId: restorationId,
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
previousPageTitle: 'Settings',
),
backgroundColor: Styles.scaffoldBackground(brightness),
child: ListView(
restorationId: 'list',
children: [
FutureBuilder<int>(
future: model.desiredCalories,
builder: (context, snapshot) {
final steps = <SettingsItem>[];
for (var cals = max; cals < min; cals += step) {
steps.add(
SettingsItem(
label: cals.toString(),
icon: SettingsIcon(
icon: Styles.checkIcon,
foregroundColor:
snapshot.hasData && snapshot.data == cals
? CupertinoColors.activeBlue
: Styles.transparentColor,
backgroundColor: Styles.transparentColor,
),
onPress: snapshot.hasData
? () => model.setDesiredCalories(cals)
: null,
),
);
}
return SettingsGroup(
items: steps,
header: const SettingsGroupHeader('Available calorie levels'),
footer:
const SettingsGroupFooter('These are used for serving '
'calculations'),
);
},
),
],
),
),
);
}
}
class SettingsScreen extends StatefulWidget {
const SettingsScreen({this.restorationId, super.key});
final String? restorationId;
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
SettingsItem _buildCaloriesItem(BuildContext context, Preferences prefs) {
return SettingsItem(
label: 'Calorie Target',
icon: const SettingsIcon(
backgroundColor: Styles.iconBlue,
icon: Styles.calorieIcon,
),
content: FutureBuilder<int>(
future: prefs.desiredCalories,
builder: (context, snapshot) {
return Row(
children: [
Text(
snapshot.data?.toString() ?? '',
style: CupertinoTheme.of(context).textTheme.textStyle,
),
const SizedBox(width: 8),
const SettingsNavigationIndicator(),
],
);
},
),
onPress: () {
context.go('/settings/calories');
},
);
}
SettingsItem _buildCategoriesItem(BuildContext context, Preferences prefs) {
return SettingsItem(
label: 'Preferred Categories',
subtitle: 'What types of veggies you prefer!',
icon: const SettingsIcon(
backgroundColor: Styles.iconGold,
icon: Styles.preferenceIcon,
),
content: const SettingsNavigationIndicator(),
onPress: () {
context.go('/settings/categories');
},
);
}
SettingsItem _buildRestoreDefaultsItem(
BuildContext context, Preferences prefs) {
return SettingsItem(
label: 'Restore Defaults',
icon: const SettingsIcon(
backgroundColor: CupertinoColors.systemRed,
icon: Styles.resetIcon,
),
content: const SettingsNavigationIndicator(),
onPress: () {
showCupertinoDialog<void>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Are you sure?'),
content: const Text(
'Are you sure you want to reset the current settings?',
),
actions: [
CupertinoDialogAction(
isDestructiveAction: true,
child: const Text('Yes'),
onPressed: () async {
await prefs.restoreDefaults();
if (!context.mounted) return;
context.pop();
},
),
CupertinoDialogAction(
isDefaultAction: true,
child: const Text('No'),
onPressed: () => context.pop(),
)
],
),
);
},
);
}
@override
Widget build(BuildContext context) {
final prefs = Provider.of<Preferences>(context);
return RestorationScope(
restorationId: widget.restorationId,
child: CupertinoPageScaffold(
child: Container(
color:
Styles.scaffoldBackground(CupertinoTheme.brightnessOf(context)),
child: CustomScrollView(
restorationId: 'list',
slivers: [
const CupertinoSliverNavigationBar(
largeTitle: Text('Settings'),
),
SliverSafeArea(
top: false,
sliver: SliverList(
delegate: SliverChildListDelegate(
[
SettingsGroup(
items: [
_buildCaloriesItem(context, prefs),
_buildCategoriesItem(context, prefs),
_buildRestoreDefaultsItem(context, prefs),
],
),
],
),
),
),
],
),
),
),
);
}
}
| samples/veggieseasons/lib/screens/settings.dart/0 | {
"file_path": "samples/veggieseasons/lib/screens/settings.dart",
"repo_id": "samples",
"token_count": 4464
} | 1,354 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/veggieseasons/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/veggieseasons/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,355 |
// 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/foundation.dart';
// Base class for the web (real) implementation and dart:io (stub)
// implementation.
abstract class WebStartupAnalyzerBase {
late final Listenable onChange;
ValueNotifier<double?> onFirstFrame = ValueNotifier(null);
ValueNotifier<(double, double)?> onFirstPaint = ValueNotifier(null);
ValueNotifier<List<int>?> onAdditionalFrames = ValueNotifier(null);
double get domContentLoaded;
double get loadEntrypoint;
double get initializeEngine;
double get appRunnerRunApp;
double? get firstFrame;
double? get firstPaint;
double? get firstContentfulPaint;
List<int>? get additionalFrames;
Map<String, dynamic> get startupTiming;
}
| samples/web/_packages/web_startup_analyzer/lib/src/web_startup_analyzer_base.dart/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/lib/src/web_startup_analyzer_base.dart",
"repo_id": "samples",
"token_count": 250
} | 1,356 |
// 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:convert';
import 'data.dart';
import 'util.dart' as util;
String _escapeAttribute(String s) =>
const HtmlEscape(HtmlEscapeMode.attribute).convert(s);
String _escapeElement(String s) =>
const HtmlEscape(HtmlEscapeMode.element).convert(s);
String description(Sample sample) => '''
<!DOCTYPE html>
<html lang="en">
$_descriptionHeader
${_descriptionPage(sample)}
$_footer
</html>
''';
String index(List<Sample> samples) => '''
<!DOCTYPE html>
<html lang="en">
$_indexHeader
${_indexBody(samples)}
$_footer
</html>
''';
const String _indexHeader = '''
<head>
<meta charset="utf-8">
<title>Flutter samples</title>
<link href="styles.css" rel="stylesheet" media="screen">
<link href="https://fonts.googleapis.com/css?family=Google+Sans|Google+Sans+Display|Roboto:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="packages/mdc_web/material-components-web.min.js"></script>
<script defer src="main.dart.js"></script>
$_googleAnalytics
</head>
''';
const String _descriptionHeader = '''
<head>
<meta charset="utf-8">
<title>Flutter samples</title>
<link href="styles.css" rel="stylesheet" media="screen">
<link href="https://fonts.googleapis.com/css?family=Google+Sans|Google+Sans+Display|Roboto:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="packages/mdc_web/material-components-web.min.js"></script>
<script src="https://kit.fontawesome.com/16cc04762e.js"></script>
<script defer src="description.dart.js"></script>
$_googleAnalytics
</head>
''';
const String _navbar = '''
<div class="navbar">
<a class="leading" href="./">
<img src="images/logos/logo_lockup_flutter_horizontal_wht_96.png" />
<span class="title">Samples</span>
</a>
<div class="nav-items">
<a href="https://flutter.dev/">Flutter Home</a>
<a href="https://api.flutter.dev/">API Docs</a>
</div>
</div>
''';
String _footer = '''
<div class="footer">
<span>© Flutter ${DateTime.now().toUtc().year}</span>
</div>
''';
String _indexBody(List<Sample> samples) => '''
<body>
<div class="content">
${util.indent(_navbar, 4)}
<div class="container">
<div class="index-header">
<h1>All Samples</h1>
<p>A curated list of Flutter samples and apps</p>
</div>
<div class="search-container">
<div id="search-bar" class="mdc-text-field mdc-text-field--with-leading-icon mdc-text-field--with-trailing-icon">
<i class="material-icons mdc-text-field__icon">search</i>
<i id="clear-button" class="material-icons mdc-text-field__icon" role="button" tabindex="0">clear</i>
<input class="mdc-text-field__input" id="text-field-hero-input">
<div class="mdc-line-ripple"></div>
<label for="text-field-hero-input" class="mdc-floating-label">Search</label>
</div>
</div>
<div class="filter-menu">
<div class="filter-buttons">
<div class="mdc-chip-set mdc-chip-set--choice" role="grid">
<div class="mdc-chip mdc-chip--selected" role="row">
<div class="mdc-chip__ripple"></div>
<span role="gridcell">
<span role="button" tabindex="0" class="mdc-chip__text">All</span>
</span>
</div>
<div class="mdc-chip" role="row">
<div class="mdc-chip__ripple"></div>
<span role="gridcell">
<span role="button" tabindex="-1" class="mdc-chip__text">Sample</span>
</span>
</div>
<div class="mdc-chip" role="row">
<div class="mdc-chip__ripple"></div>
<span role="gridcell">
<span role="button" tabindex="-1" class="mdc-chip__text">Web Demos</span>
</span>
</div>
</div>
</div>
<div class="filter-end"></div>
</div>
<div class="grid">
${util.indent(_indexCards(samples), 6)}
</div>
</div>
</div>
</body>
''';
String _backgroundImage(String url) =>
_escapeAttribute('background-image: url(\'$url\');');
String _indexCards(List<Sample> samples) => samples.map(_indexCard).join();
String _indexCard(Sample sample) => '''
<div class="mdc-card demo-card mdc-elevation--z0" search-attrs="${_escapeAttribute(sample.searchAttributes)}">
<div class="mdc-card__primary-action demo-card__primary-action" tabindex="0" href="${sample.filename}.html">
<div class="mdc-card__media mdc-card__media--16-9 demo-card__media" style="${_backgroundImage(sample.thumbnail)}"></div>
<div class="demo-card__label type-label">${_escapeElement(sample.type)}</div>
<div class="demo-card__primary">
<h2 class="demo-card__title mdc-typography mdc-typography--headline6">${_escapeElement(sample.name)}</h2>
</div>
<div class="demo-card__secondary mdc-typography mdc-typography--body2">${sample.shortDescription}</div>
</div>
</div>
''';
String _descriptionPage(Sample sample) => '''
<body>
<div class="content">
${util.indent(_navbar, 4)}
<div class="container">
<div class="description-title-row">
<h1>${sample.name}</h1>
<div class="type-label type-label-bordered">${sample.type}</div>
</div>
<p>By ${sample.author}</p>
<div class="toolbar">
<div class="buttons">
${util.indent(_descriptionButtons(sample), 6)}
</div>
<div class="tags-container">
<div class="tags-label">
<i class="material-icons">local_offer</i>
<span>Tags</span>
</div>
<div class="tags">
${util.indent(_tags(sample), 8)}
</div>
</div>
</div>
<div class="slider-container">
<div class="slider-content">
${util.indent(_descriptionScreenshots(sample), 4)}
</div>
</div>
<div class="description">
${util.indent(_descriptionText(sample), 4)}
</div>
</div>
</div>
</body>
''';
String _descriptionButtons(Sample sample) {
var buf = StringBuffer();
var sampleLink = sample.web;
if (sampleLink != null && sampleLink.isNotEmpty) {
buf.write(
'''<button class="mdc-button mdc-button--outlined" onclick="window.location.href = '$sampleLink';"><span class="mdc-button__ripple"></span> Launch App</button>''');
}
if (sample.type == 'app' ||
sample.type == 'sample' ||
sample.type == 'demo') {
buf.write(
'''<button class="mdc-button mdc-button--outlined" onclick="window.location.href = '${sample.source}';">
<div class="mdc-button__ripple"></div>
<i class="material-icons mdc-button__icon" aria-hidden="true">code</i>
<span class="mdc-button__label">Source Code</span>
</button>''');
}
return buf.toString();
}
String _tags(Sample sample) {
var buf = StringBuffer();
for (final tag in sample.tags) {
buf.write('<a href="./#?search=tag%3A$tag">$tag</a>\n');
}
return buf.toString();
}
String _descriptionScreenshots(Sample sample) {
var buf = StringBuffer();
for (final screenshot in sample.screenshots) {
buf.write(
'''<div class="slider-single"><img class="slider-single-image" src="${screenshot.url}" alt="${screenshot.alt}" /></div>\n''');
}
return buf.toString();
}
String _descriptionText(Sample sample) {
return '<p>${sample.description}</p>';
}
const String _googleAnalytics = """
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-67589403-8"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-67589403-8');
</script>""";
| samples/web/samples_index/lib/src/templates.dart/0 | {
"file_path": "samples/web/samples_index/lib/src/templates.dart",
"repo_id": "samples",
"token_count": 3357
} | 1,357 |
# web_embedding
This directory contains examples of how to embed Flutter in web apps (without iframes):
* **element_embedding_demo**: Modifies the index.html of a flutter app so it is
launched in a custom `hostElement`. This is the most basic embedding example.
* **ng-flutter**: A simple Angular app (and component) that replicates the above
example, but in an Angular style.
Check the `README.md` of each example for more details on how to run it, and the
"Points of Interest" it may contain.
## Community Contributions
Members of the community have graciously ported and contributed the following examples
of Flutter Web embedding into other web frameworks:
| Author | Host Framework | Code |
|--------|----------------|------|
| [@p-mazhnik][] | **React JS** | [p-mazhnik/flutter-embedding cra-flutter][] |
| [@p-mazhnik][] | **React Native** | [p-mazhnik/flutter-embedding expo-flutter][] |
_(All contributions are welcome! Please, [create an issue][] or open a PR to let us know
how you've embedded a Flutter Web app with your favorite web framework_
(Vue? Svelte? Ember? Aurelia? jQuery? MooTools? Prototype?), _so it can be added to the table above!)_
[@p-mazhnik]: https://github.com/p-mazhnik
[p-mazhnik/flutter-embedding cra-flutter]: https://github.com/p-mazhnik/flutter-embedding/tree/main/cra-flutter
[p-mazhnik/flutter-embedding expo-flutter]: https://github.com/p-mazhnik/flutter-embedding/tree/main/expo-flutter
[create an issue]: https://github.com/flutter/samples/issues/new
| samples/web_embedding/README.md/0 | {
"file_path": "samples/web_embedding/README.md",
"repo_id": "samples",
"token_count": 490
} | 1,358 |
import 'package:flutter/material.dart';
class CounterDemo extends StatefulWidget {
final ValueNotifier<int> counter;
const CounterDemo({
super.key,
required this.counter,
});
@override
State<CounterDemo> createState() => _CounterDemoState();
}
class _CounterDemoState extends State<CounterDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Counter'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
ValueListenableBuilder(
valueListenable: widget.counter,
builder: (context, value, child) => Text(
'$value',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
widget.counter.value++;
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
| samples/web_embedding/ng-flutter/flutter/lib/pages/counter.dart/0 | {
"file_path": "samples/web_embedding/ng-flutter/flutter/lib/pages/counter.dart",
"repo_id": "samples",
"token_count": 574
} | 1,359 |
import { ChangeDetectorRef, Component } from '@angular/core';
import { NgFlutterComponent } from './ng-flutter/ng-flutter.component';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { MatSidenavModule } from '@angular/material/sidenav';
import { CommonModule } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatCardModule } from '@angular/material/card';
import { MatSliderModule } from '@angular/material/slider';
import { MatButtonModule } from '@angular/material/button';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
@Component({
standalone: true,
selector: 'app-root',
template: `
<mat-toolbar color="primary">
<button
aria-label="Toggle sidenav"
mat-icon-button
(click)="drawer.toggle()">
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
<span>Angular 🤝 Flutter</span>
<span class="toolbar-spacer"></span>
<mat-icon aria-hidden="true">flutter_dash</mat-icon>
</mat-toolbar>
<mat-sidenav-container [hasBackdrop]=false class="sidenav-container">
<mat-sidenav #drawer mode="side" [opened]=false class="sidenav">
<mat-nav-list autosize>
<section>
<h2>Effects</h2>
<div class="button-list">
<button class="mb-control" mat-stroked-button color="primary"
(click)="container.classList.toggle('fx-shadow')">Shadow</button>
<button class="mb-control" mat-stroked-button color="primary"
(click)="container.classList.toggle('fx-mirror')">Mirror</button>
<button class="mb-control" mat-stroked-button color="primary"
(click)="container.classList.toggle('fx-resize')">Resize</button>
<button class="mb-control" mat-stroked-button color="primary"
(click)="container.classList.toggle('fx-spin')">Spin</button>
</div>
</section>
<section>
<h2>JS Interop</h2>
<mat-form-field appearance="outline">
<mat-label>Screen</mat-label>
<mat-select
(valueChange)="this.flutterState?.setScreen($event)"
[value]="this.flutterState?.getScreen()">
<mat-option value="counter">Counter</mat-option>
<mat-option value="text">TextField</mat-option>
<mat-option value="dash">Custom App</mat-option>
</mat-select>
</mat-form-field>
@if (this.flutterState?.getScreen() === 'counter') {
<mat-form-field appearance="outline">
<mat-label>Clicks</mat-label>
<input type="number" matInput (input)="onCounterSet($event)" [value]="this.flutterState?.getClicks()" />
</mat-form-field>
} @else {
<mat-form-field appearance="outline">
<mat-label>Text</mat-label>
<input type="text" matInput (input)="onTextSet($event)" [value]="this.flutterState?.getText()" />
@if (this.flutterState?.getText()) {
<button matSuffix mat-icon-button aria-label="Clear" (click)="this.flutterState?.setText('')">
<mat-icon>close</mat-icon>
</button>
}
</mat-form-field>
}
</section>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content class="sidenav-content">
<div class="flutter-app" #container>
<ng-flutter
src="flutter/main.dart.js"
assetBase="/flutter/"
(appLoaded)="onFlutterAppLoaded($event)"></ng-flutter>
</div>
</mat-sidenav-content>
</mat-sidenav-container>
`,
styles: [`
:host{
display: flex;
height: 100%;
flex-direction: column;
}
.toolbar-spacer {
flex: 1 1 auto;
}
.sidenav-container {
flex: 1;
}
.sidenav {
width: 300px;
padding: 10px;
}
.button-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-bottom: 20px;
}
.button-list button {
min-width: 130px;
}
.sidenav-content {
display: flex;
justify-content: center;
align-items: center;
}
.flutter-app {
border: 1px solid #eee;
border-radius: 5px;
height: 480px;
width: 320px;
transition: all 150ms ease-in-out;
overflow: hidden;
}
`],
imports: [
NgFlutterComponent,
MatToolbarModule,
MatSidenavModule,
MatSidenavModule,
MatIconModule,
CommonModule,
MatListModule,
MatCardModule,
MatSliderModule,
MatButtonModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
],
})
export class AppComponent {
title = 'ng-flutter';
flutterState?: any;
constructor(private changeDetectorRef: ChangeDetectorRef, private breakpointObserver: BreakpointObserver) { }
onFlutterAppLoaded(state: any) {
this.flutterState = state;
this.flutterState.onClicksChanged(() => { this.onCounterChanged() });
this.flutterState.onTextChanged(() => { this.onTextChanged() });
}
onCounterSet(event: Event) {
let clicks = parseInt((event.target as HTMLInputElement).value, 10) || 0;
this.flutterState.setClicks(clicks);
}
onTextSet(event: Event) {
this.flutterState.setText((event.target as HTMLInputElement).value || '');
}
// I need to force a change detection here. When clicking on the "Decrement"
// button, everything works fine, but clicking on Flutter doesn't trigger a
// repaint (even though this method is called)
onCounterChanged() {
this.changeDetectorRef.detectChanges();
}
onTextChanged() {
this.changeDetectorRef.detectChanges();
}
}
| samples/web_embedding/ng-flutter/src/app/app.component.ts/0 | {
"file_path": "samples/web_embedding/ng-flutter/src/app/app.component.ts",
"repo_id": "samples",
"token_count": 2354
} | 1,360 |
targets:
$default:
sources:
include:
- examples/**
exclude:
- '**/.*/**'
- '**/android/**'
- '**/ios/**'
- '**/linux/**'
- '**/macos/**'
- '**/windows/**'
- '**/build/**'
- '**/node_modules/**'
- '**/*.jar'
- '**/codelab_rebuild.yaml'
builders:
code_excerpter|code_excerpter:
enabled: true
| website/build.excerpt.yaml/0 | {
"file_path": "website/build.excerpt.yaml",
"repo_id": "website",
"token_count": 238
} | 1,361 |
name: staggered_pic_selection
publish_to: none
description: A more complex staggered animation example.
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/pic1.jpg
- images/pic2.jpg
- images/pic3.jpg
- images/pic4.jpg
- images/pic5.jpg
- images/pic6.jpg
- images/pic7.jpg
- images/pic8.jpg
- images/pic9.jpg
- images/pic10.jpg
- images/pic11.jpg
- images/pic12.jpg
- images/pic13.jpg
- images/pic14.jpg
- images/pic15.jpg
- images/pic16.jpg
- images/pic17.jpg
- images/pic18.jpg
- images/pic19.jpg
- images/pic20.jpg
- images/pic21.jpg
- images/pic22.jpg
- images/pic23.jpg
- images/pic24.jpg
- images/pic25.jpg
- images/pic26.jpg
- images/pic27.jpg
- images/pic28.jpg
- images/pic29.jpg
- images/pic30.jpg
| website/examples/_animation/staggered_pic_selection/pubspec.yaml/0 | {
"file_path": "website/examples/_animation/staggered_pic_selection/pubspec.yaml",
"repo_id": "website",
"token_count": 448
} | 1,362 |
# 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:
errors:
# Ignored since ignore_for_files can't be hidden in diff excerpts yet
missing_required_argument: ignore
| website/examples/animation/implicit/analysis_options.yaml/0 | {
"file_path": "website/examples/animation/implicit/analysis_options.yaml",
"repo_id": "website",
"token_count": 96
} | 1,363 |
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: PhysicsCardDragDemo()));
}
class PhysicsCardDragDemo extends StatelessWidget {
const PhysicsCardDragDemo({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: const DraggableCard(
child: FlutterLogo(
size: 128,
),
),
);
}
}
class DraggableCard extends StatefulWidget {
const DraggableCard({required this.child, super.key});
final Widget child;
@override
State<DraggableCard> createState() => _DraggableCardState();
}
// #docregion alignment
class _DraggableCardState extends State<DraggableCard>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
// #enddocregion alignment
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 1));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
// #docregion build
@override
Widget build(BuildContext context) {
return Align(
child: Card(
child: widget.child,
),
);
}
// #enddocregion build
}
| website/examples/cookbook/animation/physics_simulation/lib/step1.dart/0 | {
"file_path": "website/examples/cookbook/animation/physics_simulation/lib/step1.dart",
"repo_id": "website",
"token_count": 455
} | 1,364 |
// ignore_for_file: unused_element, prefer_const_literals_to_create_immutables
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: AnimatedOpacity(
duration: transitionDuration,
opacity: isDownloading || isFetching ? 0.0 : 1.0,
curve: Curves.ease,
child: Text(
isDownloaded ? 'OPEN' : 'GET',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
fontWeight: FontWeight.bold,
color: CupertinoColors.activeBlue,
),
),
),
),
);
}
}
@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,
);
},
),
);
}
}
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
// #docregion TapCallbacks
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.downloadProgress = 0,
required this.onDownload,
required this.onCancel,
required this.onOpen,
this.transitionDuration = const Duration(milliseconds: 500),
});
final DownloadStatus status;
final double downloadProgress;
final VoidCallback onDownload;
final VoidCallback onCancel;
final VoidCallback onOpen;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
void _onPressed() {
switch (status) {
case DownloadStatus.notDownloaded:
onDownload();
case DownloadStatus.fetchingDownload:
// do nothing.
break;
case DownloadStatus.downloading:
onCancel();
case DownloadStatus.downloaded:
onOpen();
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _onPressed,
child: const Stack(
children: [
/* ButtonShapeWidget and progress indicator */
],
),
);
}
}
// #enddocregion TapCallbacks
| website/examples/cookbook/effects/download_button/lib/button_taps.dart/0 | {
"file_path": "website/examples/cookbook/effects/download_button/lib/button_taps.dart",
"repo_id": "website",
"token_count": 1602
} | 1,365 |
import 'package:flutter/material.dart';
class SetupFlow extends StatefulWidget {
const SetupFlow({
super.key,
required this.setupPageRoute,
});
final String setupPageRoute;
@override
State<SetupFlow> createState() => SetupFlowState();
}
class SetupFlowState extends State<SetupFlow> {
// #docregion SetupFlow2
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildFlowAppBar(),
body: const SizedBox(),
);
}
PreferredSizeWidget _buildFlowAppBar() {
return AppBar(
title: const Text('Bulb Setup'),
);
}
// #enddocregion SetupFlow2
}
| website/examples/cookbook/effects/nested_nav/lib/setupflow2.dart/0 | {
"file_path": "website/examples/cookbook/effects/nested_nav/lib/setupflow2.dart",
"repo_id": "website",
"token_count": 219
} | 1,366 |
import 'package:flutter/material.dart';
@immutable
class FilterSelector extends StatefulWidget {
const FilterSelector({
super.key,
required this.filters,
required this.onFilterChanged,
this.padding = const EdgeInsets.symmetric(vertical: 24),
});
final List<Color> filters;
final void Function(Color selectedColor) onFilterChanged;
final EdgeInsets padding;
@override
State<FilterSelector> createState() => _FilterSelectorState();
}
class _FilterSelectorState extends State<FilterSelector> {
static const _filtersPerScreen = 5;
static const _viewportFractionPerItem = 1.0 / _filtersPerScreen;
late final PageController _controller;
Color itemColor(int index) => widget.filters[index % widget.filters.length];
@override
void initState() {
super.initState();
_controller = PageController(
viewportFraction: _viewportFractionPerItem,
);
_controller.addListener(_onPageChanged);
}
void _onPageChanged() {
final page = (_controller.page ?? 0).round();
widget.onFilterChanged(widget.filters[page]);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
// #docregion BuildCarousel
Widget _buildCarousel(double itemSize) {
return Container(
height: itemSize,
margin: widget.padding,
child: PageView.builder(
controller: _controller,
itemCount: widget.filters.length,
itemBuilder: (context, index) {
return Center(
child: AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return FilterItem(
color: itemColor(index),
onFilterSelected: () => {},
);
},
),
);
},
),
);
}
// #enddocregion BuildCarousel
@override
Widget build(BuildContext context) {
_buildCarousel(5); // Makes sure _buildCarousel is used
return Container();
}
}
@immutable
class FilterItem extends StatelessWidget {
const FilterItem({
super.key,
required this.color,
this.onFilterSelected,
});
final Color color;
final VoidCallback? onFilterSelected;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onFilterSelected,
child: AspectRatio(
aspectRatio: 1.0,
child: Padding(
padding: const EdgeInsets.all(8),
child: ClipOval(
child: Image.network(
'https://docs.flutter.dev/cookbook/img-files'
'/effects/instagram-buttons/millennial-texture.jpg',
color: color.withOpacity(0.5),
colorBlendMode: BlendMode.hardLight,
),
),
),
),
);
}
}
| website/examples/cookbook/effects/photo_filter_carousel/lib/excerpt6.dart/0 | {
"file_path": "website/examples/cookbook/effects/photo_filter_carousel/lib/excerpt6.dart",
"repo_id": "website",
"token_count": 1140
} | 1,367 |
// ignore_for_file: unused_field
import 'package:flutter/material.dart';
class Menu extends StatefulWidget {
const Menu({super.key});
@override
State<Menu> createState() => _MenuState();
}
// #docregion step3
class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
final List<Interval> _itemSlideIntervals = [];
late Interval _buttonInterval;
@override
void initState() {
super.initState();
_createAnimationIntervals();
_staggeredController = AnimationController(
vsync: this,
duration: _animationDuration,
);
}
void _createAnimationIntervals() {
for (var i = 0; i < _menuTitles.length; ++i) {
final startTime = _initialDelayTime + (_staggerTime * i);
final endTime = startTime + _itemSlideTime;
_itemSlideIntervals.add(
Interval(
startTime.inMilliseconds / _animationDuration.inMilliseconds,
endTime.inMilliseconds / _animationDuration.inMilliseconds,
),
);
}
final buttonStartTime =
Duration(milliseconds: (_menuTitles.length * 50)) + _buttonDelayTime;
final buttonEndTime = buttonStartTime + _buttonTime;
_buttonInterval = Interval(
buttonStartTime.inMilliseconds / _animationDuration.inMilliseconds,
buttonEndTime.inMilliseconds / _animationDuration.inMilliseconds,
);
} //code-excerpt-close-bracket
// #enddocregion step3
@override
Widget build(BuildContext context) {
return Container();
}
late AnimationController _staggeredController;
static const _initialDelayTime = Duration(milliseconds: 50);
static const _itemSlideTime = Duration(milliseconds: 250);
static const _staggerTime = Duration(milliseconds: 50);
static const _buttonDelayTime = Duration(milliseconds: 150);
static const _buttonTime = Duration(milliseconds: 500);
final _animationDuration = _initialDelayTime +
(_staggerTime * _menuTitles.length) +
_buttonDelayTime +
_buttonTime;
static const _menuTitles = [
'Declarative style',
'Premade widgets',
'Stateful hot reload',
'Native performance',
'Great community',
];
}
| website/examples/cookbook/effects/staggered_menu_animation/lib/step3.dart/0 | {
"file_path": "website/examples/cookbook/effects/staggered_menu_animation/lib/step3.dart",
"repo_id": "website",
"token_count": 756
} | 1,368 |
name: form
description: Use Form widget to perform form validation.
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/forms/validation/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/forms/validation/pubspec.yaml",
"repo_id": "website",
"token_count": 89
} | 1,369 |
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
// MyApp is a StatefulWidget. This allows updating the state of the
// widget when an item is removed.
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
MyAppState createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
// #docregion Items
final items = List<String>.generate(20, (i) => 'Item ${i + 1}');
// #enddocregion Items
@override
Widget build(BuildContext context) {
const title = 'Dismissing Items';
return MaterialApp(
title: title,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: ListView.builder(
itemCount: items.length,
// #docregion Dismissible
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
// Each Dismissible must contain a Key. Keys allow Flutter to
// uniquely identify widgets.
key: Key(item),
// Provide a function that tells the app
// what to do after an item has been swiped away.
onDismissed: (direction) {
// Remove the item from the data source.
setState(() {
items.removeAt(index);
});
// Then show a snackbar.
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('$item dismissed')));
},
// Show a red background as the item is swiped away.
background: Container(color: Colors.red),
child: ListTile(
title: Text(item),
),
);
},
// #enddocregion Dismissible
),
),
);
}
}
| website/examples/cookbook/gestures/dismissible/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/gestures/dismissible/lib/main.dart",
"repo_id": "website",
"token_count": 917
} | 1,370 |
import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Fade in images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: Stack(
children: <Widget>[
const Center(child: CircularProgressIndicator()),
Center(
// #docregion MemoryNetwork
child: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/250?image=9',
),
// #enddocregion MemoryNetwork
),
],
),
),
);
}
}
| website/examples/cookbook/images/fading_in_images/lib/memory_main.dart/0 | {
"file_path": "website/examples/cookbook/images/fading_in_images/lib/memory_main.dart",
"repo_id": "website",
"token_count": 418
} | 1,371 |
name: grid_lists
description: A new Flutter project.
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/grid_lists/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/lists/grid_lists/pubspec.yaml",
"repo_id": "website",
"token_count": 138
} | 1,372 |
name: error_reporting
description: Error reporting example using sentry.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
sentry_flutter: ^7.16.0
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/cookbook/maintenance/error_reporting/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/maintenance/error_reporting/pubspec.yaml",
"repo_id": "website",
"token_count": 127
} | 1,373 |
import 'package:flutter/material.dart';
class FirstRoute extends StatelessWidget {
const FirstRoute({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('First Route'),
),
body: Center(
child: ElevatedButton(
child: const Text('Open route'),
// #docregion FirstRouteOnPressed
// Within the `FirstRoute` widget
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()),
);
}
// #enddocregion FirstRouteOnPressed
),
),
);
}
}
class SecondRoute extends StatelessWidget {
const SecondRoute({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second Route'),
),
body: Center(
child: ElevatedButton(
// #docregion SecondRouteOnPressed
// Within the SecondRoute widget
onPressed: () {
Navigator.pop(context);
}
// #enddocregion SecondRouteOnPressed
,
child: const Text('Go back!'),
),
),
);
}
}
| website/examples/cookbook/navigation/navigation_basics/lib/main_step2.dart/0 | {
"file_path": "website/examples/cookbook/navigation/navigation_basics/lib/main_step2.dart",
"repo_id": "website",
"token_count": 605
} | 1,374 |
import 'dart:async';
import 'package:http/http.dart' as http;
// #docregion fetchPhotos
Future<http.Response> fetchPhotos(http.Client client) async {
return client.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
}
// #enddocregion fetchPhotos
| website/examples/cookbook/networking/background_parsing/lib/main_step2.dart/0 | {
"file_path": "website/examples/cookbook/networking/background_parsing/lib/main_step2.dart",
"repo_id": "website",
"token_count": 87
} | 1,375 |
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
// #docregion Http
import 'package:http/http.dart' as http;
// #enddocregion Http
// #docregion fetchAlbum
Future<Album> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
// #enddocregion fetchAlbum
// #docregion updateAlbum
Future<Album> updateAlbum(String title) async {
final response = await http.put(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
}
// #enddocregion updateAlbum
// #docregion Album
class Album {
final int id;
final String title;
const Album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
'id': int id,
'title': String title,
} =>
Album(
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}
// #enddocregion Album
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final TextEditingController _controller = TextEditingController();
late Future<Album> _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Update Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(
title: const Text('Update Data Example'),
),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8),
child: FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(snapshot.data!.title),
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter Title',
),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
child: const Text('Update Data'),
),
],
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}
| website/examples/cookbook/networking/update_data/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/networking/update_data/lib/main.dart",
"repo_id": "website",
"token_count": 1850
} | 1,376 |
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() => runApp(const VideoPlayerApp());
class VideoPlayerApp extends StatelessWidget {
const VideoPlayerApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Video Player Demo',
home: VideoPlayerScreen(),
);
}
}
class VideoPlayerScreen extends StatefulWidget {
const VideoPlayerScreen({super.key});
@override
State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
late VideoPlayerController _controller;
late Future<void> _initializeVideoPlayerFuture;
@override
void initState() {
super.initState();
// Create and store the VideoPlayerController. The VideoPlayerController
// offers several different constructors to play videos from assets, files,
// or the internet.
_controller = VideoPlayerController.networkUrl(
Uri.parse(
'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',
),
);
// Initialize the controller and store the Future for later use.
_initializeVideoPlayerFuture = _controller.initialize();
// Use the controller to loop the video.
_controller.setLooping(true);
}
@override
void dispose() {
// Ensure disposing of the VideoPlayerController to free up resources.
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Butterfly Video'),
),
// #docregion FutureBuilder
// Use a FutureBuilder to display a loading spinner while waiting for the
// VideoPlayerController to finish initializing.
body: FutureBuilder(
future: _initializeVideoPlayerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
// If the VideoPlayerController has finished initialization, use
// the data it provides to limit the aspect ratio of the video.
return AspectRatio(
aspectRatio: _controller.value.aspectRatio,
// Use the VideoPlayer widget to display the video.
child: VideoPlayer(_controller),
);
} else {
// If the VideoPlayerController is still initializing, show a
// loading spinner.
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
// #enddocregion FutureBuilder
// #docregion FAB
floatingActionButton: FloatingActionButton(
onPressed: () {
// Wrap the play or pause in a call to `setState`. This ensures the
// correct icon is shown.
setState(() {
// If the video is playing, pause it.
if (_controller.value.isPlaying) {
_controller.pause();
} else {
// If the video is paused, play it.
_controller.play();
}
});
},
// Display the correct icon depending on the state of the player.
child: Icon(
_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
),
),
// #enddocregion FAB
);
}
}
| website/examples/cookbook/plugins/play_video/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/plugins/play_video/lib/main.dart",
"repo_id": "website",
"token_count": 1305
} | 1,377 |
name: counter_app
description: Flutter project for unit testing introduction.
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
test: ^1.24.9
dev_dependencies:
example_utils:
path: ../../../../example_utils
flutter:
uses-material-design: true
| website/examples/cookbook/testing/unit/counter_app/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/testing/unit/counter_app/pubspec.yaml",
"repo_id": "website",
"token_count": 134
} | 1,378 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// #docregion main
void main() {
testWidgets('MyWidget has a title and message', (tester) async {
await tester.pumpWidget(const MyWidget(title: 'T', message: 'M'));
final titleFinder = find.text('T');
final messageFinder = find.text('M');
// Use the `findsOneWidget` matcher provided by flutter_test to verify
// that the Text widgets appear exactly once in the widget tree.
expect(titleFinder, findsOneWidget);
expect(messageFinder, findsOneWidget);
});
}
// #enddocregion main
class MyWidget extends StatelessWidget {
const MyWidget({
super.key,
required this.title,
required this.message,
});
final String title;
final String message;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text(message),
),
),
);
}
}
| website/examples/cookbook/testing/widget/introduction/test/main_step6_test.dart/0 | {
"file_path": "website/examples/cookbook/testing/widget/introduction/test/main_step6_test.dart",
"repo_id": "website",
"token_count": 400
} | 1,379 |
// 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 'dart:convert';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Isolates demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Isolates demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
getPhotos();
},
child: Text('Fetch photos'),
),
),
),
);
}
}
// #docregion isolate-run
// Produces a list of 211,640 photo objects.
// (The JSON file is ~20MB.)
Future<List<Photo>> getPhotos() async {
final String jsonString = await rootBundle.loadString('assets/photos.json');
final List<Photo> photos = await Isolate.run<List<Photo>>(() {
final List<Object?> photoData = jsonDecode(jsonString) as List<Object?>;
return photoData.cast<Map<String, Object?>>().map(Photo.fromJson).toList();
});
return photos;
}
// #enddocregion isolate-run
class Photo {
final int albumId;
final int id;
final String title;
final String thumbnailUrl;
Photo({
required this.albumId,
required this.id,
required this.title,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> data) {
return Photo(
albumId: data['albumId'] as int,
id: data['id'] as int,
title: data['title'] as String,
thumbnailUrl: data['thumbnailUrl'] as String,
);
}
}
| website/examples/development/concurrency/isolates/lib/main.dart/0 | {
"file_path": "website/examples/development/concurrency/isolates/lib/main.dart",
"repo_id": "website",
"token_count": 686
} | 1,380 |
// #docregion DynamicLibrary
import 'dart:ffi'; // For FFI
import 'dart:io'; // For Platform.isX
final DynamicLibrary nativeAddLib = Platform.isAndroid
? DynamicLibrary.open('libnative_add.so')
: DynamicLibrary.process();
// #enddocregion DynamicLibrary
// #docregion NativeAdd
final int Function(int x, int y) nativeAdd = nativeAddLib
.lookup<NativeFunction<Int32 Function(Int32, Int32)>>('native_add')
.asFunction();
// #enddocregion NativeAdd
| website/examples/development/platform_integration/lib/c_interop.dart/0 | {
"file_path": "website/examples/development/platform_integration/lib/c_interop.dart",
"repo_id": "website",
"token_count": 150
} | 1,381 |
// ignore_for_file: avoid_print, prefer_const_declarations, prefer_const_constructors
// #docregion Build
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(onTap: () => print('tapped'));
}
}
// #enddocregion Build
// #docregion Enum
enum Color {
red,
green,
blue,
}
// #enddocregion Enum
// #docregion Class
class A<T> {
T? i;
}
// #enddocregion Class
// #docregion SampleTable
final sampleTable = [
Table(
children: const [
TableRow(
children: [Text('T1')],
)
],
),
Table(
children: const [
TableRow(
children: [Text('T2')],
)
],
),
Table(
children: const [
TableRow(
children: [Text('T3')],
)
],
),
Table(
children: const [
TableRow(
children: [Text('T4')],
)
],
),
];
// #enddocregion SampleTable
// #docregion Const
const foo = 1;
final bar = foo;
void onClick() {
print(foo);
print(bar);
}
// #enddocregion Const
| website/examples/development/tools/lib/hot-reload/before.dart/0 | {
"file_path": "website/examples/development/tools/lib/hot-reload/before.dart",
"repo_id": "website",
"token_count": 475
} | 1,382 |
import 'package:flutter/material.dart';
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
'Welcome!',
style: Theme.of(context).textTheme.displayMedium,
),
),
);
}
}
void main() => runApp(const SignUpApp());
class SignUpApp extends StatelessWidget {
const SignUpApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => const SignUpScreen(),
'/welcome': (context) => const WelcomeScreen(),
},
);
}
}
class SignUpScreen extends StatelessWidget {
const SignUpScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
body: const Center(
child: SizedBox(
width: 400,
child: Card(
child: SignUpForm(),
),
),
),
);
}
}
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _firstNameTextController = TextEditingController();
final _lastNameTextController = TextEditingController();
final _usernameTextController = TextEditingController();
double _formProgress = 0;
void _showWelcomeScreen() {
Navigator.of(context).pushNamed('/welcome');
}
void _updateFormProgress() {
var progress = 0.0;
final controllers = [
_firstNameTextController,
_lastNameTextController,
_usernameTextController
];
for (final controller in controllers) {
if (controller.value.text.isNotEmpty) {
progress += 1 / controllers.length;
}
}
setState(() {
_formProgress = progress;
});
}
@override
Widget build(BuildContext context) {
return Form(
onChanged: _updateFormProgress,
// #docregion UseAnimatedProgressIndicator
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedProgressIndicator(value: _formProgress), // NEW
Text('Sign up', style: Theme.of(context).textTheme.headlineMedium),
Padding(
// #enddocregion UseAnimatedProgressIndicator
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _firstNameTextController,
decoration: const InputDecoration(hintText: 'First name'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _lastNameTextController,
decoration: const InputDecoration(hintText: 'Last name'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _usernameTextController,
decoration: const InputDecoration(hintText: 'Username'),
),
),
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.white;
}),
backgroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.blue;
}),
),
onPressed:
_formProgress == 1 ? _showWelcomeScreen : null, // UPDATED
child: const Text('Sign up'),
),
],
),
);
}
}
// #docregion AnimatedProgressIndicator
class AnimatedProgressIndicator extends StatefulWidget {
final double value;
const AnimatedProgressIndicator({
super.key,
required this.value,
});
@override
State<AnimatedProgressIndicator> createState() {
return _AnimatedProgressIndicatorState();
}
}
class _AnimatedProgressIndicatorState extends State<AnimatedProgressIndicator>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Color?> _colorAnimation;
late Animation<double> _curveAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 1200),
vsync: this,
);
final colorTween = TweenSequence([
TweenSequenceItem(
tween: ColorTween(begin: Colors.red, end: Colors.orange),
weight: 1,
),
TweenSequenceItem(
tween: ColorTween(begin: Colors.orange, end: Colors.yellow),
weight: 1,
),
TweenSequenceItem(
tween: ColorTween(begin: Colors.yellow, end: Colors.green),
weight: 1,
),
]);
_colorAnimation = _controller.drive(colorTween);
_curveAnimation = _controller.drive(CurveTween(curve: Curves.easeIn));
}
@override
void didUpdateWidget(oldWidget) {
super.didUpdateWidget(oldWidget);
_controller.animateTo(widget.value);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) => LinearProgressIndicator(
value: _curveAnimation.value,
valueColor: _colorAnimation,
backgroundColor: _colorAnimation.value?.withOpacity(0.4),
),
);
}
}
// #enddocregion AnimatedProgressIndicator
| website/examples/get-started/codelab_web/lib/step3.dart/0 | {
"file_path": "website/examples/get-started/codelab_web/lib/step3.dart",
"repo_id": "website",
"token_count": 2326
} | 1,383 |
import 'package:flutter/widgets.dart';
class LifecycleWatcher extends StatefulWidget {
const LifecycleWatcher({super.key});
@override
State<LifecycleWatcher> createState() => _LifecycleWatcherState();
}
class _LifecycleWatcherState extends State<LifecycleWatcher>
with WidgetsBindingObserver {
AppLifecycleState? _lastLifecycleState;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
setState(() {
_lastLifecycleState = state;
});
}
@override
Widget build(BuildContext context) {
if (_lastLifecycleState == null) {
return const Text(
'This widget has not observed any lifecycle changes.',
textDirection: TextDirection.ltr,
);
}
return Text(
'The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
textDirection: TextDirection.ltr,
);
}
}
void main() {
runApp(const Center(child: LifecycleWatcher()));
}
| website/examples/get-started/flutter-for/android_devs/lib/lifecycle.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/lifecycle.dart",
"repo_id": "website",
"token_count": 426
} | 1,384 |
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return const Image(
image:
// #docregion AssetImage
AssetImage('images/a_dot_burr.jpeg')
// #enddocregion AssetImage
);
}
}
class ImageExample extends StatelessWidget {
const ImageExample({super.key});
// #docregion Imageasset
@override
Widget build(BuildContext context) {
return Image.asset('images/my_image.png');
}
// #enddocregion Imageasset
}
| website/examples/get-started/flutter-for/ios_devs/lib/images.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/images.dart",
"repo_id": "website",
"token_count": 219
} | 1,385 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(
child:
// #docregion row
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(CupertinoIcons.globe),
Text('Hello, world!'),
],
),
// #enddocregion row
),
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/row.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/row.dart",
"repo_id": "website",
"token_count": 340
} | 1,386 |
import 'package:flutter/material.dart';
// #docregion CreateState
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({
super.key,
required this.title,
});
final String title;
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
@override
Widget build(BuildContext context) {
return const Text('Hello World!');
}
}
// #enddocregion CreateState
// #docregion UseStatefulWidget
class MyStatelessWidget extends StatelessWidget {
// This widget is the root of your application.
const MyStatelessWidget({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyStatefulWidget(title: 'State Change Demo'),
);
}
}
// #enddocregion UseStatefulWidget
| website/examples/get-started/flutter-for/react_native_devs/lib/best_practices.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/best_practices.dart",
"repo_id": "website",
"token_count": 275
} | 1,387 |
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
/// This widget is the root of your application.
const SampleApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Sample App',
home: SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List<Widget> widgets = [];
@override
void initState() {
super.initState();
for (int i = 0; i < 100; i++) {
widgets.add(getRow(i));
}
}
Widget getRow(int index) {
return GestureDetector(
onTap: () {
setState(() {
widgets.add(getRow(widgets.length));
developer.log('Row $index');
});
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $index'),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample App')),
body: ListView.builder(
itemCount: widgets.length,
itemBuilder: (context, index) {
return getRow(index);
},
),
);
}
}
| website/examples/get-started/flutter-for/xamarin_devs/lib/listview_builder.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/xamarin_devs/lib/listview_builder.dart",
"repo_id": "website",
"token_count": 562
} | 1,388 |
The samples in this folder used to be under `src/_includes/code`. Despite that,
the sources were not being included anywhere. It is likely that the sources
appear in some pages none-the-less. What needs to be done is the following:
- Each app/sample needs to be fully reviewed (and potentially simplified).
- If the sources are in fact being used in site pages, then they need to be
integrated as proper code excerpts. See [Code excerpts][] for details.
- Each app/sample should be tested, at least with a smoke test.
[Code excerpts]: https://github.com/dart-lang/site-shared/blob/main/doc/code-excerpts.md
| website/examples/internationalization/README.md/0 | {
"file_path": "website/examples/internationalization/README.md",
"repo_id": "website",
"token_count": 161
} | 1,389 |
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart
// This is a library that looks up messages for specific locales by
// delegating to the appropriate library.
export 'messages_all_locales.dart' show initializeMessages;
| website/examples/internationalization/intl_example/lib/l10n/messages_all.dart/0 | {
"file_path": "website/examples/internationalization/intl_example/lib/l10n/messages_all.dart",
"repo_id": "website",
"token_count": 68
} | 1,390 |
// 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';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
title: const Text('Welcome to Flutter'),
),
body: const Center(
child: Text('Hello World'),
),
),
);
}
}
| website/examples/layout/base/lib/main_starter.dart/0 | {
"file_path": "website/examples/layout/base/lib/main_starter.dart",
"repo_id": "website",
"token_count": 237
} | 1,391 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
// #docregion TextAdd
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// #enddocregion TextAdd
const String appTitle = 'Flutter layout demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
),
// #docregion addWidget
// #docregion TextAdd
body: const SingleChildScrollView(
child: Column(
children: [
TitleSection(
name: 'Oeschinen Lake Campground',
location: 'Kandersteg, Switzerland',
),
ButtonSection(),
TextSection(
description:
'Lake Oeschinen lies at the foot of the Blüemlisalp in the '
'Bernese Alps. Situated 1,578 meters above sea level, it '
'is one of the larger Alpine Lakes. A gondola ride from '
'Kandersteg, followed by a half-hour walk through pastures '
'and pine forest, leads you to the lake, which warms to 20 '
'degrees Celsius in the summer. Activities enjoyed here '
'include rowing, and riding the summer toboggan run.',
),
],
),
),
// #enddocregion addWidget
),
);
}
}
// #enddocregion TextAdd
class TitleSection extends StatelessWidget {
const TitleSection({
super.key,
required this.name,
required this.location,
});
final String name;
final String location;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(32),
child: Row(
children: [
Expanded(
/*1*/
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
/*2*/
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
name,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Text(
location,
style: TextStyle(
color: Colors.grey[500],
),
),
],
),
),
/*3*/
Icon(
Icons.star,
color: Colors.red[500],
),
const Text('41'),
],
),
);
}
}
class ButtonSection extends StatelessWidget {
const ButtonSection({super.key});
@override
Widget build(BuildContext context) {
final Color color = Theme.of(context).primaryColor;
return SizedBox(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ButtonWithText(
color: color,
icon: Icons.call,
label: 'CALL',
),
ButtonWithText(
color: color,
icon: Icons.near_me,
label: 'ROUTE',
),
ButtonWithText(
color: color,
icon: Icons.share,
label: 'SHARE',
),
],
),
);
}
}
class ButtonWithText extends StatelessWidget {
const ButtonWithText({
super.key,
required this.color,
required this.icon,
required this.label,
});
final Color color;
final IconData icon;
final String label;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color),
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: color,
),
),
),
],
);
}
}
// #docregion TextSection
class TextSection extends StatelessWidget {
const TextSection({
super.key,
required this.description,
});
final String description;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(32),
child: Text(
description,
softWrap: true,
),
);
}
}
// #enddocregion TextSection
| website/examples/layout/lakes/step4/lib/main.dart/0 | {
"file_path": "website/examples/layout/lakes/step4/lib/main.dart",
"repo_id": "website",
"token_count": 2297
} | 1,392 |
// #docregion Main
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('My Home Page'),
),
body: Center(
child: Builder(
builder: (context) {
return Column(
children: [
const Text('Hello World'),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
print('Click!');
},
child: const Text('A button'),
),
],
);
},
),
),
),
);
}
}
// #enddocregion Main
void containerExample(BuildContext context) {
// #docregion Container
Container(
color: Theme.of(context).secondaryHeaderColor,
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.titleLarge,
),
);
// #enddocregion Container
// #docregion Container2
Container(
color: Colors.blue,
child: Row(
children: [
Image.network('https://www.example.com/1.png'),
const Text('A'),
],
),
);
// #enddocregion Container2
}
class OneColumnLayout extends StatelessWidget {
const OneColumnLayout({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
class TwoColumnLayout extends StatelessWidget {
const TwoColumnLayout({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
class LayoutBuilderExample extends StatelessWidget {
const LayoutBuilderExample({super.key});
@override
// #docregion LayoutBuilder
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 600) {
return const OneColumnLayout();
} else {
return const TwoColumnLayout();
}
},
);
}
// #enddocregion LayoutBuilder
}
Future<void> exampleChannels() async {
// #docregion MethodChannel
// Dart side
const channel = MethodChannel('foo');
final greeting = await channel.invokeMethod('bar', 'world') as String;
print(greeting);
// #enddocregion MethodChannel
}
| website/examples/resources/architectural_overview/lib/main.dart/0 | {
"file_path": "website/examples/resources/architectural_overview/lib/main.dart",
"repo_id": "website",
"token_count": 1041
} | 1,393 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
import 'package:state_mgmt/main.dart';
import 'package:state_mgmt/src/provider.dart';
void main() {
testWidgets('smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(
ChangeNotifierProvider(
create: (context) => CartModel(),
child: const MyApp(),
),
);
await _visitPage(tester, '/setstate');
await _visitPage(tester, '/provider');
await _visitPage(tester, '/callbacks');
await _visitPage(tester, '/perf');
expect(find.byType(TextButton).evaluate().length, 4,
reason: 'Smoke test was expecting a different number of pages to test. '
'Please make sure you visit all the pages above.');
});
}
/// Just opens a page by tapping the button with [name]. Then immediately
/// returns back. This just tests that everything builds correctly without
/// crashing at runtime.
Future<void> _visitPage(WidgetTester tester, String name) async {
await tester.tap(find.text(name));
await tester.pumpAndSettle();
await tester.pageBack();
await tester.pumpAndSettle();
}
| website/examples/state_mgmt/simple/test/widget_test.dart/0 | {
"file_path": "website/examples/state_mgmt/simple/test/widget_test.dart",
"repo_id": "website",
"token_count": 428
} | 1,394 |
name: code_debugging
description: Examples to illustrate debugging your Flutter code.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
example_utils:
path: ../../example_utils
integration_test:
sdk: flutter
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/testing/code_debugging/pubspec.yaml/0 | {
"file_path": "website/examples/testing/code_debugging/pubspec.yaml",
"repo_id": "website",
"token_count": 130
} | 1,395 |
// ignore_for_file: directives_ordering
import './my_app.dart';
// #docregion Main
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
FlutterError.onError = (details) {
FlutterError.presentError(details);
if (kReleaseMode) exit(1);
};
runApp(const MyApp());
}
// rest of `flutter create` code...
// #enddocregion Main
| website/examples/testing/errors/lib/quit_immediate.dart/0 | {
"file_path": "website/examples/testing/errors/lib/quit_immediate.dart",
"repo_id": "website",
"token_count": 144
} | 1,396 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
static const String _title = 'Focus Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[MyCustomWidget(), MyCustomWidget()],
),
),
);
}
}
class MyCustomWidget extends StatefulWidget {
const MyCustomWidget({super.key});
@override
State<MyCustomWidget> createState() => _MyCustomWidgetState();
}
class _MyCustomWidgetState extends State<MyCustomWidget> {
Color _color = Colors.white;
String _label = 'Unfocused';
@override
Widget build(BuildContext context) {
return Focus(
onFocusChange: (focused) {
setState(() {
_color = focused ? Colors.black26 : Colors.white;
_label = focused ? 'Focused' : 'Unfocused';
});
},
child: Center(
child: Container(
width: 300,
height: 50,
alignment: Alignment.center,
color: _color,
child: Text(_label),
),
),
);
}
}
| website/examples/ui/advanced/focus/lib/custom_control_example.dart/0 | {
"file_path": "website/examples/ui/advanced/focus/lib/custom_control_example.dart",
"repo_id": "website",
"token_count": 534
} | 1,397 |
import 'package:flutter/material.dart';
import '../global/device_type.dart';
import '../widgets/scroll_view_with_scrollbars.dart';
class AdaptiveDataTablePage extends StatelessWidget {
AdaptiveDataTablePage({super.key});
final List<int> items = List.generate(100, (index) => index);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
bool showCol2 = constraints.maxWidth > 300;
bool showCol3 = constraints.maxWidth > 600;
bool showCol4 = constraints.maxWidth > 900;
return Column(children: [
Row(
children: [
const _TableHeader('Column 1'),
if (showCol2) const _TableHeader('Column 2'),
if (showCol3) const _TableHeader('Column 3'),
if (showCol4) const _TableHeader('Column 4'),
],
),
Expanded(
child: ScrollViewWithScrollbars(
child: Column(
children: items.map((i) {
return Container(
color: i % 2 == 0 ? Colors.grey.shade300 : null,
child: Row(
children: [
_TableRowItem('Item $i, Column 1'),
if (showCol2) _TableRowItem('Item $i, Column 2'),
if (showCol3) _TableRowItem('Item $i, Column 3'),
if (showCol4) _TableRowItem('Item $i, Column 4'),
],
),
);
}).toList(),
),
),
),
]);
},
);
}
}
class _TableHeader extends StatelessWidget {
const _TableHeader(this.label);
final String label;
@override
Widget build(BuildContext context) => Expanded(
child: Padding(
padding: const EdgeInsets.all(Insets.medium),
child: Text(
label,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
),
);
}
class _TableRowItem extends StatelessWidget {
const _TableRowItem(this.label);
final String label;
@override
Widget build(BuildContext context) => Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Insets.medium, vertical: Insets.extraLarge),
child: Text(label)));
}
| website/examples/ui/layout/adaptive_app_demos/lib/pages/adaptive_data_table_page.dart/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/lib/pages/adaptive_data_table_page.dart",
"repo_id": "website",
"token_count": 1159
} | 1,398 |
import 'package:flutter/material.dart';
class MyButton extends StatelessWidget {
const MyButton({super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
print('MyButton was tapped!');
},
child: Container(
height: 50,
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.lightGreen[500],
),
child: const Center(
child: Text('Engage'),
),
),
);
}
}
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Center(
child: MyButton(),
),
),
),
);
}
| website/examples/ui/widgets_intro/lib/main_mybutton.dart/0 | {
"file_path": "website/examples/ui/widgets_intro/lib/main_mybutton.dart",
"repo_id": "website",
"token_count": 363
} | 1,399 |
---
title: Page not found
description: Page not found
layout: landing
body_class: landing-page not-found
permalink: /404.html
---
<div class="not-found__wrapper">
<h1>404</h1>
<p>Sorry, we couldn't find that page…</p>
<img src='/assets/images/404/dash_nest.png' class='not-found__illo' alt="Dash pointing you in the right direction">
<p>But Dash is here to help - maybe one of these will point you in the right direction?</p>
<ul class="not-found__link-list">
<li><a href="{{site.main-url}}/">Homepage</a></li>
<li><a href="{{site.pub}}/">Package site</a></li>
<li><a href="{{site.api}}/">API reference</a></li>
<li><a href="/">Documentation</a></li>
<li><a href="https://flutter.github.io/samples">Samples</a></li>
<li><a href="{{site.main-url}}/community">Community</a></li>
<li><a href="{{site.medium}}/flutter">Medium</a></li>
<li><a href="{{site.social.twitter}}/">Twitter</a></li>
<li><a href="/resources/faq">FAQ</a></li>
</ul>
</div>
| website/src/404.html/0 | {
"file_path": "website/src/404.html",
"repo_id": "website",
"token_count": 385
} | 1,400 |
{% assign platform = include.platform -%}
{% assign caption = include.caption | default: platform -%}
{% assign alt = include.alt | default: caption -%}
{% assign image = include.image -%}
{% if include.width -%}
{% assign width = 'width: ' | append: include.width | append: ';' -%}
{% else -%}
{% assign width = '' -%}
{% endif -%}
{% if include.height -%}
{% assign height = 'height: ' | append: include.height | append: ';' -%}
{% else -%}
{% assign height = '' -%}
{% endif -%}
{% comment %}
NOTE possibly sneaky introspection, feeling like this should be removed
NOTE(rearch) We second that, never a good idea.
{% endcomment %}
{% if include.path-prefix -%}
{% assign path = include.path-prefix | append: '/' -%}
{% else -%}
{% assign path = '' -%}
{% endif -%}
{% if platform -%}
{% assign alt = alt | append: ' on ' | append: platform -%}
{% assign platform_in_lowercase = platform | downcase -%}
{% assign path = path | append: platform_in_lowercase | append: '/' -%}
{% endif -%}
<figure class="site-figure {{include.class}}">
<div class="site-figure-container-lg">
<img src='/assets/images/docs/{{path}}{{include.image}}'
class='{{include.img-class}}'
alt='{{alt}}'
style='{{width}} {{height}}'
>
{% if caption -%}
<figcaption class="figure-caption">{{caption}}</figcaption>
{% endif -%}
</div>
</figure>
| website/src/_includes/docs/app-figure.liquid/0 | {
"file_path": "website/src/_includes/docs/app-figure.liquid",
"repo_id": "website",
"token_count": 528
} | 1,401 |
#### Build the Windows version of the Flutter app in PowerShell or the Command Prompt
To generate the needed Windows platform dependencies,
run the `flutter build` command.
```terminal
C:\> flutter build windows --debug
```
```terminal
Building Windows application... 31.4s
√ Built build\windows\runner\Debug\my_app.exe.
```
{% comment %} Nav tabs {% endcomment -%}
<ul class="nav nav-tabs" id="vscode-to-vs-setup" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="from-vscode-to-vs-tab" href="#from-vscode-to-vs" role="tab" aria-controls="from-vscode-to-vs" aria-selected="true">Start from VS Code</a>
</li>
<li class="nav-item">
<a class="nav-link" id="from-vs-to-vscode-tab" href="#from-vs-to-vscode" role="tab" aria-controls="from-vs-to-vscode" aria-selected="false">Start from Visual Studio</a>
</li>
</ul>
{% comment %} Tab panes {% endcomment -%}
<div class="tab-content">
<div class="tab-pane active" id="from-vscode-to-vs" role="tabpanel" aria-labelledby="from-vscode-to-vs-tab" markdown="1">
#### Start debugging with VS Code first {#vscode-windows}
If you use VS Code to debug most of your code, start with this section.
##### Start the debugger in VS Code
{% include docs/debug/debug-flow-vscode-as-start.md %}
{% comment %}
{:width="50%"}
<div class="figure-caption">
Flutter app generated as a Windows app. The app displays two buttons to open this page in a browser or in the app.
</div>
{% endcomment %}
##### Attach to the Flutter process in Visual Studio
1. To open the project solution file, go to
**File** <span aria-label="and then">></span>
**Open** <span aria-label="and then">></span>
**Project/Solution…**
You can also press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd>.
1. Choose the `build/windows/my_app.sln` file in your Flutter app directory.
{% comment %}
{:width="100%"}
<div class="figure-caption">
Open Project/Solution dialog box in Visual Studio 2022 with
`my_app.sln` file selected.
</div>
{% endcomment %}
1. Go to **Debug** > **Attach to Process**.
You can also press <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>P</kbd>.
1. From the **Attach to Process** dialog box, choose `my_app.exe`.
{% comment %}
{:width="100%"}
{% endcomment %}
Visual Studio starts monitoring the Flutter app.
{% comment %}
{:width="100%"}
{% endcomment %}
</div>
<div class="tab-pane" id="from-vs-to-vscode" role="tabpanel" aria-labelledby="from-vs-to-vscode-tab" markdown="1">
#### Start debugging with Visual Studio first
If you use Visual Studio to debug most of your code, start with this section.
##### Start the local Windows debugger
1. To open the project solution file, go to
**File** <span aria-label="and then">></span>
**Open** <span aria-label="and then">></span>
**Project/Solution…**
You can also press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd>.
1. Choose the `build/windows/my_app.sln` file in your Flutter app directory.
{% comment %}
{:width="100%"}
<div class="figure-caption">
Open Project/Solution dialog box in Visual Studio 2022 with
`my_app.sln` file selected.
</div>
{% endcomment %}
1. Set `my_app` as the startup project.
In the **Solution Explorer**, right-click on `my_app` and select
**Set as Startup Project**.
1. Click **Local Windows Debugger** to start debugging.
You can also press <kbd>F5</kbd>.
When the Flutter app has started, a console window displays
a message with the Dart VM service URI. It resembles the following response:
```terminal
flutter: The Dart VM service is listening on http://127.0.0.1:62080/KPHEj2qPD1E=/
```
1. Copy the Dart VM service URI.
##### Attach to the Dart VM in VS Code
1. To open the command palette, go to
**View** <span aria-label="and then">></span>
**Command Palette...**
You can also press <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>.
1. Type `debug`.
1. Click the **Debug: Attach to Flutter on Device** command.
{% comment %}
{:width="100%"}
{% endcomment %}
1. In the **Paste an VM Service URI** box, paste the URI you copied
from Visual Studio and press <kbd>Enter</kbd>.
{% comment %}

{% endcomment %}
</div>
</div>
{% comment %} End: Tab panes. {% endcomment -%}
| website/src/_includes/docs/debug/debug-flow-windows.md/0 | {
"file_path": "website/src/_includes/docs/debug/debug-flow-windows.md",
"repo_id": "website",
"token_count": 1949
} | 1,402 |
{% assign doctor = site.data.doctor %}
{% assign config = site.data.doctor[include.config] %}
{% case include.devos %}
{% when 'macOS' %}
{% assign displayos = 'macOS 14.4.0 23E214 darwin-arm64' %}
{% when 'Windows' %}
{% assign displayos = 'Microsoft Windows 11 [Version 10.0.22621.3155]' %}
{% when 'Linux' %}
{% assign displayos = 'Ubuntu 20.04 (LTS)' %}
{% endcase %}
{% comment %}
Don't change the whitespace control dashes in this list.
It took about two hours to get exactly right. @atsansone
{% endcomment %}
```terminal
Running flutter doctor...
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, {{site.appnow.flutter}}, on {{displayos}}, locale en)
{%- if config.windows == 'Y' %}
[✓] Windows version (Installed version of Windows is version 10 or higher)
{%- endif %}
{% case config.android-toolchain %}
{% when 'Y' %}[✓] Android toolchain - develop for Android devices (Android SDK version {{site.appnow.android_sdk}})
{% when 'N' %}[!] Android toolchain - develop for Android devices
{% endcase %}
{%- case config.chrome %}
{% when 'Y' %}[✓] Chrome - develop for the web
{% when 'N' %}[!] Chrome - develop for the web
{% endcase -%}
{% unless config.xcode == 'X' -%}
{% case config.xcode %}
{% when 'Y' %}[✓] Xcode - develop for iOS and macOS (Xcode {{site.appnow.xcode}})
{% when 'N' %}[!] Xcode - develop for iOS and macOS (Xcode not installed)
{% endcase %}
{%- endunless -%}
{% unless config.visual-studio == 'X' -%}
{% case config.visual-studio %}
{% when 'Y' %}[✓] Visual Studio - develop Windows apps (version 2022)
{% when 'N' %}[!] Visual Studio - develop Windows apps
{% endcase %}
{%- endunless %}
{%- case config.android-studio %}
{% when 'Y' %}[✓] Android Studio (version {{site.appnow.android_studio}})
{% when 'N' %}[!] Android Studio (not installed)
{% endcase -%}
{% unless config.linux == 'X' -%}
{% case config.linux %}
{% when 'Y' %}[✓] Linux toolchain - develop for Linux desktop
{% when 'N' %}[!] Linux toolchain - develop for Linux desktop
{% endcase %}
{%- endunless -%}
[✓] VS Code (version {{site.appnow.vscode}})
[✓] Connected device (1 available)
[✓] Network resources
{% unless config.errors == 0 %}
! Doctor found issues in {{config.errors}} categories.
{% else %}
∙ No issues found!
{% endunless -%}
```
| website/src/_includes/docs/install/flutter-doctor-success.md/0 | {
"file_path": "website/src/_includes/docs/install/flutter-doctor-success.md",
"repo_id": "website",
"token_count": 829
} | 1,403 |
{% assign terminal=include.terminal %}
{% assign target = include.target %}
{% assign dir = include.dir %}
### Add Flutter to your `PATH`
{:.no_toc}
To run Flutter commands in {{terminal}},
add Flutter to the `PATH` environment variable.
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. If it exists, open the Zsh environmental variable file `~/.zshenv`
in your text editor. If it doesn't, create `~/.zshenv`.
1. Copy the following line and paste it 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 setting 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://www.cyberciti.biz/faq/unix-linux-adding-path/
| website/src/_includes/docs/install/reqs/macos/set-path.md/0 | {
"file_path": "website/src/_includes/docs/install/reqs/macos/set-path.md",
"repo_id": "website",
"token_count": 361
} | 1,404 |
<div class="tab-pane active" id="vscode" role="tabpanel" aria-labelledby="vscode-tab" markdown="1">
### Create your sample Flutter app {#create-app}
1. Open the Command Palette.
Go to **View** <span aria-label="and then">></span> **Command Palette** or
press <kbd>{{special}}</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>.
1. Type `flutter`
1. Select the **Flutter: New Project**.
1. When prompted for **Which Flutter Project**, select **Application**.
1. Create or select the parent directory for the new project folder.
1. When prompted for a **Project Name**, enter `test_drive`.
1. Press <kbd>Enter</kbd>.
1. Wait for project creation to complete.
1. Open the `lib` directory, then the `main.dart`.
To learn what each code block does, check out the comments in that Dart file.
The previous commands create a Flutter project directory called `test_drive` that
contains a simple demo app that uses [Material Components][].
### Run your sample Flutter app
Run your example application on your desktop platform, in the Chrome web browser, in an iOS simulator, or
Android emulator.
{{site.alert.secondary}}
Though you can deploy your app to the web,
note that the web target doesn't support
hot reload at this time.
{{site.alert.end}}
1. Open the Command Palette.
Go to **View** <span aria-label="and then">></span> **Command Palette** or
press <kbd>{{special}}</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>.
1. Type `flutter`
1. Select the **Flutter: Select Device**.
If no devices are running, this command prompts you to enable a device.
1. Select a target device from **Select Device** prompt.
1. After you select a target, start the app.
Go to **Run** <span aria-label="and then">></span>
**Start Debugging** or press <kbd>F5</kbd>.
1. Wait for the app to launch.
You can watch the launch progress in the **Debug Console** view.
{% capture save_changes -%}
: invoke **Save All**, or click **Hot Reload**
{% include docs/install/test-drive/hot-reload-icon.md %}.
{% endcapture %}
{% include docs/install/test-drive/try-hot-reload.md save_changes=save_changes ide="VS Code" %}
[Material Components]: {{site.material}}/components
</div>
| website/src/_includes/docs/install/test-drive/vscode.md/0 | {
"file_path": "website/src/_includes/docs/install/test-drive/vscode.md",
"repo_id": "website",
"token_count": 708
} | 1,405 |
{% for entry in include.children -%}
{% if include.active_entries and forloop.index == include.active_entries[1] -%}
{% assign isActive = true -%}
{% assign class = 'nav-link active' -%}
{% else -%}
{% assign isActive = false -%}
{% assign class = 'nav-link' -%}
{% endif -%}
{% if entry == 'divider' -%}
<div class="dropdown-divider"></div>
{% elsif entry contains 'header' -%}
<li class="nav-header">{{entry.header}}</li>
{%- elsif entry.children -%}
{% assign class = class | append: ' collapsible' -%}
{% if isActive or entry.expanded -%}
{% assign expanded = 'true' -%}
{% assign show = 'show' -%}
{% else -%}
{% assign class = class | append: ' collapsed' -%}
{% assign expanded = 'false' -%}
{% assign show = '' -%}
{% endif -%}
{% assign id = include.parent_id | append: '-' | append: forloop.index -%}
{% assign href = entry.permalink -%}
{% unless href -%}
{% assign href = '#' | append: id -%}
{% endunless -%}
<li class="nav-item">
<a class="{{class}}"
data-toggle="collapse" data-target="#{{id}}"
href="{{href}}" role="button"
aria-expanded="{{expanded}}" aria-controls="{{id}}"
>{{entry.title}}
</a>
<ul class="nav flex-column flex-nowrap collapse {{show}}" id="{{id}}">
{% if isActive -%}
{% include sidenav-level-3.html parent_id=id children=entry.children active_entries=active_entries -%}
{% else -%}
{% include sidenav-level-3.html parent_id=id children=entry.children -%}
{% endif -%}
</ul>
</li>
{%- elsif entry.permalink -%}
{% if entry.permalink contains '://' -%}
{% assign isExternal = true -%}
{% else -%}
{% assign isExternal = false -%}
{% endif -%}
<li class="nav-item">
<a class="{{class}}" href="{{entry.permalink}}"
{%- if isExternal %} target="_blank" rel="noopener" {%- endif -%}
>{{entry.title}}</a>
</li>
{% endif -%}
{% endfor %}
| website/src/_includes/sidenav-level-2.html/0 | {
"file_path": "website/src/_includes/sidenav-level-2.html",
"repo_id": "website",
"token_count": 809
} | 1,406 |
##
## Classes that support the processing of <?code-excerpt?> and
## <?code-pane?> instructions.
##
require 'active_support'
require 'active_support/isolated_execution_state'
require 'active_support/core_ext/string'
require 'open3'
require 'nokogiri'
require 'yaml'
require_relative 'code_diff_core'
require_relative 'dart_site_util'
module DartSite
class CodeExcerptProcessor
# @param code_framer is used to wrap code blocks with HTML that provides
# features like code block headers and a copy-code button.
def initialize(code_framer)
@@log_file_name = 'code-excerpt-log.txt'
@@log_entry_count = 0
@log_diffs = false
File.delete(@@log_file_name) if File.exist?(@@log_file_name)
# @site_title = Jekyll.configuration({})['title']
@code_differ = DartSite::CodeDiffCore.new
@code_framer = code_framer
end
def code_excerpt_regex
/^(\s*(<\?(code-\w+)[^>]*>)\n)((\s*)```((\w*)([^\n]*))\n(.*?)\n(\s*)```\n?)?/m;
end
def code_excerpt_processing_init
@path_base = ''
end
def process_code_excerpt(match)
# pi_line_with_whitespace = match[1]
pi = match[2] # full processing instruction <?code-excerpt...?>
pi_name = match[3]
args = process_pi_args(pi)
optional_code_block = match[4]
indent = match[5]
secondary_class = match[6]
lang = !match[7] || match[7].empty? ? (args['ext'] || 'nocode') : match[7]
attrs = mk_code_example_directive_attr(lang, args['linenums'])
return process_code_pane(pi, attrs, args) if pi_name == 'code-pane'
if pi_name != 'code-excerpt'
log_puts "Warning: unrecognized instruction: #{pi}"
return match[0]
elsif !optional_code_block
# w/o a code block assume it is a set cmd
process_set_command(pi, args)
return ''
end
code = match[9]
leading_whitespace = get_indentation_string(optional_code_block)
code = Util.trim_min_leading_space(code)
if lang == 'diff'
diff = @code_differ.render(args, code)
diff.indent!(leading_whitespace.length) if leading_whitespace
return diff
end
title = args['title']
classes = args['class']
# We escape all code fragments (not just HTML fragments),
# because we're rendering the code block as HTML.
escaped_code = CGI.escapeHTML(code)
code = @code_framer.frame_code(title, classes, attrs, _process_highlight_markers(escaped_code), indent, secondary_class)
code.indent!(leading_whitespace.length) if leading_whitespace
code
end
def _process_highlight_markers(s)
# Only replace [! and !] if both exist
s.gsub(/\[!(.*?)!\]/m, '<span class="highlight">\1</span>')
end
def trim_min_leading_space(code)
lines = code.split(/\n/);
non_blank_lines = lines.reject { |s| s.match(/^\s*$/) }
# Length of leading spaces to be trimmed
len = non_blank_lines.map{ |s|
matches = s.match(/^[ \t]*/)
matches ? matches[0].length : 0 }.min
len == 0 ? code : lines.map{|s| s.length < len ? s : s[len..-1]}.join("\n")
end
# @return [Hash] of attributes as attribute-name/value pairs.
# Supported attribute names (all optional):
# - [Array] `:class`
# - [String] `:lang`
def mk_code_example_directive_attr(lang, linenums)
classes = []
classes << 'linenums' if linenums
classes << 'nocode' if lang == 'nocode'
attrs = {}
attrs[:class] = classes unless classes.empty?
attrs[:lang] = lang unless lang == 'nocode'
attrs
end
# @param [Hash] attrs: attributes as attribute-name/value pairs.
# @return [String] Attributes as a single string: 'foo="bar" baz="..."'
def attr_str(attrs)
attributes = []
attrs.each do |name, value|
attr_as_s = name.to_s
value *= ' ' if value.kind_of?(Array)
attr_as_s += %Q(="#{value}") if value
attributes << attr_as_s
end
attributes * ' '
end
def process_pi_args(pi)
# match = /<\?code-\w+\s*(("([^"]*)")?((\s+[-\w]+="[^"]*"\s*)*))\?>/.match(pi)
match = /<\?code-\w+\s*(.*?)\s*\?>/.match(pi)
unless match
log_puts "ERROR: improperly formatted instruction: #{pi}"
return nil
end
arg_string = match[1]
args = { }
# First argument can be unnamed. When present, it is saved as
# args['']. It is used to define a path and an optional region.
match = /^"(([^("]*)(\s+\(([^"]+)\))?)"/.match(arg_string)
if match
arg_string = $' # reset to remaining args
args[''] = match[1]
path = args['path'] = match[2]
args['ext'] = File.extname(path)&.sub(/^\./,'')
args['region'] = match[4]&.gsub(/[^\w]+/, '-') || ''
end
# Process remaining args
arg_string.scan(/\b(\w[-\w]*)(="([^"]*)")?/) { |id,arg,val|
if id == 'title' && !arg then val = trim_file_vers(args['']) end
args[id] = val || ''
}
# puts " >> args: #{args}"
args
end
# @param [Hash] attrs: attributes as attribute-name/value pairs.
def process_code_pane(pi, _attrs, args)
# TODO: support use of globally set replace args.
title = args['title'] || trim_file_vers(args[''])
escaped_code = get_code_frag(args['path'],
full_frag_path(args['path'], args['region']),
src_path(args['path'], args['region']),
args['region'])
# args['replace'] syntax: /regex/replacement/g
# Replacement and '_g' are currently mandatory (but not checked)
if args['replace']
_, re, replacement, _g = args['replace'].split '/'
escaped_code.gsub!(Regexp.new(re)) {
match = Regexp.last_match
# TODO: doesn't yet recognize escaped '$' ('\$')
while (arg_match = /(?<=\$)(\d)(?!\d)/.match(replacement)) do
next unless arg_match
replacement.gsub!("$#{arg_match[0]}", match[arg_match[0].to_i])
end
if /\$\d+|\\\$/.match?(replacement)
raise "Plugin doesn't support \\$, or more than 9 match groups $1, ..., $9: #{replacement}.\nAborting."
end
if replacement.include? '$&'
replacement.gsub('$&', match[0])
else
replacement
end
}
end
escaped_code = _process_highlight_markers(escaped_code)
attrs = {}
attrs[:language] = _attrs[:lang] if _attrs[:lang]
attrs[:format] = _attrs[:class] if _attrs[:class]
<<~TEMPLATE
#{pi}
<code-pane name="#{title}" #{attr_str attrs}>#{escaped_code}</code-pane>
TEMPLATE
end
def process_set_command(_pi, args)
# Ignore all commands other than path-base.
path_base = args['path-base']
return unless path_base
@path_base = path_base.sub(/\/$/, '')
# puts ">> path base set to '#{@path_base}'"
end
def get_code_frag(proj_rel_path, _frag_path, src_path, region)
excerpt_yaml_path = File.join(Dir.pwd, 'tmp', '_fragments', @path_base, proj_rel_path + '.excerpt.yaml');
if File.exist? excerpt_yaml_path
yaml = YAML.load_file(excerpt_yaml_path)
result = yaml[region]
if result.nil?
result = "CODE EXCERPT not found: region '#{region}' not found in #{excerpt_yaml_path}"
log_puts result
else
lines = result.split(/(?<=\n)/) # split and keep separator
result = escape_and_trim_code(lines)
end
# We don't generate frag_path fragments anymore:
# elsif File.exists? frag_path
# lines = File.readlines frag_path
# result = escapeAndTrimCode(lines)
elsif region.empty? && src_path && (File.exist? src_path)
lines = File.readlines src_path
result = escape_and_trim_code(lines)
raise 'CODE EXCERPT not found: no .excerpt.yaml file ' \
"and source contains docregions: #{src_path}" if result.include? '#docregion'
else
result = "CODE EXCERPT not found: #{excerpt_yaml_path}, region='#{region}'"
log_puts result
end
result
end
def full_frag_path(proj_rel_path, region)
frag_rel_path = File.join(@path_base, proj_rel_path)
if region && !region.empty?
dir = File.dirname(frag_rel_path)
basename = File.basename(frag_rel_path, '.*')
ext = File.extname(frag_rel_path)
frag_rel_path = File.join(dir, "#{basename}-#{region}#{ext}")
end
frag_extension = '.txt'
File.join(Dir.pwd, 'tmp', '_fragments', frag_rel_path + frag_extension)
end
def src_path(proj_rel_path, region)
region == '' ? File.join(@path_base, proj_rel_path) : nil
end
def escape_and_trim_code(lines)
# Skip blank lines at the end too
while !lines.empty? && lines.last.strip == '' do lines.pop end
CGI.escapeHTML(lines.join)
end
def log_puts(s)
puts(s)
file_mode = (@@log_entry_count += 1) <= 1 ? 'w' : 'a'
File.open(@@log_file_name, file_mode) do |logFile| logFile.puts(s) end
end
def trim_file_vers(s)
# Path/title like styles.1.css or foo_1.dart? Then drop the '.1' or '_1' qualifier:
match = /^(.*)[._]\d(\.\w+)(\s+.+)?$/.match(s)
s = "#{match[1]}#{match[2]}#{match[3]}" if match
s
end
def get_indentation_string(s)
match = s.match(/^[ \t]*/)
match ? match[0] : nil
end
end
end
| website/src/_plugins/code_excerpt_processor.rb/0 | {
"file_path": "website/src/_plugins/code_excerpt_processor.rb",
"repo_id": "website",
"token_count": 4394
} | 1,407 |
@use '../vendor/bootstrap';
.book-img-with-details {
margin-bottom: 1.5rem;
img {
@include bootstrap.media-breakpoint-down(sm) { max-width: 200px; }
width: 100%;
}
.details {
.title {
@include bootstrap.media-breakpoint-up(sm) { margin-top: 0; }
margin-bottom: 0;
}
}
}
| website/src/_sass/components/_books.scss/0 | {
"file_path": "website/src/_sass/components/_books.scss",
"repo_id": "website",
"token_count": 137
} | 1,408 |
/**
* @license
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Pretty printing styles. Used with prettify.js. */
/* SPAN elements with the classes below are added by prettyprint. */
.pln { color: #000 } /* plain text */
@media screen {
.str { color: #080 } /* string content */
.kwd { color: #008 } /* a keyword */
.com { color: #800 } /* a comment */
.typ { color: #606 } /* a type name */
.lit { color: #066 } /* a literal value */
/* punctuation, lisp open bracket, lisp close bracket */
.pun, .opn, .clo { color: #660 }
.tag { color: #008 } /* a markup tag name */
.atn { color: #606 } /* a markup attribute name */
.atv { color: #080 } /* a markup attribute value */
.dec, .var { color: #606 } /* a declaration; a variable name */
.fun { color: red } /* a function name */
}
/* Use higher contrast and text-weight for printable form. */
@media print, projection {
.str { color: #060 }
.kwd { color: #006; font-weight: bold }
.com { color: #600; font-style: italic }
.typ { color: #404; font-weight: bold }
.lit { color: #044 }
.pun, .opn, .clo { color: #440 }
.tag { color: #006; font-weight: bold }
.atn { color: #404 }
.atv { color: #060 }
}
/* Put a border around prettyprinted code snippets. */
pre.prettyprint { padding: 2px; border: 1px solid #888 }
/* Specify class=linenums on a pre to get line numbering */
ol.linenums { margin-top: 0; margin-bottom: 0 } /* IE indents via margin-left */
li.L0,
li.L1,
li.L2,
li.L3,
li.L5,
li.L6,
li.L7,
li.L8 { list-style-type: none }
/* Alternate shading for lines */
li.L1,
li.L3,
li.L5,
li.L7,
li.L9 { background: #eee }
| website/src/_sass/vendor/_prettify.scss/0 | {
"file_path": "website/src/_sass/vendor/_prettify.scss",
"repo_id": "website",
"token_count": 747
} | 1,409 |
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 27.7.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="448px" height="512px" viewBox="0 0 448 512" style="enable-background:new 0 0 448 512;" xml:space="preserve">
<style type="text/css">
.st0{fill:#027DFD;}
</style>
<path class="st0" d="M220.8,123.3c1,0.5,1.8,1.7,3,1.7c1.1,0,2.8-0.4,2.9-1.5c0.2-1.4-1.9-2.3-3.2-2.9c-1.7-0.7-3.9-1-5.5-0.1
c-0.4,0.2-0.8,0.7-0.6,1.1C217.7,122.9,219.7,122.7,220.8,123.3L220.8,123.3z M198.9,125c1.2,0,2-1.2,3-1.7c1.1-0.6,3.1-0.4,3.5-1.6
c0.2-0.4-0.2-0.9-0.6-1.1c-1.6-0.9-3.8-0.6-5.5,0.1c-1.3,0.6-3.4,1.5-3.2,2.9C196.2,124.6,197.9,125.1,198.9,125z M420,403.8
c-3.6-4-5.3-11.6-7.2-19.7c-1.8-8.1-3.9-16.8-10.5-22.4c-1.3-1.1-2.6-2.1-4-2.9c-1.3-0.8-2.7-1.5-4.1-2c9.2-27.3,5.6-54.5-3.7-79.1
c-11.4-30.1-31.3-56.4-46.5-74.4c-17.1-21.5-33.7-41.9-33.4-72C311.1,85.4,315.7,0.1,234.8,0C132.4-0.2,158,103.4,156.9,135.2
c-1.7,23.4-6.4,41.8-22.5,64.7c-18.9,22.5-45.5,58.8-58.1,96.7c-6,17.9-8.8,36.1-6.2,53.3c-6.5,5.8-11.4,14.7-16.6,20.2
c-4.2,4.3-10.3,5.9-17,8.3s-14,6-18.5,14.5c-2.1,3.9-2.8,8.1-2.8,12.4c0,3.9,0.6,7.9,1.2,11.8c1.2,8.1,2.5,15.7,0.8,20.8
c-5.2,14.4-5.9,24.4-2.2,31.7c3.8,7.3,11.4,10.5,20.1,12.3c17.3,3.6,40.8,2.7,59.3,12.5c19.8,10.4,39.9,14.1,55.9,10.4
c11.6-2.6,21.1-9.6,25.9-20.2c12.5-0.1,26.3-5.4,48.3-6.6c14.9-1.2,33.6,5.3,55.1,4.1c0.6,2.3,1.4,4.6,2.5,6.7v0.1
c8.3,16.7,23.8,24.3,40.3,23c16.6-1.3,34.1-11,48.3-27.9c13.6-16.4,36-23.2,50.9-32.2c7.4-4.5,13.4-10.1,13.9-18.3
C435.9,425.3,431.1,416.2,420,403.8L420,403.8z M223.7,87.3c9.8-22.2,34.2-21.8,44-0.4c6.5,14.2,3.6,30.9-4.3,40.4
c-1.6-0.8-5.9-2.6-12.6-4.9c1.1-1.2,3.1-2.7,3.9-4.6c4.8-11.8-0.2-27-9.1-27.3c-7.3-0.5-13.9,10.8-11.8,23c-4.1-2-9.4-3.5-13-4.4
C219.8,102.2,220.5,94.5,223.7,87.3z M183,75.8c10.1,0,20.8,14.2,19.1,33.5c-3.5,1-7.1,2.5-10.2,4.6c1.2-8.9-3.3-20.1-9.6-19.6
c-8.4,0.7-9.8,21.2-1.8,28.1c1,0.8,1.9-0.2-5.9,5.5C159,113.3,164.1,75.8,183,75.8z M169.4,136.5c6.2-4.6,13.6-10,14.1-10.5
c4.7-4.4,13.5-14.2,27.9-14.2c7.1,0,15.6,2.3,25.9,8.9c6.3,4.1,11.3,4.4,22.6,9.3c8.4,3.5,13.7,9.7,10.5,18.2
c-2.6,7.1-11,14.4-22.7,18.1c-11.1,3.6-19.8,16-38.2,14.9c-3.9-0.2-7-1-9.6-2.1c-8-3.5-12.2-10.4-20-15
c-8.6-4.8-13.2-10.4-14.7-15.3C163.8,143.9,165.2,139.8,169.4,136.5L169.4,136.5z M172.7,470.5c-2.7,35.1-43.9,34.4-75.3,18
c-29.9-15.8-68.6-6.5-76.5-21.9c-2.4-4.7-2.4-12.7,2.6-26.4V440c2.4-7.6,0.6-16-0.6-23.9c-1.2-7.8-1.8-15,0.9-20
c3.5-6.7,8.5-9.1,14.8-11.3c10.3-3.7,11.8-3.4,19.6-9.9c5.5-5.7,9.5-12.9,14.3-18c5.1-5.5,10-8.1,17.7-6.9c8.1,1.2,15.1,6.8,21.9,16
l19.6,35.6C141.2,421.5,174.8,450,172.7,470.5L172.7,470.5z M171.3,444.6c-4.1-6.6-9.6-13.6-14.4-19.6c7.1,0,14.2-2.2,16.7-8.9
c2.3-6.2,0-14.9-7.4-24.9c-13.5-18.2-38.3-32.5-38.3-32.5c-13.5-8.4-21.1-18.7-24.6-29.9s-3-23.3-0.3-35.2
c5.2-22.9,18.6-45.2,27.2-59.2c2.3-1.7,0.8,3.2-8.7,20.8c-8.5,16.1-24.4,53.3-2.6,82.4c0.6-20.7,5.5-41.8,13.8-61.5
c12-27.4,37.3-74.9,39.3-112.7c1.1,0.8,4.6,3.2,6.2,4.1c4.6,2.7,8.1,6.7,12.6,10.3c12.4,10,28.5,9.2,42.4,1.2
c6.2-3.5,11.2-7.5,15.9-9c9.9-3.1,17.8-8.6,22.3-15c7.7,30.4,25.7,74.3,37.2,95.7c6.1,11.4,18.3,35.5,23.6,64.6
c3.3-0.1,7,0.4,10.9,1.4c13.8-35.7-11.7-74.2-23.3-84.9c-4.7-4.6-4.9-6.6-2.6-6.5c12.6,11.2,29.2,33.7,35.2,59
c2.8,11.6,3.3,23.7,0.4,35.7c16.4,6.8,35.9,17.9,30.7,34.8c-2.2-0.1-3.2,0-4.2,0c3.2-10.1-3.9-17.6-22.8-26.1
c-19.6-8.6-36-8.6-38.3,12.5c-12.1,4.2-18.3,14.7-21.4,27.3c-2.8,11.2-3.6,24.7-4.4,39.9c-0.5,7.7-3.6,18-6.8,29
C253.5,460.3,208.9,470.3,171.3,444.6L171.3,444.6z M428.7,433.1c-0.9,16.8-41.2,19.9-63.2,46.5c-13.2,15.7-29.4,24.4-43.6,25.5
s-26.5-4.8-33.7-19.3c-4.7-11.1-2.4-23.1,1.1-36.3c3.7-14.2,9.2-28.8,9.9-40.6c0.8-15.2,1.7-28.5,4.2-38.7
c2.6-10.3,6.6-17.2,13.7-21.1c0.3-0.2,0.7-0.3,1-0.5c0.8,13.2,7.3,26.6,18.8,29.5c12.6,3.3,30.7-7.5,38.4-16.3
c9-0.3,15.7-0.9,22.6,5.1c9.9,8.5,7.1,30.3,17.1,41.6C425.6,420.1,429,428,428.7,433.1L428.7,433.1z M173.3,148.7
c2,1.9,4.7,4.5,8,7.1c6.6,5.2,15.8,10.6,27.3,10.6c11.6,0,22.5-5.9,31.8-10.8c4.9-2.6,10.9-7,14.8-10.4c3.9-3.4,5.9-6.3,3.1-6.6
s-2.6,2.6-6,5.1c-4.4,3.2-9.7,7.4-13.9,9.8c-7.4,4.2-19.5,10.2-29.9,10.2s-18.7-4.8-24.9-9.7c-3.1-2.5-5.7-5-7.7-6.9
c-1.5-1.4-1.9-4.6-4.3-4.9C170.2,142.1,169.8,145.9,173.3,148.7L173.3,148.7z"/>
</svg>
| website/src/assets/images/docs/brand-svg/linux.svg/0 | {
"file_path": "website/src/assets/images/docs/brand-svg/linux.svg",
"repo_id": "website",
"token_count": 3513
} | 1,410 |
function setupTabs(container, storageName, defaultTabGetter) {
const tabs = $(container).find('li a');
function getTabIdFromQuery(query) {
const match = query.match(/(#|\btab=)([\w-]+)/);
return match ? match[2] : '';
}
function clickHandler(e) {
e.preventDefault();
$(this).tab('show');
const id = getTabIdFromQuery($(this).attr('href'));
if (storageName && window.localStorage) {
window.localStorage.setItem(storageName, id);
}
updateUrlQuery(id);
}
function updateUrlQuery(id) {
const loc = window.location;
const query = '?tab=' + id;
if (id && loc.search !== query) {
const url = loc.protocol + '//' + loc.host + loc.pathname + query + loc.hash;
history.replaceState(undefined, undefined, url);
}
}
function selectTab(id) {
const tab = tabs.filter('[href="#' + id + '"]');
tab.click();
}
function getSelectedTab() {
let selectedTab = getTabIdFromQuery(location.search);
if (!selectedTab && storageName && window.localStorage) {
selectedTab = window.localStorage.getItem(storageName);
}
if (selectedTab) {
return selectedTab;
}
if (defaultTabGetter) {
return defaultTabGetter();
}
return null;
}
function initializeTabs() {
tabs.click(clickHandler);
const selectedTab = getSelectedTab();
selectTab(selectedTab);
}
initializeTabs();
}
| website/src/assets/js/tabs.js/0 | {
"file_path": "website/src/assets/js/tabs.js",
"repo_id": "website",
"token_count": 526
} | 1,411 |
---
title: Add a drawer to a screen
description: How to implement a Material Drawer.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/design/drawer"?>
In apps that use Material Design,
there are two primary options for navigation: tabs and drawers.
When there is insufficient space to support tabs,
drawers provide a handy alternative.
In Flutter, use the [`Drawer`][] widget in combination with a
[`Scaffold`][] to create a layout with a Material Design drawer.
This recipe uses the following steps:
1. Create a `Scaffold`.
2. Add a drawer.
3. Populate the drawer with items.
4. Close the drawer programmatically.
## 1. Create a `Scaffold`
To add a drawer to the app, wrap it in a [`Scaffold`][] widget.
The `Scaffold` widget provides a consistent visual structure to apps that
follow the Material Design Guidelines.
It also supports special Material Design
components, such as Drawers, AppBars, and SnackBars.
In this example, create a `Scaffold` with a `drawer`:
<?code-excerpt "lib/drawer.dart (DrawerStart)" replace="/null, //g"?>
```dart
Scaffold(
appBar: AppBar(
title: const Text('AppBar without hamburger button'),
),
drawer: // Add a Drawer here in the next step.
);
```
## 2. Add a drawer
Now add a drawer to the `Scaffold`. A drawer can be any widget,
but it's often best to use the `Drawer` widget from the
[material library][],
which adheres to the Material Design spec.
<?code-excerpt "lib/drawer.dart (DrawerEmpty)" replace="/null, //g"?>
```dart
Scaffold(
appBar: AppBar(
title: const Text('AppBar with hamburger button'),
),
drawer: Drawer(
child: // Populate the Drawer in the next step.
),
);
```
## 3. Populate the drawer with items
Now that you have a `Drawer` in place, add content to it.
For this example, use a [`ListView`][].
While you could use a `Column` widget,
`ListView` is handy because it allows users to scroll
through the drawer if the
content takes more space than the screen supports.
Populate the `ListView` with a [`DrawerHeader`][]
and two [`ListTile`][] widgets.
For more information on working with Lists,
see the [list recipes][].
<?code-excerpt "lib/drawer.dart (DrawerListView)"?>
```dart
Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Item 1'),
onTap: () {
// Update the state of the app.
// ...
},
),
ListTile(
title: const Text('Item 2'),
onTap: () {
// Update the state of the app.
// ...
},
),
],
),
);
```
## 4. Close the drawer programmatically
After a user taps an item, you might want to close the drawer.
You can do this by using the [`Navigator`][].
When a user opens the drawer, Flutter adds the drawer to the navigation
stack. Therefore, to close the drawer, call `Navigator.pop(context)`.
<?code-excerpt "lib/drawer.dart (CloseDrawer)"?>
```dart
ListTile(
title: const Text('Item 1'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
```
## Interactive example
This example shows a [`Drawer`][] as it is used within a [`Scaffold`][] widget.
The [`Drawer`][] has three [`ListTile`][] items.
The `_onItemTapped` function changes the selected item's index
and displays the corresponding text in the center of the `Scaffold`.
{{site.alert.note}}
For more information on implementing navigation,
check out the [Navigation][] section of the cookbook.
{{site.alert.end}}
<?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});
static const appTitle = 'Drawer Demo';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: _widgetOptions[_selectedIndex],
),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
ListTile(
title: const Text('Home'),
selected: _selectedIndex == 0,
onTap: () {
// Update the state of the app
_onItemTapped(0);
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: const Text('Business'),
selected: _selectedIndex == 1,
onTap: () {
// Update the state of the app
_onItemTapped(1);
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: const Text('School'),
selected: _selectedIndex == 2,
onTap: () {
// Update the state of the app
_onItemTapped(2);
// Then close the drawer
Navigator.pop(context);
},
),
],
),
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/drawer.png" alt="Drawer Demo" class="site-mobile-screenshot" />
</noscript>
[`Drawer`]: {{site.api}}/flutter/material/Drawer-class.html
[`DrawerHeader`]: {{site.api}}/flutter/material/DrawerHeader-class.html
[list recipes]: /cookbook#lists
[`ListTile`]: {{site.api}}/flutter/material/ListTile-class.html
[`ListView`]: {{site.api}}/flutter/widgets/ListView-class.html
[material library]: {{site.api}}/flutter/material/material-library.html
[`Navigator`]: {{site.api}}/flutter/widgets/Navigator-class.html
[`Scaffold`]: {{site.api}}/flutter/material/Scaffold-class.html
[Navigation]: /cookbook#navigation
| website/src/cookbook/design/drawer.md/0 | {
"file_path": "website/src/cookbook/design/drawer.md",
"repo_id": "website",
"token_count": 3005
} | 1,412 |
---
title: Create a shimmer loading effect
description: How to implement a shimmer loading effect.
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/effects/shimmer_loading"?>
Loading times are unavoidable in application development.
From a user experience (UX) perspective,
the most important thing is to show your users
that loading is taking place. One popular approach
to communicate to users that data is loading is to
display a chrome color with a shimmer animation over
the shapes that approximate the type of content that is loading.
The following animation shows the app's behavior:
{:.site-mobile-screenshot}
This recipe begins with the content widgets defined and positioned.
There is also a Floating Action Button (FAB) in the bottom-right
corner that toggles between a loading mode and a loaded mode
so that you can easily validate your implementation.
## Draw the shimmer shapes
The shapes that shimmer in this effect are independent
from the actual content that eventually loads.
Therefore, the goal is to display shapes that represent
the eventual content as accurately as possible.
Displaying accurate shapes is easy in situations where the
content has a clear boundary. For example, in this recipe,
there are some circular images and some rounded rectangle images.
You can draw shapes that precisely match the outlines
of those images.
On the other hand, consider the text that appears beneath the
rounded rectangle images. You won't know how many lines of
text exist until the text loads.
Therefore, there is no point in trying to draw a rectangle
for every line of text. Instead, while the data is loading,
you draw a couple of very thin rounded rectangles that
represent the text that will appear. The shape and size
doesn't quite match, but that is OK.
Start with the circular list items at the top of the screen.
Ensure that each `CircleListItem` widget displays a circle
with a color while the image is loading.
<?code-excerpt "lib/main.dart (CircleListItem)"?>
```dart
class CircleListItem extends StatelessWidget {
const CircleListItem({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Container(
width: 54,
height: 54,
decoration: const BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
),
child: ClipOval(
child: Image.network(
'https://docs.flutter.dev/cookbook'
'/img-files/effects/split-check/Avatar1.jpg',
fit: BoxFit.cover,
),
),
),
);
}
}
```
As long as your widgets display some kind of shape,
you can apply the shimmer effect in this recipe.
Similar to the `CircleListItem` widgets,
ensure that the `CardListItem` widgets
display a color where the image will appear.
Also, in the `CardListItem` widget,
switch between the display of the text and
the rectangles based on the current loading status.
<?code-excerpt "lib/main.dart (CardListItem)"?>
```dart
class CardListItem extends StatelessWidget {
const CardListItem({
super.key,
required this.isLoading,
});
final bool isLoading;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildImage(),
const SizedBox(height: 16),
_buildText(),
],
),
);
}
Widget _buildImage() {
return AspectRatio(
aspectRatio: 16 / 9,
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network(
'https://docs.flutter.dev/cookbook'
'/img-files/effects/split-check/Food1.jpg',
fit: BoxFit.cover,
),
),
),
);
}
Widget _buildText() {
if (isLoading) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
height: 24,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
),
const SizedBox(height: 16),
Container(
width: 250,
height: 24,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
),
],
);
} else {
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 8),
child: Text(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do '
'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
),
);
}
}
}
```
Your UI now renders itself differently depending on
whether it's loading or loaded.
By temporarily commenting out the image URLs,
you can see the two ways your UI renders.
{:.site-mobile-screenshot}
The next goal is to paint all of the colored areas
with a single gradient that looks like a shimmer.
## Paint the shimmer gradient
The key to the effect achieved in this recipe is to use a widget
called [`ShaderMask`][]. The `ShaderMask` widget, as the name suggests,
applies a shader to its child, but only in the areas where
the child already painted something. For example,
you'll apply a shader to only the black shapes that you
configured earlier.
Define a chrome-colored, linear gradient that gets applied to the
shimmer shapes.
<?code-excerpt "lib/main.dart (shimmerGradient)"?>
```dart
const _shimmerGradient = LinearGradient(
colors: [
Color(0xFFEBEBF4),
Color(0xFFF4F4F4),
Color(0xFFEBEBF4),
],
stops: [
0.1,
0.3,
0.4,
],
begin: Alignment(-1.0, -0.3),
end: Alignment(1.0, 0.3),
tileMode: TileMode.clamp,
);
```
Define a new stateful widget called `ShimmerLoading`
that wraps a given `child` widget with a `ShaderMask`.
Configure the `ShaderMask` widget to apply the shimmer
gradient as a shader with a `blendMode` of `srcATop`.
The `srcATop` blend mode replaces any color that your
`child` widget painted with the shader color.
<?code-excerpt "lib/main.dart (ShimmerLoading)"?>
```dart
class ShimmerLoading extends StatefulWidget {
const ShimmerLoading({
super.key,
required this.isLoading,
required this.child,
});
final bool isLoading;
final Widget child;
@override
State<ShimmerLoading> createState() => _ShimmerLoadingState();
}
class _ShimmerLoadingState extends State<ShimmerLoading> {
@override
Widget build(BuildContext context) {
if (!widget.isLoading) {
return widget.child;
}
return ShaderMask(
blendMode: BlendMode.srcATop,
shaderCallback: (bounds) {
return _shimmerGradient.createShader(bounds);
},
child: widget.child,
);
}
}
```
Wrap your `CircleListItem` widgets with a `ShimmerLoading` widget.
<?code-excerpt "lib/shimmer_loading_items.dart (buildTopRowItem)"?>
```dart
Widget _buildTopRowItem() {
return ShimmerLoading(
isLoading: _isLoading,
child: const CircleListItem(),
);
}
```
Wrap your `CardListItem` widgets with a `ShimmerLoading` widget.
<?code-excerpt "lib/shimmer_loading_items.dart (buildListItem)"?>
```dart
Widget _buildListItem() {
return ShimmerLoading(
isLoading: _isLoading,
child: CardListItem(
isLoading: _isLoading,
),
);
}
```
When your shapes are loading, they now display
the shimmer gradient that is
returned from the `shaderCallback`.
This is a big step in the right direction,
but there's a problem with this gradient display.
Each `CircleListItem` widget and each `CardListItem` widget
displays a new version of the gradient.
For this recipe, the entire screen should
look like one, big shimmering surface.
You solve this problem in the next step.
## Paint one big shimmer
To paint one big shimmer across the screen,
each `ShimmerLoading` widget needs
to paint the same full-screen gradient based
on the position of that `ShimmerLoading`
widget on the screen.
To be more precise, rather than assume that the shimmer
should take up the entire screen,
there should be some area that shares the shimmer.
Maybe that area takes up the entire screen,
or maybe it doesn't. The way to solve this
kind of problem in Flutter is to define another widget
that sits above all of the `ShimmerLoading` widgets
in the widget tree, and call it `Shimmer`.
Then, each `ShimmerLoading` widget gets a reference
to the `Shimmer` ancestor
and requests the desired size and gradient to display.
Define a new stateful widget called `Shimmer` that
takes in a [`LinearGradient`][] and provides descendants
with access to its `State` object.
<?code-excerpt "lib/main.dart (Shimmer)"?>
```dart
class Shimmer extends StatefulWidget {
static ShimmerState? of(BuildContext context) {
return context.findAncestorStateOfType<ShimmerState>();
}
const Shimmer({
super.key,
required this.linearGradient,
this.child,
});
final LinearGradient linearGradient;
final Widget? child;
@override
ShimmerState createState() => ShimmerState();
}
class ShimmerState extends State<Shimmer> {
@override
Widget build(BuildContext context) {
return widget.child ?? const SizedBox();
}
}
```
Add methods to the `ShimmerState` class in order
to provide access to the `linearGradient`,
the size of the `ShimmerState`'s `RenderBox`,
and look up the position of a descendant within the
`ShimmerState`'s `RenderBox`.
<?code-excerpt "lib/shimmer_state.dart (ShimmerState)"?>
```dart
class ShimmerState extends State<Shimmer> {
Gradient get gradient => LinearGradient(
colors: widget.linearGradient.colors,
stops: widget.linearGradient.stops,
begin: widget.linearGradient.begin,
end: widget.linearGradient.end,
);
bool get isSized =>
(context.findRenderObject() as RenderBox?)?.hasSize ?? false;
Size get size => (context.findRenderObject() as RenderBox).size;
Offset getDescendantOffset({
required RenderBox descendant,
Offset offset = Offset.zero,
}) {
final shimmerBox = context.findRenderObject() as RenderBox;
return descendant.localToGlobal(offset, ancestor: shimmerBox);
}
@override
Widget build(BuildContext context) {
return widget.child ?? const SizedBox();
}
}
```
Wrap all of your screen's content with the `Shimmer` widget.
<?code-excerpt "lib/main.dart (ExampleUiAnimationState)"?>
```dart
class _ExampleUiLoadingAnimationState extends State<ExampleUiLoadingAnimation> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Shimmer(
linearGradient: _shimmerGradient,
child: ListView(
// ListView Contents
),
),
);
}
}
```
Use the `Shimmer` widget within your
`ShimmerLoading` widget to paint the shared gradient.
<?code-excerpt "lib/shimmer_loading_state_pt2.dart (ShimmerLoadingStatePt2)"?>
```dart
class _ShimmerLoadingState extends State<ShimmerLoading> {
@override
Widget build(BuildContext context) {
if (!widget.isLoading) {
return widget.child;
}
// Collect ancestor shimmer information.
final shimmer = Shimmer.of(context)!;
if (!shimmer.isSized) {
// The ancestor Shimmer widget isn't laid
// out yet. Return an empty box.
return const SizedBox();
}
final shimmerSize = shimmer.size;
final gradient = shimmer.gradient;
final offsetWithinShimmer = shimmer.getDescendantOffset(
descendant: context.findRenderObject() as RenderBox,
);
return ShaderMask(
blendMode: BlendMode.srcATop,
shaderCallback: (bounds) {
return gradient.createShader(
Rect.fromLTWH(
-offsetWithinShimmer.dx,
-offsetWithinShimmer.dy,
shimmerSize.width,
shimmerSize.height,
),
);
},
child: widget.child,
);
}
}
```
Your `ShimmerLoading` widgets now display a shared
gradient that takes up all of the space within the
`Shimmer` widget.
## Animate the shimmer
The shimmer gradient needs to move in order to
give the appearance of a shimmering shine.
The `LinearGradient` has a property called `transform`
that can be used to transform the appearance of the gradient,
for example, to move it horizontally.
The `transform` property accepts a `GradientTransform` instance.
Define a class called `_SlidingGradientTransform` that implements
`GradientTransform` to achieve the appearance of horizontal sliding.
<?code-excerpt "lib/original_example.dart (SlidingGradientTransform)"?>
```dart
class _SlidingGradientTransform extends GradientTransform {
const _SlidingGradientTransform({
required this.slidePercent,
});
final double slidePercent;
@override
Matrix4? transform(Rect bounds, {TextDirection? textDirection}) {
return Matrix4.translationValues(bounds.width * slidePercent, 0.0, 0.0);
}
}
```
The gradient slide percentage changes over time
in order to create the appearance of motion.
To change the percentage, configure an
[`AnimationController`][] in the `ShimmerState` class.
<?code-excerpt "lib/original_example.dart (ShimmerStateAnimation)" replace="/\/\/ code-excerpt-closing-bracket/}/g"?>
```dart
class ShimmerState extends State<Shimmer> with SingleTickerProviderStateMixin {
late AnimationController _shimmerController;
@override
void initState() {
super.initState();
_shimmerController = AnimationController.unbounded(vsync: this)
..repeat(min: -0.5, max: 1.5, period: const Duration(milliseconds: 1000));
}
@override
void dispose() {
_shimmerController.dispose();
super.dispose();
}
}
```
Apply the `_SlidingGradientTransform` to the `gradient`
by using the `_shimmerController`'s `value` as the `slidePercent`.
<?code-excerpt "lib/original_example.dart (LinearGradient)"?>
```dart
LinearGradient get gradient => LinearGradient(
colors: widget.linearGradient.colors,
stops: widget.linearGradient.stops,
begin: widget.linearGradient.begin,
end: widget.linearGradient.end,
transform:
_SlidingGradientTransform(slidePercent: _shimmerController.value),
);
```
The gradient now animates, but your individual
`ShimmerLoading` widgets don't repaint themselves
as the gradient changes. Therefore, it looks like nothing
is happening.
Expose the `_shimmerController` from `ShimmerState`
as a [`Listenable`][].
<?code-excerpt "lib/original_example.dart (shimmerChanges)"?>
```dart
Listenable get shimmerChanges => _shimmerController;
```
In `ShimmerLoading`, listen for changes to the ancestor
`ShimmerState`'s `shimmerChanges` property,
and repaint the shimmer gradient.
<?code-excerpt "lib/original_example.dart (ShimmerLoadingState)" replace="/\/\/ code-excerpt-closing-bracket/}/g"?>
```dart
class _ShimmerLoadingState extends State<ShimmerLoading> {
Listenable? _shimmerChanges;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_shimmerChanges != null) {
_shimmerChanges!.removeListener(_onShimmerChange);
}
_shimmerChanges = Shimmer.of(context)?.shimmerChanges;
if (_shimmerChanges != null) {
_shimmerChanges!.addListener(_onShimmerChange);
}
}
@override
void dispose() {
_shimmerChanges?.removeListener(_onShimmerChange);
super.dispose();
}
void _onShimmerChange() {
if (widget.isLoading) {
setState(() {
// update the shimmer painting.
});
}
}
}
```
Congratulations!
You now have a full-screen,
animated shimmer effect that turns
on and off as the content loads.
## Interactive example
<?code-excerpt "lib/original_example.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-interactive_example
import 'package:flutter/material.dart';
void main() {
runApp(
const MaterialApp(
home: ExampleUiLoadingAnimation(),
debugShowCheckedModeBanner: false,
),
);
}
const _shimmerGradient = LinearGradient(
colors: [
Color(0xFFEBEBF4),
Color(0xFFF4F4F4),
Color(0xFFEBEBF4),
],
stops: [
0.1,
0.3,
0.4,
],
begin: Alignment(-1.0, -0.3),
end: Alignment(1.0, 0.3),
tileMode: TileMode.clamp,
);
class ExampleUiLoadingAnimation extends StatefulWidget {
const ExampleUiLoadingAnimation({
super.key,
});
@override
State<ExampleUiLoadingAnimation> createState() =>
_ExampleUiLoadingAnimationState();
}
class _ExampleUiLoadingAnimationState extends State<ExampleUiLoadingAnimation> {
bool _isLoading = true;
void _toggleLoading() {
setState(() {
_isLoading = !_isLoading;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Shimmer(
linearGradient: _shimmerGradient,
child: ListView(
physics: _isLoading ? const NeverScrollableScrollPhysics() : null,
children: [
const SizedBox(height: 16),
_buildTopRowList(),
const SizedBox(height: 16),
_buildListItem(),
_buildListItem(),
_buildListItem(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggleLoading,
child: Icon(
_isLoading ? Icons.hourglass_full : Icons.hourglass_bottom,
),
),
);
}
Widget _buildTopRowList() {
return SizedBox(
height: 72,
child: ListView(
physics: _isLoading ? const NeverScrollableScrollPhysics() : null,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: [
const SizedBox(width: 16),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
_buildTopRowItem(),
],
),
);
}
Widget _buildTopRowItem() {
return ShimmerLoading(
isLoading: _isLoading,
child: const CircleListItem(),
);
}
Widget _buildListItem() {
return ShimmerLoading(
isLoading: _isLoading,
child: CardListItem(
isLoading: _isLoading,
),
);
}
}
class Shimmer extends StatefulWidget {
static ShimmerState? of(BuildContext context) {
return context.findAncestorStateOfType<ShimmerState>();
}
const Shimmer({
super.key,
required this.linearGradient,
this.child,
});
final LinearGradient linearGradient;
final Widget? child;
@override
ShimmerState createState() => ShimmerState();
}
class ShimmerState extends State<Shimmer> with SingleTickerProviderStateMixin {
late AnimationController _shimmerController;
@override
void initState() {
super.initState();
_shimmerController = AnimationController.unbounded(vsync: this)
..repeat(min: -0.5, max: 1.5, period: const Duration(milliseconds: 1000));
}
@override
void dispose() {
_shimmerController.dispose();
super.dispose();
}
// code-excerpt-closing-bracket
LinearGradient get gradient => LinearGradient(
colors: widget.linearGradient.colors,
stops: widget.linearGradient.stops,
begin: widget.linearGradient.begin,
end: widget.linearGradient.end,
transform:
_SlidingGradientTransform(slidePercent: _shimmerController.value),
);
bool get isSized =>
(context.findRenderObject() as RenderBox?)?.hasSize ?? false;
Size get size => (context.findRenderObject() as RenderBox).size;
Offset getDescendantOffset({
required RenderBox descendant,
Offset offset = Offset.zero,
}) {
final shimmerBox = context.findRenderObject() as RenderBox;
return descendant.localToGlobal(offset, ancestor: shimmerBox);
}
Listenable get shimmerChanges => _shimmerController;
@override
Widget build(BuildContext context) {
return widget.child ?? const SizedBox();
}
}
class _SlidingGradientTransform extends GradientTransform {
const _SlidingGradientTransform({
required this.slidePercent,
});
final double slidePercent;
@override
Matrix4? transform(Rect bounds, {TextDirection? textDirection}) {
return Matrix4.translationValues(bounds.width * slidePercent, 0.0, 0.0);
}
}
class ShimmerLoading extends StatefulWidget {
const ShimmerLoading({
super.key,
required this.isLoading,
required this.child,
});
final bool isLoading;
final Widget child;
@override
State<ShimmerLoading> createState() => _ShimmerLoadingState();
}
class _ShimmerLoadingState extends State<ShimmerLoading> {
Listenable? _shimmerChanges;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_shimmerChanges != null) {
_shimmerChanges!.removeListener(_onShimmerChange);
}
_shimmerChanges = Shimmer.of(context)?.shimmerChanges;
if (_shimmerChanges != null) {
_shimmerChanges!.addListener(_onShimmerChange);
}
}
@override
void dispose() {
_shimmerChanges?.removeListener(_onShimmerChange);
super.dispose();
}
void _onShimmerChange() {
if (widget.isLoading) {
setState(() {
// update the shimmer painting.
});
}
}
// code-excerpt-closing-bracket
@override
Widget build(BuildContext context) {
if (!widget.isLoading) {
return widget.child;
}
// Collect ancestor shimmer info.
final shimmer = Shimmer.of(context)!;
if (!shimmer.isSized) {
// The ancestor Shimmer widget has not laid
// itself out yet. Return an empty box.
return const SizedBox();
}
final shimmerSize = shimmer.size;
final gradient = shimmer.gradient;
final offsetWithinShimmer = shimmer.getDescendantOffset(
descendant: context.findRenderObject() as RenderBox,
);
return ShaderMask(
blendMode: BlendMode.srcATop,
shaderCallback: (bounds) {
return gradient.createShader(
Rect.fromLTWH(
-offsetWithinShimmer.dx,
-offsetWithinShimmer.dy,
shimmerSize.width,
shimmerSize.height,
),
);
},
child: widget.child,
);
}
}
//----------- List Items ---------
class CircleListItem extends StatelessWidget {
const CircleListItem({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Container(
width: 54,
height: 54,
decoration: const BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
),
child: ClipOval(
child: Image.network(
'https://docs.flutter.dev/cookbook'
'/img-files/effects/split-check/Avatar1.jpg',
fit: BoxFit.cover,
),
),
),
);
}
}
class CardListItem extends StatelessWidget {
const CardListItem({
super.key,
required this.isLoading,
});
final bool isLoading;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildImage(),
const SizedBox(height: 16),
_buildText(),
],
),
);
}
Widget _buildImage() {
return AspectRatio(
aspectRatio: 16 / 9,
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: Image.network(
'https://docs.flutter.dev/cookbook'
'/img-files/effects/split-check/Food1.jpg',
fit: BoxFit.cover,
),
),
),
);
}
Widget _buildText() {
if (isLoading) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
height: 24,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
),
const SizedBox(height: 16),
Container(
width: 250,
height: 24,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(16),
),
),
],
);
} else {
return const Padding(
padding: EdgeInsets.symmetric(horizontal: 8),
child: Text(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do '
'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
),
);
}
}
}
```
[`AnimationController`]: {{site.api}}/flutter/animation/AnimationController-class.html
[cloning the example code]: {{site.github}}/flutter/codelabs
[issue 44152]: {{site.repo.flutter}}/issues/44152
[`LinearGradient`]: {{site.api}}/flutter/painting/LinearGradient-class.html
[`Listenable`]: {{site.api}}/flutter/foundation/Listenable-class.html
[`ShaderMask`]: {{site.api}}/flutter/widgets/ShaderMask-class.html
| website/src/cookbook/effects/shimmer-loading.md/0 | {
"file_path": "website/src/cookbook/effects/shimmer-loading.md",
"repo_id": "website",
"token_count": 9658
} | 1,413 |
---
title: Fade in images with a placeholder
description: How to fade images into view.
---
<?code-excerpt path-base="cookbook/images/fading_in_images"?>
When displaying images using the default `Image` widget,
you might notice they simply pop onto the screen as they're loaded.
This might feel visually jarring to your users.
Instead, wouldn't it be nice to display a placeholder at first,
and images would fade in as they're loaded? Use the
[`FadeInImage`][] widget for exactly this purpose.
`FadeInImage` works with images of any type: in-memory, local assets,
or images from the internet.
## In-Memory
In this example, use the [`transparent_image`][]
package for a simple transparent placeholder.
<?code-excerpt "lib/memory_main.dart (MemoryNetwork)" replace="/^child\: //g"?>
```dart
FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/250?image=9',
),
```
### Complete example
<?code-excerpt "lib/memory_main.dart"?>
```dart
import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Fade in images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: Stack(
children: <Widget>[
const Center(child: CircularProgressIndicator()),
Center(
child: FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: 'https://picsum.photos/250?image=9',
),
),
],
),
),
);
}
}
```
{:.site-mobile-screenshot}
## From asset bundle
You can also consider using local assets for placeholders.
First, add the asset to the project's `pubspec.yaml` file
(for more details, see [Adding assets and images][]):
```diff
flutter:
assets:
+ - assets/loading.gif
```
Then, use the [`FadeInImage.assetNetwork()`][] constructor:
<?code-excerpt "lib/asset_main.dart (AssetNetwork)" replace="/^child\: //g"?>
```dart
FadeInImage.assetNetwork(
placeholder: 'assets/loading.gif',
image: 'https://picsum.photos/250?image=9',
),
```
### Complete example
<?code-excerpt "lib/asset_main.dart"?>
```dart
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'Fade in images';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: Center(
child: FadeInImage.assetNetwork(
placeholder: 'assets/loading.gif',
image: 'https://picsum.photos/250?image=9',
),
),
),
);
}
}
```
{:.site-mobile-screenshot}
[Adding assets and images]: /ui/assets/assets-and-images
[`FadeInImage`]: {{site.api}}/flutter/widgets/FadeInImage-class.html
[`FadeInImage.assetNetwork()`]: {{site.api}}/flutter/widgets/FadeInImage/FadeInImage.assetNetwork.html
[`transparent_image`]: {{site.pub-pkg}}/transparent_image
| website/src/cookbook/images/fading-in-images.md/0 | {
"file_path": "website/src/cookbook/images/fading-in-images.md",
"repo_id": "website",
"token_count": 1348
} | 1,414 |
---
title: Animate a widget across screens
description: How to animate a widget from one screen to another
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="cookbook/navigation/hero_animations"?>
It's often helpful to guide users through an app as they navigate from screen
to screen. A common technique to lead users through an app is to animate a
widget from one screen to the next. This creates a visual anchor connecting
the two screens.
Use the [`Hero`][] widget
to animate a widget from one screen to the next.
This recipe uses the following steps:
1. Create two screens showing the same image.
2. Add a `Hero` widget to the first screen.
3. Add a `Hero` widget to the second screen.
## 1. Create two screens showing the same image
In this example, display the same image on both screens.
Animate the image from the first screen to the second screen when
the user taps the image. For now, create the visual structure;
handle animations in the next steps.
{{site.alert.note}}
This example builds upon the
[Navigate to a new screen and back][]
and [Handle taps][] recipes.
{{site.alert.end}}
<?code-excerpt "lib/main_original.dart"?>
```dart
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',
),
),
),
);
}
}
```
## 2. Add a `Hero` widget to the first screen
To connect the two screens together with an animation, wrap
the `Image` widget on both screens in a `Hero` widget.
The `Hero` widget requires two arguments:
<dl>
<dt>`tag`</dt>
<dd>An object that identifies the `Hero`.
It must be the same on both screens.</dd>
<dt>`child`</dt>
<dd>The widget to animate across screens.</dd>
</dl>
{% comment %}
RegEx removes the first "child" property name and removed the trailing comma at the end
{% endcomment %}
<?code-excerpt "lib/main.dart (Hero1)" replace="/^child: //g;/,$//g"?>
```dart
Hero(
tag: 'imageHero',
child: Image.network(
'https://picsum.photos/250?image=9',
),
)
```
## 3. Add a `Hero` widget to the second screen
To complete the connection with the first screen,
wrap the `Image` on the second screen with a `Hero`
widget that has the same `tag` as the `Hero` in the first screen.
After applying the `Hero` widget to the second screen,
the animation between screens just works.
{% comment %}
RegEx removes the first "child" property name and removed the trailing comma at the end
{% endcomment %}
<?code-excerpt "lib/main.dart (Hero2)" replace="/^child: //g;/,$//g"?>
```dart
Hero(
tag: 'imageHero',
child: Image.network(
'https://picsum.photos/250?image=9',
),
)
```
{{site.alert.note}}
This code is identical to what you have on the first screen.
As a best practice, create a reusable widget instead of
repeating code. This example uses identical code for both
widgets, for simplicity.
{{site.alert.end}}
## 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 HeroApp());
class HeroApp extends StatelessWidget {
const HeroApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Transition Demo',
home: MainScreen(),
);
}
}
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: Hero(
tag: 'imageHero',
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: Hero(
tag: 'imageHero',
child: Image.network(
'https://picsum.photos/250?image=9',
),
),
),
),
);
}
}
```
<noscript>
<img src="/assets/images/docs/cookbook/hero.gif" alt="Hero demo" class="site-mobile-screenshot" />
</noscript>
[Handle taps]: /cookbook/gestures/handling-taps
[`Hero`]: {{site.api}}/flutter/widgets/Hero-class.html
[Navigate to a new screen and back]: /cookbook/navigation/navigation-basics
| website/src/cookbook/navigation/hero-animations.md/0 | {
"file_path": "website/src/cookbook/navigation/hero-animations.md",
"repo_id": "website",
"token_count": 2094
} | 1,415 |
---
title: Communicate with WebSockets
description: How to connect to a web socket.
---
<?code-excerpt path-base="cookbook/networking/web_sockets/"?>
In addition to normal HTTP requests,
you can connect to servers using `WebSockets`.
`WebSockets` allow for two-way communication with a server
without polling.
In this example, connect to a
[test WebSocket server sponsored by Lob.com][].
The server sends back the same message you send to it.
This recipe uses the following steps:
1. Connect to a WebSocket server.
2. Listen for messages from the server.
3. Send data to the server.
4. Close the WebSocket connection.
## 1. Connect to a WebSocket server
The [`web_socket_channel`][] package provides the
tools you need to connect to a WebSocket server.
The package provides a `WebSocketChannel`
that allows you to both listen for messages
from the server and push messages to the server.
In Flutter, use the following line to
create a `WebSocketChannel` that connects to a server:
<?code-excerpt "lib/main.dart (connect)" replace="/_channel/channel/g"?>
```dart
final channel = WebSocketChannel.connect(
Uri.parse('wss://echo.websocket.events'),
);
```
## 2. Listen for messages from the server
Now that you've established a connection,
listen to messages from the server.
After sending a message to the test server,
it sends the same message back.
In this example, use a [`StreamBuilder`][]
widget to listen for new messages, and a
[`Text`][] widget to display them.
<?code-excerpt "lib/main.dart (StreamBuilder)" replace="/_channel/channel/g"?>
```dart
StreamBuilder(
stream: channel.stream,
builder: (context, snapshot) {
return Text(snapshot.hasData ? '${snapshot.data}' : '');
},
)
```
### How this works
The `WebSocketChannel` provides a
[`Stream`][] of messages from the server.
The `Stream` class is a fundamental part of the `dart:async` package.
It provides a way to listen to async events from a data source.
Unlike `Future`, which returns a single async response,
the `Stream` class can deliver many events over time.
The [`StreamBuilder`][] widget connects to a `Stream`
and asks Flutter to rebuild every time it
receives an event using the given `builder()` function.
## 3. Send data to the server
To send data to the server,
`add()` messages to the `sink` provided
by the `WebSocketChannel`.
<?code-excerpt "lib/main.dart (add)" replace="/_channel/channel/g;/_controller.text/'Hello!'/g"?>
```dart
channel.sink.add('Hello!');
```
### How this works
The `WebSocketChannel` provides a
[`StreamSink`][] to push messages to the server.
The `StreamSink` class provides a general way to add sync or async
events to a data source.
## 4. Close the WebSocket connection
After you're done using the WebSocket, close the connection:
<?code-excerpt "lib/main.dart (close)" replace="/_channel/channel/g"?>
```dart
channel.sink.close();
```
## Complete example
<?code-excerpt "lib/main.dart"?>
```dart
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const title = 'WebSocket Demo';
return const MaterialApp(
title: title,
home: MyHomePage(
title: title,
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
required this.title,
});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController _controller = TextEditingController();
final _channel = WebSocketChannel.connect(
Uri.parse('wss://echo.websocket.events'),
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Form(
child: TextFormField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Send a message'),
),
),
const SizedBox(height: 24),
StreamBuilder(
stream: _channel.stream,
builder: (context, snapshot) {
return Text(snapshot.hasData ? '${snapshot.data}' : '');
},
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send message',
child: const Icon(Icons.send),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _sendMessage() {
if (_controller.text.isNotEmpty) {
_channel.sink.add(_controller.text);
}
}
@override
void dispose() {
_channel.sink.close();
_controller.dispose();
super.dispose();
}
}
```
{:.site-mobile-screenshot}
[`Stream`]: {{site.api}}/flutter/dart-async/Stream-class.html
[`StreamBuilder`]: {{site.api}}/flutter/widgets/StreamBuilder-class.html
[`StreamSink`]: {{site.api}}/flutter/dart-async/StreamSink-class.html
[test WebSocket server sponsored by Lob.com]: https://www.lob.com/blog/websocket-org-is-down-here-is-an-alternative
[`Text`]: {{site.api}}/flutter/widgets/Text-class.html
[`web_socket_channel`]: {{site.pub-pkg}}/web_socket_channel
| website/src/cookbook/networking/web-sockets.md/0 | {
"file_path": "website/src/cookbook/networking/web-sockets.md",
"repo_id": "website",
"token_count": 1989
} | 1,416 |
---
title: Find widgets
description: How to use the Finder classes for testing widgets.
---
<?code-excerpt path-base="cookbook/testing/widget/finders/"?>
{% assign api = site.api | append: '/flutter' -%}
To locate widgets in a test environment, use the [`Finder`][]
classes. While it's possible to write your own `Finder` classes,
it's generally more convenient to locate widgets using the tools
provided by the [`flutter_test`][] package.
During a `flutter run` session on a widget test, you can also
interactively tap parts of the screen for the Flutter tool to
print the suggested `Finder`.
This recipe looks at the [`find`][] constant provided by
the `flutter_test` package, and demonstrates how
to work with some of the `Finders` it provides.
For a full list of available finders,
see the [`CommonFinders` documentation][].
If you're unfamiliar with widget testing and the role of
`Finder` classes,
review the [Introduction to widget testing][] recipe.
This recipe uses the following steps:
1. Find a `Text` widget.
2. Find a widget with a specific `Key`.
3. Find a specific widget instance.
### 1. Find a `Text` widget
In testing, you often need to find widgets that contain specific text.
This is exactly what the `find.text()` method is for. It creates a
`Finder` that searches for widgets that display a specific `String` of text.
<?code-excerpt "test/finders_test.dart (test1)"?>
```dart
testWidgets('finds a Text widget', (tester) async {
// Build an App with a Text widget that displays the letter 'H'.
await tester.pumpWidget(const MaterialApp(
home: Scaffold(
body: Text('H'),
),
));
// Find a widget that displays the letter 'H'.
expect(find.text('H'), findsOneWidget);
});
```
### 2. Find a widget with a specific `Key`
In some cases, you might want to find a widget based on the Key that has been
provided to it. This can be handy if displaying multiple instances of the
same widget. For example, a `ListView` might display several
`Text` widgets that contain the same text.
In this case, provide a `Key` to each widget in the list. This allows
an app to uniquely identify a specific widget, making it easier to find
the widget in the test environment.
<?code-excerpt "test/finders_test.dart (test2)"?>
```dart
testWidgets('finds a widget using a Key', (tester) async {
// Define the test key.
const testKey = Key('K');
// Build a MaterialApp with the testKey.
await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));
// Find the MaterialApp widget using the testKey.
expect(find.byKey(testKey), findsOneWidget);
});
```
### 3. Find a specific widget instance
Finally, you might be interested in locating a specific instance of a widget.
For example, this can be useful when creating widgets that take a `child`
property and you want to ensure you're rendering the `child` widget.
<?code-excerpt "test/finders_test.dart (test3)"?>
```dart
testWidgets('finds a specific instance', (tester) async {
const childWidget = Padding(padding: EdgeInsets.zero);
// Provide the childWidget to the Container.
await tester.pumpWidget(Container(child: childWidget));
// Search for the childWidget in the tree and verify it exists.
expect(find.byWidget(childWidget), findsOneWidget);
});
```
### Summary
The `find` constant provided by the `flutter_test` package provides
several ways to locate widgets in the test environment. This recipe
demonstrated three of these methods, and several more methods exist
for different purposes.
If the above examples do not work for a particular use-case,
see the [`CommonFinders` documentation][]
to review all available methods.
### Complete example
<?code-excerpt "test/finders_test.dart"?>
```dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('finds a Text widget', (tester) async {
// Build an App with a Text widget that displays the letter 'H'.
await tester.pumpWidget(const MaterialApp(
home: Scaffold(
body: Text('H'),
),
));
// Find a widget that displays the letter 'H'.
expect(find.text('H'), findsOneWidget);
});
testWidgets('finds a widget using a Key', (tester) async {
// Define the test key.
const testKey = Key('K');
// Build a MaterialApp with the testKey.
await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));
// Find the MaterialApp widget using the testKey.
expect(find.byKey(testKey), findsOneWidget);
});
testWidgets('finds a specific instance', (tester) async {
const childWidget = Padding(padding: EdgeInsets.zero);
// Provide the childWidget to the Container.
await tester.pumpWidget(Container(child: childWidget));
// Search for the childWidget in the tree and verify it exists.
expect(find.byWidget(childWidget), findsOneWidget);
});
}
```
[`Finder`]: {{api}}/flutter_test/Finder-class.html
[`CommonFinders` documentation]: {{api}}/flutter_test/CommonFinders-class.html
[`find`]: {{api}}/flutter_test/find-constant.html
[`flutter_test`]: {{api}}/flutter_test/flutter_test-library.html
[Introduction to widget testing]: /cookbook/testing/widget/introduction
| website/src/cookbook/testing/widget/finders.md/0 | {
"file_path": "website/src/cookbook/testing/widget/finders.md",
"repo_id": "website",
"token_count": 1581
} | 1,417 |
---
title: State management
description: How to structure an app to manage the state of the data flowing through it.
next:
title: Start thinking declaratively
path: /development/data-and-backend/state-mgmt/declarative
---
{{site.alert.note}}
If you have written a mobile app using Flutter
and wonder why your app's state is lost
on a restart, check out [Restore state on Android][]
or [Restore state on iOS][].
{{site.alert.end}}
[Restore state on Android]: /platform-integration/android/restore-state-android
[Restore state on iOS]: /platform-integration/ios/restore-state-ios
_If you are already familiar with state management in reactive apps,
you can skip this section, though you might want to review the
[list of different approaches][]._
<img src='/assets/images/docs/development/data-and-backend/state-mgmt/state-management-explainer.gif' width="100%" alt="A short animated gif that shows the workings of a simple declarative state management system. This is explained in full in one of the following pages. Here it's just a decoration.">
{% comment %}
Source of the above animation tracked internally as b/122314402
{% endcomment %}
As you explore Flutter,
there comes a time when you need to share application
state between screens, across your app.
There are many approaches you can take,
and many questions to think about.
In the following pages,
you will learn the basics of dealing with state in Flutter apps.
[list of different approaches]: /data-and-backend/state-mgmt/options
| website/src/data-and-backend/state-mgmt/intro.md/0 | {
"file_path": "website/src/data-and-backend/state-mgmt/intro.md",
"repo_id": "website",
"token_count": 410
} | 1,418 |
---
title: Write your first Flutter app on the web
description: How to create a Flutter web app.
short-title: Write your first web app
js:
- defer: true
url: https://old-dartpad-3ce3f.web.app/inject_embed.dart.js
---
<?code-excerpt path-base="get-started/codelab_web"?>
{{site.alert.tip}}
This codelab walks you through writing
your first Flutter app on the web, specifically.
You might prefer to try
[another codelab][first_flutter_codelab]
that takes a more generic approach.
Note that the codelab on this page
does work on mobile and desktop
once you download and configure the appropriate tooling.
{{site.alert.end}}
<img src="/assets/images/docs/get-started/sign-up.gif" alt="The web app that you'll be building" class='site-image-right'>
This is a guide to creating your first Flutter **web** app.
If you are familiar with object-oriented programming,
and concepts such as variables, loops, and conditionals,
you can complete this tutorial.
You don't need previous experience with Dart,
mobile, or web programming.
## What you'll build
{:.no_toc}
You'll implement a simple web app that displays a sign in screen.
The screen contains three text fields: first name,
last name, and username. As the user fills out the fields,
a progress bar animates along the top of the sign in area.
When all three fields are filled in, the progress bar displays
in green along the full width of the sign in area,
and the **Sign up** button becomes enabled.
Clicking the **Sign up** button causes a welcome screen
to animate in from the bottom of the screen.
The animated GIF shows how the app works at the completion of this lab.
{{site.alert.secondary}}
<h4>What you'll learn</h4>
* How to write a Flutter app that looks natural on the web.
* Basic structure of a Flutter app.
* How to implement a Tween animation.
* How to implement a stateful widget.
* How to use the debugger to set breakpoints.
{{site.alert.end}}
{{site.alert.secondary}}
<h4>What you'll use</h4>
You need three pieces of software to complete this lab:
* [Flutter SDK][]
* [Chrome browser][]
* [Text editor or IDE][editor]
While developing, run your web app in Chrome
so you can debug with Dart DevTools.
{{site.alert.end}}
## Step 0: Get the starter web app
You'll start with a simple web app that we provide for you.
<ol markdown="1">
<li markdown="1">Enable web development.<br>
At the command line, perform the following command to
make sure that you have Flutter installed correctly.
```terminal
$ flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, 3.4.0-19.0.pre.254, on macOS 12.6 21G115
darwin-arm64, locale en)
[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 14.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.2)
[✓] VS Code (version 1.71.1)
[✓] Connected device (4 available)
[✓] HTTP Host Availability
• No issues found!
```
If you see "flutter: command not found",
then make sure that you have installed the
[Flutter SDK][] and that it's in your path.
It's okay if the Android toolchain, Android Studio,
and the Xcode tools aren't installed,
since the app is intended for the web only.
If you later want this app to work on mobile,
you'll need to do additional installation and setup.
</li>
<li markdown="1">List the devices.<br>
To ensure that web _is_ installed,
list the devices available.
You should see something like the following:
``` terminal
$ flutter devices
4 connected devices:
sdk gphone64 arm64 (mobile) • emulator-5554 •
android-arm64 • Android 13 (API 33) (emulator)
iPhone 14 Pro Max (mobile) • 45A72BE1-2D4E-4202-9BB3-D6AE2601BEF8 • ios
• com.apple.CoreSimulator.SimRuntime.iOS-16-0 (simulator)
macOS (desktop) • macos •
darwin-arm64 • macOS 12.6 21G115 darwin-arm64
Chrome (web) • chrome •
web-javascript • Google Chrome 105.0.5195.125
```
The **Chrome** device automatically starts Chrome and enables the use
of the Flutter DevTools tooling.
</li>
<li markdown="1">The starting app is displayed in the following DartPad.
<?code-excerpt "lib/starter.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-starting_code
import 'package:flutter/material.dart';
void main() => runApp(const SignUpApp());
class SignUpApp extends StatelessWidget {
const SignUpApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => const SignUpScreen(),
},
);
}
}
class SignUpScreen extends StatelessWidget {
const SignUpScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
body: const Center(
child: SizedBox(
width: 400,
child: Card(
child: SignUpForm(),
),
),
),
);
}
}
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _firstNameTextController = TextEditingController();
final _lastNameTextController = TextEditingController();
final _usernameTextController = TextEditingController();
double _formProgress = 0;
@override
Widget build(BuildContext context) {
return Form(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
LinearProgressIndicator(value: _formProgress),
Text('Sign up', style: Theme.of(context).textTheme.headlineMedium),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _firstNameTextController,
decoration: const InputDecoration(hintText: 'First name'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _lastNameTextController,
decoration: const InputDecoration(hintText: 'Last name'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _usernameTextController,
decoration: const InputDecoration(hintText: 'Username'),
),
),
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.white;
}),
backgroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.blue;
}),
),
onPressed: null,
child: const Text('Sign up'),
),
],
),
);
}
}
```
{{site.alert.important}}
This page uses an embedded version of [DartPad][]
to display examples and exercises.
If you see empty boxes instead of DartPads,
go to the [DartPad troubleshooting page][].
{{site.alert.end}}
</li>
<li markdown="1">Run the example.<br>
Click the **Run** button to run the example.
Note that you can type into the text fields,
but the **Sign up** button is disabled.
</li>
<li markdown="1">Copy the code.<br>
Click the clipboard icon in the upper right of the
code pane to copy the Dart code to your clipboard.
</li>
<li markdown="1">Create a new Flutter project.<br>
From your IDE, editor, or at the command line,
[create a new Flutter project][] and name it `signin_example`.
</li>
<li markdown="1">Replace the contents of `lib/main.dart`
with the contents of the clipboard.<br>
</li>
</ol>
### Observations
{:.no_toc}
* The entire code for this example lives in the
`lib/main.dart` file.
* If you know Java, the Dart language should feel very familiar.
* All of the app's UI is created in Dart code.
For more information, see [Introduction to declarative UI][].
* The app's UI adheres to [Material Design][],
a visual design language that runs on any device or platform.
You can customize the Material Design widgets,
but if you prefer something else,
Flutter also offers the Cupertino widget library,
which implements the current iOS design language.
Or you can create your own custom widget library.
* In Flutter, almost everything is a [Widget][].
Even the app itself is a widget.
The app's UI can be described as a widget tree.
## Step 1: Show the Welcome screen
The `SignUpForm` class is a stateful widget.
This simply means that the widget stores information
that can change, such as user input, or data from a feed.
Since widgets themselves are immutable
(can't be modified once created),
Flutter stores state information in a companion class,
called the `State` class. In this lab,
all of your edits will be made to the private
`_SignUpFormState` class.
{{site.alert.secondary}}
<h4>Fun fact</h4>
The Dart compiler enforces privacy for any identifier
prefixed with an underscore. For more information,
see the [Effective Dart Style Guide][].
{{site.alert.end}}
First, in your `lib/main.dart` file,
add the following class definition for the
`WelcomeScreen` widget after the `SignUpScreen` class:
<?code-excerpt "lib/step1.dart (WelcomeScreen)"?>
```dart
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
'Welcome!',
style: Theme.of(context).textTheme.displayMedium,
),
),
);
}
}
```
Next, you will enable the button to display the screen
and create a method to display it.
<ol markdown="1">
<li markdown="1"> Locate the `build()` method for the
`_SignUpFormState` class. This is the part of the code
that builds the SignUp button.
Notice how the button is defined:
It's a `TextButton` with a blue background,
white text that says **Sign up** and, when pressed,
does nothing.
</li>
<li markdown="1">Update the `onPressed` property.<br>
Change the `onPressed` property to call the (non-existent)
method that will display the welcome screen.
Change `onPressed: null` to the following:
<?code-excerpt "lib/step1.dart (onPressed)"?>
```dart
onPressed: _showWelcomeScreen,
```
</li>
<li markdown="1">Add the `_showWelcomeScreen` method.<br>
Fix the error reported by the analyzer that `_showWelcomeScreen`
is not defined. Directly above the `build()` method,
add the following function:
<?code-excerpt "lib/step1.dart (showWelcomeScreen)"?>
```dart
void _showWelcomeScreen() {
Navigator.of(context).pushNamed('/welcome');
}
```
</li>
<li markdown="1">Add the `/welcome` route.<br>
Create the connection to show the new screen.
In the `build()` method for `SignUpApp`,
add the following route below `'/'`:
<?code-excerpt "lib/step1.dart (WelcomeRoute)"?>
```dart
'/welcome': (context) => const WelcomeScreen(),
```
</li>
<li markdown="1">Run the app.<br>
The **Sign up** button should now be enabled.
Click it to bring up the welcome screen.
Note how it animates in from the bottom.
You get that behavior for free.
</li>
</ol>
### Observations
{:.no_toc}
* The `_showWelcomeScreen()` function is used in the `build()`
method as a callback function. Callback functions are often
used in Dart code and, in this case, this means
"call this method when the button is pressed".
* The `const` keyword in front of the constructor is very
important. When Flutter encounters a constant widget, it
short-circuits most of the rebuilding work under the hood
making the rendering more efficient.
* Flutter has only one `Navigator` object.
This widget manages Flutter's screens
(also called _routes_ or _pages_) inside a stack.
The screen at the top of the stack is the view that
is currently displayed. Pushing a new screen to this
stack switches the display to that new screen.
This is why the `_showWelcomeScreen` function pushes
the `WelcomeScreen` onto the Navigator's stack.
The user clicks the button and, voila,
the welcome screen appears. Likewise,
calling `pop()` on the `Navigator` returns to the
previous screen. Because Flutter's navigation is
integrated into the browser's navigation,
this happens implicitly when clicking the browser's
back arrow button.
## Step 2: Enable sign in progress tracking
This sign in screen has three fields.
Next, you will enable the ability to track the
user's progress on filling in the form fields,
and update the app's UI when the form is complete.
{{site.alert.note}}
This example does **not** validate the accuracy of the user input.
That is something you can add later using form validation, if you like.
{{site.alert.end}}
<ol markdown="1">
<li markdown="1">Add a method to update `_formProgress`.
In the `_SignUpFormState` class, add a new method called
`_updateFormProgress()`:
<?code-excerpt "lib/step2.dart (updateFormProgress)"?>
```dart
void _updateFormProgress() {
var progress = 0.0;
final controllers = [
_firstNameTextController,
_lastNameTextController,
_usernameTextController
];
for (final controller in controllers) {
if (controller.value.text.isNotEmpty) {
progress += 1 / controllers.length;
}
}
setState(() {
_formProgress = progress;
});
}
```
This method updates the `_formProgress` field based on the
the number of non-empty text fields.
</li>
<li markdown="1">Call `_updateFormProgress` when the form
changes.<br>
In the `build()` method of the `_SignUpFormState` class,
add a callback to the `Form` widget's `onChanged` argument.
Add the code below marked as NEW:
<?code-excerpt "lib/step2.dart (onChanged)"?>
```dart
return Form(
onChanged: _updateFormProgress, // NEW
child: Column(
```
</li>
<li markdown="1">Update the `onPressed` property (again).<br>
In `step 1`, you modified the `onPressed` property for the
**Sign up** button to display the welcome screen.
Now, update that button to display the welcome
screen only when the form is completely filled in:
<?code-excerpt "lib/step2.dart (onPressed)"?>
```dart
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.white;
}),
backgroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.blue;
}),
),
onPressed:
_formProgress == 1 ? _showWelcomeScreen : null, // UPDATED
child: const Text('Sign up'),
),
```
</li>
<li markdown="1">Run the app.<br>
The **Sign up** button is initially disabled,
but becomes enabled when all three text fields contain
(any) text.
</li>
</ol>
### Observations
{:.no_toc}
* Calling a widget's `setState()` method tells Flutter that the
widget needs to be updated on screen.
The framework then disposes of the previous immutable widget
(and its children), creates a new one
(with its accompanying child widget tree),
and renders it to screen. For this to work seamlessly,
Flutter needs to be fast.
The new widget tree must be created and rendered to screen
in less than 1/60th of a second to create a smooth visual
transition—especially for an animation.
Luckily Flutter _is_ fast.
* The `progress` field is defined as a floating value,
and is updated in the `_updateFormProgress` method.
When all three fields are filled in, `_formProgress` is set to 1.0.
When `_formProgress` is set to 1.0, the `onPressed` callback is set to the
`_showWelcomeScreen` method. Now that its `onPressed` argument is non-null, the button is enabled.
Like most Material Design buttons in Flutter,
[TextButton][]s are disabled by default if their `onPressed` and `onLongPress` callbacks are null.
* Notice that the `_updateFormProgress` passes a function to `setState()`.
This is called an anonymous
function and has the following syntax:
```dart
methodName(() {...});
```
Where `methodName` is a named function that takes an anonymous
callback function as an argument.
* The Dart syntax in the last step that displays the
welcome screen is:
<?code-excerpt "lib/step2.dart (ternary)" replace="/, \/\/ UPDATED//g"?>
```dart
_formProgress == 1 ? _showWelcomeScreen : null
```
This is a Dart conditional assignment and has the syntax:
`condition ? expression1 : expression2`.
If the expression `_formProgress == 1` is true, the entire expression results
in the value on the left hand side of the `:`, which is the
`_showWelcomeScreen` method in this case.
## Step 2.5: Launch Dart DevTools
How do you debug a Flutter web app?
It's not too different from debugging any Flutter app.
You want to use [Dart DevTools][]!
(Not to be confused with Chrome DevTools.)
Our app currently has no bugs, but let's check it out anyway.
The following instructions for launching DevTools applies to any workflow,
but there is a shortcut if you're using IntelliJ.
See the tip at the end of this section for more information.
<ol markdown="1">
<li markdown="1">Run the app.<br>
If your app isn't currently running, launch it.
Select the **Chrome** device from the pull down
and launch it from your IDE or,
from the command line, use `flutter run -d chrome`,
</li>
<li markdown="1">Get the web socket info for DevTools.<br>
At the command line, or in the IDE,
you should see a message stating something like the following:
<pre>
Launching lib/main.dart on Chrome in debug mode...
Building application for the web... 11.7s
Attempting to connect to browser instance..
Debug service listening on <b>ws://127.0.0.1:54998/pJqWWxNv92s=</b>
</pre>
Copy the address of the debug service, shown in bold.
You will need that to launch DevTools.
</li>
<li markdown="1">Ensure that DevTools is installed.<br>
Do you have [DevTools installed][]?
If you are using an IDE,
make sure you have the Flutter and Dart plugins set up,
as described in the [VS Code][] and
[Android Studio and IntelliJ][] pages.
If you are working at the command line,
launch the DevTools server as explained in the
[DevTools command line][] page.
</li>
<li markdown="1">Connect to DevTools.<br>
When DevTools launches, you should see something
like the following:
```terminal
Serving DevTools at http://127.0.0.1:9100
```
Go to this URL in a Chrome browser. You should see the DevTools
launch screen. It should look like the following:
{% indent %}
{:width="100%"}
{% endindent %}
</li>
<li markdown="1">Connect to running app.<br>
Under **Connect to a running site**,
paste the ws location that you copied in step 2,
and click Connect. You should now see Dart DevTools
running successfully in your Chrome browser:
{% indent %}
{:width="100%"}
{% endindent %}
Congratulations, you are now running Dart DevTools!
</li>
</ol>
{{site.alert.note}}
This is not the only way to launch DevTools.
If you are using IntelliJ,
you can open DevTools by going to
**Flutter Inspector** -> **More Actions** -> **Open DevTools**:
{% indent %}
{:width="100%"}
{% endindent %}
{{site.alert.end}}
<ol markdown="1">
<li markdown="1">Set a breakpoint.<br>
Now that you have DevTools running,
select the **Debugger** tab in the blue bar along the top.
The debugger pane appears and, in the lower left,
see a list of libraries used in the example.
Select `lib/main.dart` to display your Dart code
in the center pane.
{% indent %}
{:width="100%"}
{% endindent %}
</li>
<li markdown="1">Set a breakpoint.<br>
In the Dart code,
scroll down to where `progress` is updated:
<?code-excerpt "lib/step2.dart (forLoop)"?>
```dart
for (final controller in controllers) {
if (controller.value.text.isNotEmpty) {
progress += 1 / controllers.length;
}
}
```
Place a breakpoint on the line with the for loop by clicking to the
left of the line number. The breakpoint now appears
in the **Breakpoints** section to the left of the window.
</li>
<li markdown="1">Trigger the breakpoint.<br>
In the running app, click one of the text fields to gain focus.
The app hits the breakpoint and pauses.
In the DevTools screen, you can see on the left
the value of `progress`, which is 0. This is to be expected,
since none of the fields are filled in.
Step through the for loop to see
the program execution.
</li>
<li markdown="1">Resume the app.<br>
Resume the app by clicking the green **Resume**
button in the DevTools window.
</li>
<li markdown="1">Delete the breakpoint.<br>
Delete the breakpoint by clicking it again, and resume the app.
</li>
</ol>
This gives you a tiny glimpse of what is possible using DevTools,
but there is lots more! For more information,
see the [DevTools documentation][].
## Step 3: Add animation for sign in progress
It's time to add animation! In this final step,
you'll create the animation for the
`LinearProgressIndicator` at the top of the sign in
area. The animation has the following behavior:
* When the app starts,
a tiny red bar appears across the top of the sign in area.
* When one text field contains text,
the red bar turns orange and animates 0.15
of the way across the sign in area.
* When two text fields contain text,
the orange bar turns yellow and animates half
of the way across the sign in area.
* When all three text fields contain text,
the orange bar turns green and animates all the
way across the sign in area.
Also, the **Sign up** button becomes enabled.
<ol markdown="1">
<li markdown="1">Add an `AnimatedProgressIndicator`.<br>
At the bottom of the file, add this widget:
<?code-excerpt "lib/step3.dart (AnimatedProgressIndicator)"?>
```dart
class AnimatedProgressIndicator extends StatefulWidget {
final double value;
const AnimatedProgressIndicator({
super.key,
required this.value,
});
@override
State<AnimatedProgressIndicator> createState() {
return _AnimatedProgressIndicatorState();
}
}
class _AnimatedProgressIndicatorState extends State<AnimatedProgressIndicator>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Color?> _colorAnimation;
late Animation<double> _curveAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 1200),
vsync: this,
);
final colorTween = TweenSequence([
TweenSequenceItem(
tween: ColorTween(begin: Colors.red, end: Colors.orange),
weight: 1,
),
TweenSequenceItem(
tween: ColorTween(begin: Colors.orange, end: Colors.yellow),
weight: 1,
),
TweenSequenceItem(
tween: ColorTween(begin: Colors.yellow, end: Colors.green),
weight: 1,
),
]);
_colorAnimation = _controller.drive(colorTween);
_curveAnimation = _controller.drive(CurveTween(curve: Curves.easeIn));
}
@override
void didUpdateWidget(oldWidget) {
super.didUpdateWidget(oldWidget);
_controller.animateTo(widget.value);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) => LinearProgressIndicator(
value: _curveAnimation.value,
valueColor: _colorAnimation,
backgroundColor: _colorAnimation.value?.withOpacity(0.4),
),
);
}
}
```
The [`didUpdateWidget`][] function updates
the `AnimatedProgressIndicatorState` whenever
`AnimatedProgressIndicator` changes.
</li>
<li markdown="1">Use the new `AnimatedProgressIndicator`.<br>
Then, replace the `LinearProgressIndicator` in the `Form`
with this new `AnimatedProgressIndicator`:
<?code-excerpt "lib/step3.dart (UseAnimatedProgressIndicator)"?>
```dart
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedProgressIndicator(value: _formProgress), // NEW
Text('Sign up', style: Theme.of(context).textTheme.headlineMedium),
Padding(
```
This widget uses an `AnimatedBuilder` to animate the
progress indicator to the latest value.
</li>
<li markdown="1">Run the app.<br>
Type anything into the three fields to verify that
the animation works, and that clicking the
**Sign up** button brings up the **Welcome** screen.
</li>
</ol>
### Complete sample
<?code-excerpt "lib/main.dart"?>
```run-dartpad:theme-light:mode-flutter:run-true:width-100%:height-600px:split-60:ga_id-starting_code
import 'package:flutter/material.dart';
void main() => runApp(const SignUpApp());
class SignUpApp extends StatelessWidget {
const SignUpApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => const SignUpScreen(),
'/welcome': (context) => const WelcomeScreen(),
},
);
}
}
class SignUpScreen extends StatelessWidget {
const SignUpScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
body: const Center(
child: SizedBox(
width: 400,
child: Card(
child: SignUpForm(),
),
),
),
);
}
}
class WelcomeScreen extends StatelessWidget {
const WelcomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(
'Welcome!',
style: Theme.of(context).textTheme.displayMedium,
),
),
);
}
}
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _firstNameTextController = TextEditingController();
final _lastNameTextController = TextEditingController();
final _usernameTextController = TextEditingController();
double _formProgress = 0;
void _updateFormProgress() {
var progress = 0.0;
final controllers = [
_firstNameTextController,
_lastNameTextController,
_usernameTextController
];
for (final controller in controllers) {
if (controller.value.text.isNotEmpty) {
progress += 1 / controllers.length;
}
}
setState(() {
_formProgress = progress;
});
}
void _showWelcomeScreen() {
Navigator.of(context).pushNamed('/welcome');
}
@override
Widget build(BuildContext context) {
return Form(
onChanged: _updateFormProgress,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedProgressIndicator(value: _formProgress),
Text('Sign up', style: Theme.of(context).textTheme.headlineMedium),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _firstNameTextController,
decoration: const InputDecoration(hintText: 'First name'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _lastNameTextController,
decoration: const InputDecoration(hintText: 'Last name'),
),
),
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
controller: _usernameTextController,
decoration: const InputDecoration(hintText: 'Username'),
),
),
TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.white;
}),
backgroundColor: MaterialStateProperty.resolveWith((states) {
return states.contains(MaterialState.disabled)
? null
: Colors.blue;
}),
),
onPressed: _formProgress == 1 ? _showWelcomeScreen : null,
child: const Text('Sign up'),
),
],
),
);
}
}
class AnimatedProgressIndicator extends StatefulWidget {
final double value;
const AnimatedProgressIndicator({
super.key,
required this.value,
});
@override
State<AnimatedProgressIndicator> createState() {
return _AnimatedProgressIndicatorState();
}
}
class _AnimatedProgressIndicatorState extends State<AnimatedProgressIndicator>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Color?> _colorAnimation;
late Animation<double> _curveAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 1200),
vsync: this,
);
final colorTween = TweenSequence([
TweenSequenceItem(
tween: ColorTween(begin: Colors.red, end: Colors.orange),
weight: 1,
),
TweenSequenceItem(
tween: ColorTween(begin: Colors.orange, end: Colors.yellow),
weight: 1,
),
TweenSequenceItem(
tween: ColorTween(begin: Colors.yellow, end: Colors.green),
weight: 1,
),
]);
_colorAnimation = _controller.drive(colorTween);
_curveAnimation = _controller.drive(CurveTween(curve: Curves.easeIn));
}
@override
void didUpdateWidget(oldWidget) {
super.didUpdateWidget(oldWidget);
_controller.animateTo(widget.value);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) => LinearProgressIndicator(
value: _curveAnimation.value,
valueColor: _colorAnimation,
backgroundColor: _colorAnimation.value?.withOpacity(0.4),
),
);
}
}
```
### Observations
{:.no_toc}
* You can use an `AnimationController` to run any animation.
* `AnimatedBuilder` rebuilds the widget tree when the value
of an `Animation` changes.
* Using a `Tween`, you can interpolate between almost any value,
in this case, `Color`.
## What next?
Congratulations!
You have created your first web app using Flutter!
If you'd like to continue playing with this example,
perhaps you could add form validation.
For advice on how to do this,
see the [Building a form with validation][]
recipe in the [Flutter cookbook][].
For more information on Flutter web apps,
Dart DevTools, or Flutter animations, see the following:
* [Animation docs][]
* [Dart DevTools][]
* [Implicit animations][] codelab
* [Web samples][]
[Android Studio and IntelliJ]: /tools/devtools/android-studio
[Animation docs]: /ui/animations
[Building a form with validation]: /cookbook/forms/validation
[Chrome browser]: https://www.google.com/chrome/?brand=CHBD&gclid=CjwKCAiAws7uBRAkEiwAMlbZjlVMZCxJDGAHjoSpoI_3z_HczSbgbMka5c9Z521R89cDoBM3zAluJRoCdCEQAvD_BwE&gclsrc=aw.ds
[create a new Flutter project]: /get-started/test-drive
[Dart DevTools]: /tools/devtools/overview
[DartPad]: {{site.dartpad}}
[DevTools command line]: /tools/devtools/cli
[DevTools documentation]: /tools/devtools
[DevTools installed]: /tools/devtools/overview#start
[DartPad troubleshooting page]: {{site.dart-site}}/tools/dartpad/troubleshoot
[`didUpdateWidget`]: {{site.api}}/flutter/widgets/State/didUpdateWidget.html
[editor]: /get-started/editor
[Effective Dart Style Guide]: {{site.dart-site}}/guides/language/effective-dart/style#dont-use-a-leading-underscore-for-identifiers-that-arent-private
[Flutter cookbook]: /cookbook
[Flutter SDK]: /get-started/install
[Implicit animations]: /codelabs/implicit-animations
[Introduction to declarative UI]: /get-started/flutter-for/declarative
[Material Design]: {{site.material}}/get-started
[TextButton]: {{site.api}}/flutter/material/TextButton-class.html
[VS Code]: /tools/devtools/vscode
[Web samples]: {{site.repo.samples}}/tree/main/web
[Widget]: {{site.api}}/flutter/widgets/Widget-class.html
[first_flutter_codelab]: /get-started/codelab
| website/src/get-started/codelab-web.md/0 | {
"file_path": "website/src/get-started/codelab-web.md",
"repo_id": "website",
"token_count": 11286
} | 1,419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.