text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources> | samples/add_to_app/android_view/android_view/app/src/main/res/values/colors.xml/0 | {
"file_path": "samples/add_to_app/android_view/android_view/app/src/main/res/values/colors.xml",
"repo_id": "samples",
"token_count": 161
} | 1,312 |
name: flutter_module_using_plugin
description: An example Flutter module that uses a plugin.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
provider: ^6.0.2
url_launcher: ^6.0.6
sensors: ^2.0.3
dev_dependencies:
analysis_defaults:
path: ../../../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
# This section identifies your Flutter project as a module meant for
# embedding in a native host app. These identifiers should _not_ ordinarily
# be changed after generation - they are used to ensure that the tooling can
# maintain consistency when adding or modifying assets and plugins.
# They also do not have any bearing on your native host application's
# identifiers, which may be completely independent or the same as these.
module:
androidX: true
androidPackage: dev.flutter.example.flutter_module_using_plugin
iosBundleIdentifier: dev.flutter.example.flutterModuleUsingPlugin
| samples/add_to_app/android_view/flutter_module_using_plugin/pubspec.yaml/0 | {
"file_path": "samples/add_to_app/android_view/flutter_module_using_plugin/pubspec.yaml",
"repo_id": "samples",
"token_count": 314
} | 1,313 |
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
app:liftOnScroll="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
<LinearLayout
android:id="@+id/list"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity" />
</androidx.core.widget.NestedScrollView>
<ProgressBar
android:id="@+id/spinner"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
app:layout_anchor="@+id/nestedScrollView"
app:layout_anchorGravity="center" />
</androidx.coordinatorlayout.widget.CoordinatorLayout> | samples/add_to_app/books/android_books/app/src/main/res/layout/activity_main.xml/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/res/layout/activity_main.xml",
"repo_id": "samples",
"token_count": 640
} | 1,314 |
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources> | samples/add_to_app/books/android_books/app/src/main/res/values/styles.xml/0 | {
"file_path": "samples/add_to_app/books/android_books/app/src/main/res/values/styles.xml",
"repo_id": "samples",
"token_count": 140
} | 1,315 |
// 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_module_books/api.dart';
import 'package:flutter_module_books/main.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Pressing clear calls the cancel API', (tester) async {
MockHostBookApi mockHostApi = MockHostBookApi();
await tester.pumpWidget(
MaterialApp(
home: BookDetail(hostApi: mockHostApi),
),
);
await tester.tap(find.byIcon(Icons.clear));
expect(mockHostApi.cancelCalls, 1);
});
testWidgets('Pressing done calls the finish editing API', (tester) async {
MockHostBookApi mockHostApi = MockHostBookApi();
await tester.pumpWidget(
MaterialApp(
home: BookDetail(book: Book(), hostApi: mockHostApi),
),
);
await tester.tap(find.byIcon(Icons.check));
expect(mockHostApi.booksFinished.length, 1);
});
}
// A super-simple mock for testing that calls are made to the API.
class MockHostBookApi implements HostBookApi {
int cancelCalls = 0;
final booksFinished = <Book>[];
@override
Future<void> cancel() async {
cancelCalls++;
}
@override
Future<void> finishEditingBook(Book arg) async {
booksFinished.add(arg);
}
}
| samples/add_to_app/books/flutter_module_books/test/widget_test.dart/0 | {
"file_path": "samples/add_to_app/books/flutter_module_books/test/widget_test.dart",
"repo_id": "samples",
"token_count": 514
} | 1,316 |
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "api.h"
| samples/add_to_app/books/ios_books/IosBooks/IosBooks-Bridging-Header.h/0 | {
"file_path": "samples/add_to_app/books/ios_books/IosBooks/IosBooks-Bridging-Header.h",
"repo_id": "samples",
"token_count": 35
} | 1,317 |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeWidth="1"
android:strokeColor="#00000000">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>
| samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/drawable-v24/ic_launcher_foreground.xml/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/drawable-v24/ic_launcher_foreground.xml",
"repo_id": "samples",
"token_count": 1063
} | 1,318 |
<resources>
<string name="app_name">AndroidFullScreen</string>
</resources>
| samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/values/strings.xml/0 | {
"file_path": "samples/add_to_app/fullscreen/android_fullscreen/app/src/main/res/values/strings.xml",
"repo_id": "samples",
"token_count": 26
} | 1,319 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_module/main.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
class MockCounterModel extends ChangeNotifier implements CounterModel {
int _count = 0;
@override
int get count => _count;
@override
void increment() {
_count++;
notifyListeners();
}
}
void main() {
testWidgets('MiniView smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(
MaterialApp(
home: ChangeNotifierProvider<CounterModel>.value(
value: MockCounterModel(),
child: const Contents(),
),
),
);
// Verify that our counter starts at 0.
expect(find.text('Taps: 0'), findsOneWidget);
expect(find.text('Taps: 1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.text('Tap me!'));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('Taps: 0'), findsNothing);
expect(find.text('Taps: 1'), findsOneWidget);
});
}
| samples/add_to_app/fullscreen/flutter_module/test/widget_test.dart/0 | {
"file_path": "samples/add_to_app/fullscreen/flutter_module/test/widget_test.dart",
"repo_id": "samples",
"token_count": 450
} | 1,320 |
package dev.flutter.multipleflutters
import android.content.Intent
import android.os.Bundle
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import io.flutter.embedding.android.FlutterFragment
import io.flutter.embedding.engine.FlutterEngineCache
/**
* An activity that displays 2 FlutterFragments vertically.
*/
class DoubleFlutterActivity : FragmentActivity(), EngineBindingsDelegate {
private val topBindings: EngineBindings by lazy {
EngineBindings(activity = this, delegate = this, entrypoint = "topMain")
}
private val bottomBindings: EngineBindings by lazy {
EngineBindings(activity = this, delegate = this, entrypoint = "bottomMain")
}
private val numberOfFlutters = 2
private val engineCountStart : Int
private companion object {
var engineCounter = 0
}
init {
engineCountStart = engineCounter
engineCounter += numberOfFlutters
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val root = LinearLayout(this)
root.layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
root.orientation = LinearLayout.VERTICAL
root.weightSum = numberOfFlutters.toFloat()
val fragmentManager: FragmentManager = supportFragmentManager
setContentView(root)
for (i in 0 until numberOfFlutters) {
val engineId = engineCountStart + i
val containerId = 12345 + engineId
val flutterContainer = FrameLayout(this)
root.addView(flutterContainer)
flutterContainer.id = containerId
flutterContainer.layoutParams = LinearLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT,
1.0f
)
val engine = if (i == 0) topBindings.engine else bottomBindings.engine
FlutterEngineCache.getInstance().put(engineId.toString(), engine)
val flutterFragment =
FlutterFragment.withCachedEngine(engineId.toString()).build<FlutterFragment>()
fragmentManager
.beginTransaction()
.add(
containerId,
flutterFragment
)
.commit()
}
topBindings.attach()
bottomBindings.attach()
}
override fun onDestroy() {
for (i in 0 until numberOfFlutters) {
val engineId = engineCountStart + i
FlutterEngineCache.getInstance().remove(engineId.toString())
}
super.onDestroy()
bottomBindings.detach()
topBindings.detach()
}
override fun onNext() {
val flutterIntent = Intent(this, MainActivity::class.java)
startActivity(flutterIntent)
}
}
| samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/DoubleFlutterActivity.kt/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_android/app/src/main/java/dev/flutter/multipleflutters/DoubleFlutterActivity.kt",
"repo_id": "samples",
"token_count": 1271
} | 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.
flutter_application_path = '../multiple_flutters_module'
load File.join(flutter_application_path, '.ios', 'Flutter', 'podhelper.rb')
target 'MultipleFluttersIos' do
use_frameworks!
install_all_flutter_pods(flutter_application_path)
end
post_install do |installer|
flutter_post_install(installer) if defined?(flutter_post_install)
end
| samples/add_to_app/multiple_flutters/multiple_flutters_ios/Podfile/0 | {
"file_path": "samples/add_to_app/multiple_flutters/multiple_flutters_ios/Podfile",
"repo_id": "samples",
"token_count": 160
} | 1,322 |
<resources>
<string name="app_name">AndroidUsingPrebuiltModule</string>
</resources>
| samples/add_to_app/prebuilt_module/android_using_prebuilt_module/app/src/main/res/values/strings.xml/0 | {
"file_path": "samples/add_to_app/prebuilt_module/android_using_prebuilt_module/app/src/main/res/values/strings.xml",
"repo_id": "samples",
"token_count": 28
} | 1,323 |
name: splash_screen_sample
description: A sample Flutter app with animated splash screen on Android 12.
publish_to: "none"
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/androidIcon.png
| samples/android_splash_screen/pubspec.yaml/0 | {
"file_path": "samples/android_splash_screen/pubspec.yaml",
"repo_id": "samples",
"token_count": 150
} | 1,324 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class TweenDemo extends StatefulWidget {
const TweenDemo({super.key});
static const String routeName = 'basics/tweens';
@override
State<TweenDemo> createState() => _TweenDemoState();
}
class _TweenDemoState extends State<TweenDemo>
with SingleTickerProviderStateMixin {
static const Duration _duration = Duration(seconds: 1);
static const double accountBalance = 1000000;
late final AnimationController controller;
late final Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(vsync: this, duration: _duration)
..addListener(() {
// Marks the widget tree as dirty
setState(() {});
});
animation = Tween(begin: 0.0, end: accountBalance).animate(controller);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Tweens'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 200),
child: Text('\$${animation.value.toStringAsFixed(2)}',
style: const TextStyle(fontSize: 24)),
),
ElevatedButton(
child: Text(
switch (controller.status) {
AnimationStatus.completed => 'Buy a Mansion',
AnimationStatus.forward => 'Accruing...',
AnimationStatus.reverse => 'Spending...',
_ => 'Win the lottery',
},
),
onPressed: () {
switch (controller.status) {
case AnimationStatus.completed:
controller.reverse();
default:
controller.forward();
}
},
)
],
),
),
);
}
}
| samples/animations/lib/src/basics/tweens.dart/0 | {
"file_path": "samples/animations/lib/src/basics/tweens.dart",
"repo_id": "samples",
"token_count": 997
} | 1,325 |
## 1.0.0
- Initial version.
| samples/code_sharing/server/CHANGELOG.md/0 | {
"file_path": "samples/code_sharing/server/CHANGELOG.md",
"repo_id": "samples",
"token_count": 13
} | 1,326 |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'constants.dart';
import 'context_menu_region.dart';
import 'platform_selector.dart';
// This example is based on the MenuBar docs example:
// https://master-api.flutter.dev/flutter/material/MenuBar-class.html
class CascadingMenuPage extends StatelessWidget {
const CascadingMenuPage({
super.key,
required this.onChangedPlatform,
});
static const String route = 'cascading';
static const String title = 'Cascading Menu Example';
static const String subtitle = 'A context menu with nested submenus.';
final PlatformCallback onChangedPlatform;
static const String url = '$kCodeUrl/anywhere_page.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(CascadingMenuPage.title),
actions: <Widget>[
PlatformSelector(
onChangedPlatform: onChangedPlatform,
),
IconButton(
icon: const Icon(Icons.code),
onPressed: () async {
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
),
],
),
body: const _MyContextMenuRegion(),
);
}
}
class _MyContextMenuRegion extends StatefulWidget {
const _MyContextMenuRegion();
@override
State<_MyContextMenuRegion> createState() => _MyContextMenuRegionState();
}
class _MyContextMenuRegionState extends State<_MyContextMenuRegion> {
String? _lastSelection;
Color get backgroundColor => _backgroundColor;
Color _backgroundColor = Colors.red;
set backgroundColor(Color value) {
if (_backgroundColor != value) {
setState(() {
_backgroundColor = value;
});
}
}
bool get showingMessage => _showMessage;
bool _showMessage = true;
set showingMessage(bool value) {
if (_showMessage != value) {
setState(() {
_showMessage = value;
});
}
}
@override
Widget build(BuildContext context) {
return ContextMenuRegion(
contextMenuBuilder: (context, primaryAnchor, [secondaryAnchor]) {
return _MyCascadingContextMenu(
anchor: primaryAnchor,
showingMessage: _showMessage,
onToggleMessageVisibility: () {
setState(() {
_showMessage = !_showMessage;
});
},
onChangeBackgroundColor: (color) {
setState(() {
_backgroundColor = color;
});
},
onChangeSelection: (selection) {
setState(() {
_lastSelection = selection;
});
},
);
},
child: Container(
alignment: Alignment.center,
color: backgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
showingMessage
? 'Right click or long press anywhere to show the cascading menu.'
: '',
style: Theme.of(context).textTheme.headlineSmall,
),
),
Text(
_lastSelection != null ? 'Last Selected: $_lastSelection' : ''),
],
),
),
);
}
}
/// A class for consolidating the definition of menu entries.
///
/// This sort of class is not required, but illustrates one way that defining
/// menus could be done.
class MenuEntry {
const MenuEntry(
{required this.label, this.shortcut, this.onPressed, this.menuChildren})
: assert(menuChildren == null || onPressed == null,
'onPressed is ignored if menuChildren are provided');
final String label;
final MenuSerializableShortcut? shortcut;
final VoidCallback? onPressed;
final List<MenuEntry>? menuChildren;
static List<Widget> build(List<MenuEntry> selections) {
Widget buildSelection(MenuEntry selection) {
if (selection.menuChildren != null) {
return SubmenuButton(
menuChildren: MenuEntry.build(selection.menuChildren!),
child: Text(selection.label),
);
}
return MenuItemButton(
shortcut: selection.shortcut,
onPressed: selection.onPressed,
child: Text(selection.label),
);
}
return selections.map<Widget>(buildSelection).toList();
}
static Map<MenuSerializableShortcut, Intent> shortcuts(
List<MenuEntry> selections) {
final Map<MenuSerializableShortcut, Intent> result =
<MenuSerializableShortcut, Intent>{};
for (final MenuEntry selection in selections) {
if (selection.menuChildren != null) {
result.addAll(MenuEntry.shortcuts(selection.menuChildren!));
} else {
if (selection.shortcut != null && selection.onPressed != null) {
result[selection.shortcut!] =
VoidCallbackIntent(selection.onPressed!);
}
}
}
return result;
}
}
typedef _StringCallback = void Function(String string);
typedef _ColorCallback = void Function(Color color);
class _MyCascadingContextMenu extends StatefulWidget {
const _MyCascadingContextMenu({
required this.anchor,
required this.onToggleMessageVisibility,
required this.onChangeBackgroundColor,
required this.onChangeSelection,
required this.showingMessage,
});
final Offset anchor;
final VoidCallback onToggleMessageVisibility;
final _ColorCallback onChangeBackgroundColor;
final _StringCallback onChangeSelection;
final bool showingMessage;
@override
State<_MyCascadingContextMenu> createState() =>
_MyCascadingContextMenuState();
}
class _MyCascadingContextMenuState extends State<_MyCascadingContextMenu> {
ShortcutRegistryEntry? _shortcutsEntry;
List<MenuEntry> get _menus {
final List<MenuEntry> result = <MenuEntry>[
MenuEntry(
label: 'About',
onPressed: () {
ContextMenuController.removeAny();
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
widget.onChangeSelection('About');
},
),
MenuEntry(
label: widget.showingMessage ? 'Hide' : 'Show',
onPressed: () {
ContextMenuController.removeAny();
widget.onChangeSelection(
widget.showingMessage ? 'Hide Message' : 'Show Message');
widget.onToggleMessageVisibility();
},
shortcut: const SingleActivator(LogicalKeyboardKey.keyS, control: true),
),
// Hides the message, but is only enabled if the message isn't
// already hidden.
MenuEntry(
label: 'Reset',
onPressed: widget.showingMessage
? () {
ContextMenuController.removeAny();
widget.onChangeSelection('Reset');
widget.onToggleMessageVisibility();
}
: null,
shortcut: const SingleActivator(LogicalKeyboardKey.escape),
),
MenuEntry(
label: 'Color',
menuChildren: <MenuEntry>[
MenuEntry(
label: 'Red',
onPressed: () {
ContextMenuController.removeAny();
widget.onChangeSelection('Red Background');
widget.onChangeBackgroundColor(Colors.red);
},
shortcut:
const SingleActivator(LogicalKeyboardKey.keyR, control: true),
),
MenuEntry(
label: 'Green',
onPressed: () {
ContextMenuController.removeAny();
widget.onChangeSelection('Green Background');
widget.onChangeBackgroundColor(Colors.green);
},
shortcut:
const SingleActivator(LogicalKeyboardKey.keyG, control: true),
),
MenuEntry(
label: 'Blue',
onPressed: () {
ContextMenuController.removeAny();
widget.onChangeSelection('Blue Background');
widget.onChangeBackgroundColor(Colors.blue);
},
shortcut:
const SingleActivator(LogicalKeyboardKey.keyB, control: true),
),
],
),
];
// (Re-)register the shortcuts with the ShortcutRegistry so that they are
// available to the entire application, and update them if they've changed.
_shortcutsEntry?.dispose();
_shortcutsEntry =
ShortcutRegistry.of(context).addAll(MenuEntry.shortcuts(result));
return result;
}
@override
void dispose() {
_shortcutsEntry?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return DesktopTextSelectionToolbar(
anchor: widget.anchor,
children: MenuEntry.build(_menus),
);
}
}
| samples/context_menus/lib/cascading_menu_page.dart/0 | {
"file_path": "samples/context_menus/lib/cascading_menu_page.dart",
"repo_id": "samples",
"token_count": 3779
} | 1,327 |
import 'package:context_menus/email_button_page.dart';
import 'package:context_menus/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'utils.dart';
void main() {
testWidgets('Selecting the email address shows a custom button',
(tester) async {
await tester.pumpWidget(const MyApp());
// Navigate to the EmailButtonPage example.
await tester.dragUntilVisible(
find.text(EmailButtonPage.title),
find.byType(ListView),
const Offset(0.0, -100.0),
);
await tester.pumpAndSettle();
await tester.tap(find.text(EmailButtonPage.title));
await tester.pumpAndSettle();
// Select the first word, then right click to show the context menu.
expect(find.byType(TextField), findsOneWidget);
await tester.tapAt(tester.getTopLeft(find.byType(EditableText)));
await tester.pumpAndSettle();
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
for (int i = 0; i < 6; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
}
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
await tester.pumpAndSettle();
final TestGesture gesture1 = await tester.startGesture(
textOffsetToPosition(tester, 4),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture1.up();
await gesture1.removePointer();
await tester.pumpAndSettle();
// The context menu is shown, but no email button appears.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
expect(find.text('Send email'), findsNothing);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(
find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(2));
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbarButton),
findsNWidgets(2));
case TargetPlatform.android:
case TargetPlatform.fuchsia:
expect(find.byType(TextSelectionToolbarTextButton), findsNWidgets(3));
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(
find.byType(DesktopTextSelectionToolbarButton), findsNWidgets(3));
}
// Click on "Copy" to hide the context menu.
await tester.tap(find.text('Copy'));
await tester.pumpAndSettle();
expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing);
// Select the email address, then right click it to show the context menu.
for (int i = 0; i < 38; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
}
await tester.pumpAndSettle();
await tester.sendKeyDownEvent(LogicalKeyboardKey.shift);
for (int i = 0; i < 15; i++) {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
}
await tester.sendKeyUpEvent(LogicalKeyboardKey.shift);
final TestGesture gesture2 = await tester.startGesture(
textOffsetToPosition(tester, 48),
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await tester.pump();
await gesture2.up();
await gesture2.removePointer();
await tester.pumpAndSettle();
// The context menu is shown, and the email button now appears.
expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget);
expect(find.text('Send email'), findsOneWidget);
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
expect(
find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(3));
case TargetPlatform.macOS:
expect(find.byType(CupertinoDesktopTextSelectionToolbarButton),
findsNWidgets(3));
case TargetPlatform.android:
case TargetPlatform.fuchsia:
expect(find.byType(TextSelectionToolbarTextButton), findsNWidgets(4));
case TargetPlatform.linux:
case TargetPlatform.windows:
expect(
find.byType(DesktopTextSelectionToolbarButton), findsNWidgets(4));
}
// TODO: Test failing on Flutter 3.18.0-7.0.pre.57 https://github.com/flutter/samples/issues/2110
}, skip: true);
}
| samples/context_menus/test/email_button_page_test.dart/0 | {
"file_path": "samples/context_menus/test/email_button_page_test.dart",
"repo_id": "samples",
"token_count": 1633
} | 1,328 |
# deeplink_store_example
A store app that includes three screen, ProductList, ProductDetails, and ProductCategoryList.
This app uses go_router to create routing table for all three screens. It also updates the project
parameters for Android and iOS to support deeplinks.
To learn more, visit <link TBD>.
## Getting Started
This app put a placeholder for Android Intent Filters and iOS Associated Domains. To use this
example, update them with your own web domain.
| samples/deeplink_store_example/README.md/0 | {
"file_path": "samples/deeplink_store_example/README.md",
"repo_id": "samples",
"token_count": 116
} | 1,329 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'model/products_repository.dart';
import 'styles.dart';
class ProductDetails extends StatelessWidget {
const ProductDetails({super.key});
@override
Widget build(BuildContext context) {
final String currentId = GoRouterState.of(context).pathParameters['id']!;
final Product product =
ProductsRepository.loadProduct(id: int.parse(currentId));
return Scaffold(
body: ListView(
children: <Widget>[
ProductPicture(product: product),
Styles.spacer,
Text(product.name, style: Styles.productPageItemName),
Styles.spacer,
Text('\$${product.price}', style: Styles.productPageItemPrice),
Styles.largeSpacer,
],
),
);
}
}
class ProductPicture extends StatelessWidget {
const ProductPicture({super.key, required this.product});
final Product product;
@override
Widget build(BuildContext context) {
return Stack(
children: [
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Image.asset(
product.assetName2X,
package: product.assetPackage,
fit: BoxFit.cover,
width: constraints.maxWidth,
);
},
),
const BackButton(),
],
);
}
}
| samples/deeplink_store_example/lib/product_details.dart/0 | {
"file_path": "samples/deeplink_store_example/lib/product_details.dart",
"repo_id": "samples",
"token_count": 736
} | 1,330 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import '../serializers.dart';
part 'api_error.g.dart';
abstract class ApiError implements Built<ApiError, ApiErrorBuilder> {
factory ApiError([void Function(ApiErrorBuilder)? updates]) = _$ApiError;
ApiError._();
@BuiltValueField(wireName: 'errors')
BuiltList<String>? get errors;
String toJson() {
return json.encode(serializers.serializeWith(ApiError.serializer, this));
}
static ApiError? fromJson(String jsonString) {
return serializers.deserializeWith(
ApiError.serializer, json.decode(jsonString));
}
static Serializer<ApiError> get serializer => _$apiErrorSerializer;
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/api_error.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/api_error.dart",
"repo_id": "samples",
"token_count": 314
} | 1,331 |
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import '../serializers.dart';
part 'tags.g.dart';
abstract class Tags implements Built<Tags, TagsBuilder> {
factory Tags([void Function(TagsBuilder)? updates]) = _$Tags;
Tags._();
@BuiltValueField(wireName: 'title')
String get title;
String toJson() {
return json.encode(serializers.serializeWith(Tags.serializer, this));
}
static Tags? fromJson(String jsonString) {
return serializers.deserializeWith(
Tags.serializer, json.decode(jsonString));
}
static Serializer<Tags> get serializer => _$tagsSerializer;
}
| samples/desktop_photo_search/fluent_ui/lib/src/unsplash/tags.dart/0 | {
"file_path": "samples/desktop_photo_search/fluent_ui/lib/src/unsplash/tags.dart",
"repo_id": "samples",
"token_count": 268
} | 1,332 |
// Copyright 2022 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:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter_simple_treeview/flutter_simple_treeview.dart';
import 'package:provider/provider.dart';
import '../model/photo_search_model.dart';
import '../unsplash/photo.dart';
import '../widgets/photo_details.dart';
import '../widgets/split.dart';
class UnsplashSearchContent extends StatefulWidget {
const UnsplashSearchContent({super.key});
@override
State<UnsplashSearchContent> createState() => _UnsplashSearchContentState();
}
class _UnsplashSearchContentState extends State<UnsplashSearchContent> {
final _treeViewScrollController = ScrollController();
@override
dispose() {
_treeViewScrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final photoSearchModel = Provider.of<PhotoSearchModel>(context);
return Split(
axis: Axis.horizontal,
initialFirstFraction: 0.4,
firstChild: Scrollbar(
controller: _treeViewScrollController,
child: SingleChildScrollView(
controller: _treeViewScrollController,
child: TreeView(
nodes: photoSearchModel.entries.map(_buildSearchEntry).toList(),
indent: 0,
),
),
),
secondChild: Center(
child: photoSearchModel.selectedPhoto != null
? PhotoDetails(
photo: photoSearchModel.selectedPhoto!,
onPhotoSave: (photo) async {
final saveLocation = await getSaveLocation(
suggestedName: '${photo.id}.jpg',
acceptedTypeGroups: [
const XTypeGroup(
label: 'JPG',
extensions: ['jpg'],
mimeTypes: ['image/jpeg'],
),
],
);
if (saveLocation != null) {
final fileData =
await photoSearchModel.download(photo: photo);
final photoFile =
XFile.fromData(fileData, mimeType: 'image/jpeg');
await photoFile.saveTo(saveLocation.path);
}
},
)
: Container(),
),
);
}
TreeNode _buildSearchEntry(SearchEntry searchEntry) {
void selectPhoto(Photo photo) {
searchEntry.model.selectedPhoto = photo;
}
String labelForPhoto(Photo photo) => 'Photo by ${photo.user!.name}';
return TreeNode(
content: Expanded(
child: Text(searchEntry.query),
),
children: searchEntry.photos
.map<TreeNode>(
(photo) => TreeNode(
content: Expanded(
child: Semantics(
button: true,
onTap: () => selectPhoto(photo),
label: labelForPhoto(photo),
excludeSemantics: true,
child: InkWell(
onTap: () => selectPhoto(photo),
child: Padding(
padding: const EdgeInsets.all(12),
child: Text(labelForPhoto(photo)),
),
),
),
),
),
)
.toList(),
);
}
}
| samples/desktop_photo_search/material/lib/src/widgets/unsplash_search_content.dart/0 | {
"file_path": "samples/desktop_photo_search/material/lib/src/widgets/unsplash_search_content.dart",
"repo_id": "samples",
"token_count": 1701
} | 1,333 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/desktop_photo_search/material/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/desktop_photo_search/material/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,334 |
# Photo Search app
This application has been moved to the [top level of this repo](../../desktop_photo_search). | samples/experimental/desktop_photo_search/README.md/0 | {
"file_path": "samples/experimental/desktop_photo_search/README.md",
"repo_id": "samples",
"token_count": 28
} | 1,335 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/experimental/federated_plugin/federated_plugin/example/android/gradle.properties/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,336 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/experimental/federated_plugin/federated_plugin/example/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin/example/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,337 |
// 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 Cocoa
import FlutterMacOS
import IOKit.ps
public class FederatedPluginMacosPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "battery", binaryMessenger: registrar.messenger)
let instance = FederatedPluginMacosPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getBatteryLevel":
getBatteryLevel(result)
default:
result(FlutterMethodNotImplemented)
}
}
private func getBatteryLevel(_ result: FlutterResult) {
let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array
let sourceInfo : NSDictionary = IOPSGetPowerSourceDescription(snapshot, sources[0]).takeUnretainedValue()
guard let capacity = sourceInfo[kIOPSCurrentCapacityKey] as? Int else {
result(FlutterError(code: "STATUS_UNAVAILABLE", message: "Not able to determine battery level", details: nil))
return
}
result(capacity)
}
}
| samples/experimental/federated_plugin/federated_plugin_macos/macos/Classes/FederatedPluginMacosPlugin.swift/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_macos/macos/Classes/FederatedPluginMacosPlugin.swift",
"repo_id": "samples",
"token_count": 434
} | 1,338 |
// 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:html';
import 'package:federated_plugin_web/federated_plugin_web.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:mockito/mockito.dart';
const kBatteryLevel = 0.49;
class NavigatorMock extends Mock implements Navigator {}
class BatteryManagerMock extends Mock implements BatteryManager {
@override
num get level => kBatteryLevel;
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('FederatedPlugin test', () {
final navigatorMock = NavigatorMock();
setUp(() {
when(navigatorMock.getBattery())
.thenAnswer((realInvocation) async => BatteryManagerMock());
});
testWidgets('getBatteryLevel Method', (tester) async {
final federatedPlugin = FederatedPlugin(navigator: navigatorMock);
final batteryLevel = await federatedPlugin.getBatteryLevel();
// Verify that getBattery was called.
verify(navigatorMock.getBattery());
// Verify the battery level.
expect(batteryLevel, kBatteryLevel * 100);
});
});
}
| samples/experimental/federated_plugin/federated_plugin_web/test_driver/federated_plugin_web_integration.dart/0 | {
"file_path": "samples/experimental/federated_plugin/federated_plugin_web/test_driver/federated_plugin_web_integration.dart",
"repo_id": "samples",
"token_count": 417
} | 1,339 |
include: package:analysis_defaults/flutter.yaml
analyzer:
exclude:
- lib/model/rule.g.dart
- test/widget_test.mocks.dart
| samples/experimental/linting_tool/analysis_options.yaml/0 | {
"file_path": "samples/experimental/linting_tool/analysis_options.yaml",
"repo_id": "samples",
"token_count": 55
} | 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 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:linting_tool/model/rule.dart';
import 'package:yaml/yaml.dart';
class APIProvider {
final http.Client httpClient;
APIProvider(this.httpClient);
Future<List<Rule>> getRulesList() async {
final response = await httpClient.get(Uri.parse(
'https://raw.githubusercontent.com/dart-lang/site-www/main/src/_data/linter_rules.json',
));
if (response.statusCode == 200) {
final data = json.decode(response.body) as List;
final rulesList = [
for (final item in data) Rule.fromJson(item as Map<String, dynamic>)
];
return rulesList;
} else {
throw Exception('Failed to load rules');
}
}
Future<YamlMap> getTemplateFile() async {
final response = await httpClient.get(Uri.parse(
'https://raw.githubusercontent.com/flutter/flutter/main/packages/flutter_tools/templates/app_shared/analysis_options.yaml.tmpl'));
if (response.statusCode == 200) {
return loadYaml(response.body) as YamlMap;
} else {
throw Exception('Failed to load template file');
}
}
}
| samples/experimental/linting_tool/lib/repository/api_provider.dart/0 | {
"file_path": "samples/experimental/linting_tool/lib/repository/api_provider.dart",
"repo_id": "samples",
"token_count": 470
} | 1,341 |
// Mocks generated by Mockito 5.4.2 from annotations
// in linting_tool/test/widget_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'dart:convert' as _i4;
import 'dart:typed_data' as _i5;
import 'package:http/http.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response {
_FakeResponse_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
class _FakeStreamedResponse_1 extends _i1.SmartFake
implements _i2.StreamedResponse {
_FakeStreamedResponse_1(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [Client].
///
/// See the documentation for Mockito's code generation for more information.
class MockClient extends _i1.Mock implements _i2.Client {
MockClient() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Future<_i2.Response> head(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#head,
[url],
{#headers: headers},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#head,
[url],
{#headers: headers},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> get(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#get,
[url],
{#headers: headers},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#get,
[url],
{#headers: headers},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> post(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#post,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#post,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> put(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#put,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#put,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> patch(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#patch,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#patch,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<_i2.Response> delete(
Uri? url, {
Map<String, String>? headers,
Object? body,
_i4.Encoding? encoding,
}) =>
(super.noSuchMethod(
Invocation.method(
#delete,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
returnValue: _i3.Future<_i2.Response>.value(_FakeResponse_0(
this,
Invocation.method(
#delete,
[url],
{
#headers: headers,
#body: body,
#encoding: encoding,
},
),
)),
) as _i3.Future<_i2.Response>);
@override
_i3.Future<String> read(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#read,
[url],
{#headers: headers},
),
returnValue: _i3.Future<String>.value(''),
) as _i3.Future<String>);
@override
_i3.Future<_i5.Uint8List> readBytes(
Uri? url, {
Map<String, String>? headers,
}) =>
(super.noSuchMethod(
Invocation.method(
#readBytes,
[url],
{#headers: headers},
),
returnValue: _i3.Future<_i5.Uint8List>.value(_i5.Uint8List(0)),
) as _i3.Future<_i5.Uint8List>);
@override
_i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) =>
(super.noSuchMethod(
Invocation.method(
#send,
[request],
),
returnValue:
_i3.Future<_i2.StreamedResponse>.value(_FakeStreamedResponse_1(
this,
Invocation.method(
#send,
[request],
),
)),
) as _i3.Future<_i2.StreamedResponse>);
@override
void close() => super.noSuchMethod(
Invocation.method(
#close,
[],
),
returnValueForMissingStub: null,
);
}
| samples/experimental/linting_tool/test/widget_test.mocks.dart/0 | {
"file_path": "samples/experimental/linting_tool/test/widget_test.mocks.dart",
"repo_id": "samples",
"token_count": 3444
} | 1,342 |
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "run_loop.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
RunLoop run_loop;
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"linting_tool", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
::CoUninitialize();
return EXIT_SUCCESS;
}
| samples/experimental/linting_tool/windows/runner/main.cpp/0 | {
"file_path": "samples/experimental/linting_tool/windows/runner/main.cpp",
"repo_id": "samples",
"token_count": 451
} | 1,343 |
/*
* 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.
*/
#ifndef RUNTIME_INCLUDE_DART_API_DL_H_
#define RUNTIME_INCLUDE_DART_API_DL_H_
#include "dart_api.h" /* NOLINT */
#include "dart_native_api.h" /* NOLINT */
/** \mainpage Dynamically Linked Dart API
*
* This exposes a subset of symbols from dart_api.h and dart_native_api.h
* available in every Dart embedder through dynamic linking.
*
* All symbols are postfixed with _DL to indicate that they are dynamically
* linked and to prevent conflicts with the original symbol.
*
* Link `dart_api_dl.c` file into your library and invoke
* `Dart_InitializeApiDL` with `NativeApi.initializeApiDLData`.
*/
DART_EXPORT intptr_t Dart_InitializeApiDL(void* data);
// ============================================================================
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// Verbatim copy of `dart_native_api.h` and `dart_api.h` symbol names and types
// to trigger compile-time errors if the sybols in those files are updated
// without updating these.
//
// Function return and argument types, and typedefs are carbon copied. Structs
// are typechecked nominally in C/C++, so they are not copied, instead a
// comment is added to their definition.
typedef int64_t Dart_Port_DL;
typedef void (*Dart_NativeMessageHandler_DL)(Dart_Port_DL dest_port_id,
Dart_CObject* message);
// dart_native_api.h symbols can be called on any thread.
#define DART_NATIVE_API_DL_SYMBOLS(F) \
/***** dart_native_api.h *****/ \
/* Dart_Port */ \
F(Dart_PostCObject, bool, (Dart_Port_DL port_id, Dart_CObject * message)) \
F(Dart_PostInteger, bool, (Dart_Port_DL port_id, int64_t message)) \
F(Dart_NewNativePort, Dart_Port_DL, \
(const char* name, Dart_NativeMessageHandler_DL handler, \
bool handle_concurrently)) \
F(Dart_CloseNativePort, bool, (Dart_Port_DL native_port_id))
// dart_api.h symbols can only be called on Dart threads.
#define DART_API_DL_SYMBOLS(F) \
/***** dart_api.h *****/ \
/* Errors */ \
F(Dart_IsError, bool, (Dart_Handle handle)) \
F(Dart_IsApiError, bool, (Dart_Handle handle)) \
F(Dart_IsUnhandledExceptionError, bool, (Dart_Handle handle)) \
F(Dart_IsCompilationError, bool, (Dart_Handle handle)) \
F(Dart_IsFatalError, bool, (Dart_Handle handle)) \
F(Dart_GetError, const char*, (Dart_Handle handle)) \
F(Dart_ErrorHasException, bool, (Dart_Handle handle)) \
F(Dart_ErrorGetException, Dart_Handle, (Dart_Handle handle)) \
F(Dart_ErrorGetStackTrace, Dart_Handle, (Dart_Handle handle)) \
F(Dart_NewApiError, Dart_Handle, (const char* error)) \
F(Dart_NewCompilationError, Dart_Handle, (const char* error)) \
F(Dart_NewUnhandledExceptionError, Dart_Handle, (Dart_Handle exception)) \
F(Dart_PropagateError, void, (Dart_Handle handle)) \
/* Dart_Handle, Dart_PersistentHandle, Dart_WeakPersistentHandle */ \
F(Dart_HandleFromPersistent, Dart_Handle, (Dart_PersistentHandle object)) \
F(Dart_HandleFromWeakPersistent, Dart_Handle, \
(Dart_WeakPersistentHandle object)) \
F(Dart_NewPersistentHandle, Dart_PersistentHandle, (Dart_Handle object)) \
F(Dart_SetPersistentHandle, void, \
(Dart_PersistentHandle obj1, Dart_Handle obj2)) \
F(Dart_DeletePersistentHandle, void, (Dart_PersistentHandle object)) \
F(Dart_NewWeakPersistentHandle, Dart_WeakPersistentHandle, \
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
Dart_HandleFinalizer callback)) \
F(Dart_DeleteWeakPersistentHandle, void, (Dart_WeakPersistentHandle object)) \
F(Dart_UpdateExternalSize, void, \
(Dart_WeakPersistentHandle object, intptr_t external_allocation_size)) \
F(Dart_NewFinalizableHandle, Dart_FinalizableHandle, \
(Dart_Handle object, void* peer, intptr_t external_allocation_size, \
Dart_HandleFinalizer callback)) \
F(Dart_DeleteFinalizableHandle, void, \
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object)) \
F(Dart_UpdateFinalizableExternalSize, void, \
(Dart_FinalizableHandle object, Dart_Handle strong_ref_to_object, \
intptr_t external_allocation_size)) \
/* Dart_Port */ \
F(Dart_Post, bool, (Dart_Port_DL port_id, Dart_Handle object)) \
F(Dart_NewSendPort, Dart_Handle, (Dart_Port_DL port_id)) \
F(Dart_SendPortGetId, Dart_Handle, \
(Dart_Handle port, Dart_Port_DL * port_id)) \
/* Scopes */ \
F(Dart_EnterScope, void, ()) \
F(Dart_ExitScope, void, ())
#define DART_API_ALL_DL_SYMBOLS(F) \
DART_NATIVE_API_DL_SYMBOLS(F) \
DART_API_DL_SYMBOLS(F)
// IMPORTANT! Never update these signatures without properly updating
// DART_API_DL_MAJOR_VERSION and DART_API_DL_MINOR_VERSION.
//
// End of verbatim copy.
// ============================================================================
// Copy of definition of DART_EXPORT without 'used' attribute.
//
// The 'used' attribute cannot be used with DART_API_ALL_DL_SYMBOLS because
// they are not function declarations, but variable declarations with a
// function pointer type.
//
// The function pointer variables are initialized with the addresses of the
// functions in the VM. If we were to use function declarations instead, we
// would need to forward the call to the VM adding indirection.
#if defined(__CYGWIN__)
#error Tool chain and platform not supported.
#elif defined(_WIN32)
#if defined(DART_SHARED_LIB)
#define DART_EXPORT_DL DART_EXTERN_C __declspec(dllexport)
#else
#define DART_EXPORT_DL DART_EXTERN_C
#endif
#else
#if __GNUC__ >= 4
#if defined(DART_SHARED_LIB)
#define DART_EXPORT_DL DART_EXTERN_C __attribute__((visibility("default")))
#else
#define DART_EXPORT_DL DART_EXTERN_C
#endif
#else
#error Tool chain not supported.
#endif
#endif
#define DART_API_DL_DECLARATIONS(name, R, A) \
typedef R(*name##_Type) A; \
DART_EXPORT_DL name##_Type name##_DL;
DART_API_ALL_DL_SYMBOLS(DART_API_DL_DECLARATIONS)
#undef DART_API_DL_DECLARATIONS
#undef DART_EXPORT_DL
#endif /* RUNTIME_INCLUDE_DART_API_DL_H_ */ /* NOLINT */ | samples/experimental/pedometer/src/dart-sdk/include/dart_api_dl.h/0 | {
"file_path": "samples/experimental/pedometer/src/dart-sdk/include/dart_api_dl.h",
"repo_id": "samples",
"token_count": 3855
} | 1,344 |
// 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 PageWeight extends SinglePage {
const PageWeight({
super.key,
required super.pageConfig,
});
@override
State<SinglePage> createState() => _PageWeightState();
}
class _PageWeightState extends SinglePageState {
@override
Widget createTopicIntro() {
return LightboxedPanel(
pageConfig: widget.pageConfig,
content: [
Text(
'Weight'.toUpperCase(),
style: TextStyles.headlineStyle(),
textAlign: TextAlign.left,
),
Text(
'You probably knew that fonts can vary by weight, or the boldness, '
'as we can see in the letters on this page. Tap the pieces of the '
'broken letter to bring it back together, but don’t get distracted '
'by its oscillating weight!',
style: TextStyles.bodyStyle(),
textAlign: TextAlign.left,
),
],
);
}
@override
List<Widget> buildWonkyChars() {
return <Widget>[
Positioned(
left: widget.pageConfig.wonkyCharLargeSize * -0.01,
top: widget.pageConfig.wonkyCharLargeSize * -0.26,
child: WonkyChar(
text: 'S',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: 0.15 * pi,
animDurationMillis: 3200,
animationSettings: [
WonkyAnimPalette.weight(
from: 100,
to: 300,
curve: Curves.easeInOut,
),
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.34,
top: widget.pageConfig.wonkyCharLargeSize * 0.3,
child: WonkyChar(
text: 't',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.12 * pi,
animDurationMillis: 3200,
animationSettings: [
WonkyAnimPalette.weight(
from: 1000,
to: 800,
curve: Curves.easeInOut,
),
],
),
),
Positioned(
right: widget.pageConfig.wonkyCharLargeSize * 0.07,
top: widget.pageConfig.wonkyCharLargeSize * -0.26,
child: WonkyChar(
text: 'q',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -0.15 * pi,
animDurationMillis: 5000,
animationSettings: [
WonkyAnimPalette.weight(
from: 200,
to: 500,
),
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.5,
top: widget.pageConfig.wonkyCharSmallSize * 0.3,
child: WonkyChar(
text: '*',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.15 * pi,
animationSettings: [
WonkyAnimPalette.weight(
from: 100,
to: 400,
),
],
),
),
// lower half --------------------------------------
Positioned(
left: widget.pageConfig.wonkyCharLargeSize * -0.2,
bottom: widget.pageConfig.wonkyCharLargeSize * -0.34,
child: WonkyChar(
text: 'C',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -0.15 * pi,
animDurationMillis: 7000,
animationSettings: [
WonkyAnimPalette.weight(
from: 1000,
to: 700,
),
],
),
),
Positioned(
left: widget.pageConfig.screenWidth * 0.42,
bottom: widget.pageConfig.wonkyCharLargeSize * 0.02,
child: WonkyChar(
text: 'f',
size: widget.pageConfig.wonkyCharSmallSize,
baseRotation: -0.15 * pi,
animDurationMillis: 4000,
animationSettings: [
WonkyAnimPalette.weight(
from: 100,
to: 200,
),
],
),
),
Positioned(
right: widget.pageConfig.wonkyCharLargeSize * -0.2,
bottom: widget.pageConfig.wonkyCharLargeSize * -0.23,
child: WonkyChar(
text: 'R',
size: widget.pageConfig.wonkyCharLargeSize,
baseRotation: -1.15 * pi,
animDurationMillis: 2000,
animationSettings: [
WonkyAnimPalette.weight(
from: 700,
to: 900,
),
],
),
),
];
}
@override
Widget createPuzzle() {
return RotatorPuzzle(
pageConfig: widget.pageConfig,
numTiles: 9,
puzzleNum: 1,
shader: Shader.wavy2,
shaderDuration: 3000,
tileShadedString: 'W',
tileShadedStringPadding: EdgeInsets.only(
left: 0.698 * widget.pageConfig.puzzleSize,
right: 0.698 * widget.pageConfig.puzzleSize),
tileShadedStringSize: 2.79 * widget.pageConfig.puzzleSize,
tileScaleModifier: 2.4,
tileShadedStringAnimDuration: 1000,
tileShadedStringAnimSettings: [
WonkyAnimPalette.weight(from: 600, to: 1000),
WonkyAnimPalette.width(from: 50, to: 50),
],
);
}
}
| samples/experimental/varfont_shader_puzzle/lib/page_content/page_weight.dart/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/lib/page_content/page_weight.dart",
"repo_id": "samples",
"token_count": 2665
} | 1,345 |
// 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;
float levels = 5;
float maxMag = 0.1;
float minMag = 0.02;
float magMod = maxMag / levels;
float row = floor(texCoord.y * uSize.y * 0.25); // resolution/density of rows
float offsetDir = mod(row, 2) == 0 ? -1 : 1;
float sinFn = cos(texCoord.y * 1 * PI + piTime);
float offset = (offsetDir * (minMag + maxMag * sinFn)) * uDampener;
vec2 offsetTexCoord = vec2(texCoord.x + offset, texCoord.y);
vec4 outColor = texture(uTexture, offsetTexCoord);
if (texCoord.x + offset < 0.0 || texCoord.x + offset > 1.0) {
outColor = vec4(0.0, 0.0, 0.0, 0.0);
}
fragColor = outColor;
}
| samples/experimental/varfont_shader_puzzle/shaders/row_offset.frag/0 | {
"file_path": "samples/experimental/varfont_shader_puzzle/shaders/row_offset.frag",
"repo_id": "samples",
"token_count": 389
} | 1,346 |
// Copyright 2020, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'api.dart';
class FirebaseDashboardApi implements DashboardApi {
@override
final EntryApi entries;
@override
final CategoryApi categories;
FirebaseDashboardApi(FirebaseFirestore firestore, String userId)
: entries = FirebaseEntryApi(firestore, userId),
categories = FirebaseCategoryApi(firestore, userId);
}
class FirebaseEntryApi implements EntryApi {
final FirebaseFirestore firestore;
final String userId;
final CollectionReference<Map<String, dynamic>> _categoriesRef;
FirebaseEntryApi(this.firestore, this.userId)
: _categoriesRef = firestore.collection('users/$userId/categories');
@override
Stream<List<Entry>> subscribe(String categoryId) {
var snapshots =
_categoriesRef.doc(categoryId).collection('entries').snapshots();
var result = snapshots.map<List<Entry>>((querySnapshot) {
return querySnapshot.docs.map<Entry>((snapshot) {
return Entry.fromJson(snapshot.data())..id = snapshot.id;
}).toList();
});
return result;
}
@override
Future<Entry> delete(String categoryId, String id) async {
var document = _categoriesRef.doc('$categoryId/entries/$id');
var entry = await get(categoryId, document.id);
await document.delete();
return entry;
}
@override
Future<Entry> insert(String categoryId, Entry entry) async {
var document = await _categoriesRef
.doc(categoryId)
.collection('entries')
.add(entry.toJson());
return await get(categoryId, document.id);
}
@override
Future<List<Entry>> list(String categoryId) async {
var entriesRef = _categoriesRef.doc(categoryId).collection('entries');
var querySnapshot = await entriesRef.get();
var entries = querySnapshot.docs
.map((doc) => Entry.fromJson(doc.data())..id = doc.id)
.toList();
return entries;
}
@override
Future<Entry> update(String categoryId, String id, Entry entry) async {
var document = _categoriesRef.doc('$categoryId/entries/$id');
await document.update(entry.toJson());
var snapshot = await document.get();
return Entry.fromJson(snapshot.data()!)..id = snapshot.id;
}
@override
Future<Entry> get(String categoryId, String id) async {
var document = _categoriesRef.doc('$categoryId/entries/$id');
var snapshot = await document.get();
return Entry.fromJson(snapshot.data()!)..id = snapshot.id;
}
}
class FirebaseCategoryApi implements CategoryApi {
final FirebaseFirestore firestore;
final String userId;
final CollectionReference<Map<String, dynamic>> _categoriesRef;
FirebaseCategoryApi(this.firestore, this.userId)
: _categoriesRef = firestore.collection('users/$userId/categories');
@override
Stream<List<Category>> subscribe() {
var snapshots = _categoriesRef.snapshots();
var result = snapshots.map<List<Category>>((querySnapshot) {
return querySnapshot.docs.map<Category>((snapshot) {
return Category.fromJson(snapshot.data())..id = snapshot.id;
}).toList();
});
return result;
}
@override
Future<Category> delete(String id) async {
var document = _categoriesRef.doc(id);
var categories = await get(document.id);
await document.delete();
return categories;
}
@override
Future<Category> get(String id) async {
var document = _categoriesRef.doc(id);
var snapshot = await document.get();
return Category.fromJson(snapshot.data()!)..id = snapshot.id;
}
@override
Future<Category> insert(Category category) async {
var document = await _categoriesRef.add(category.toJson());
return await get(document.id);
}
@override
Future<List<Category>> list() async {
var querySnapshot = await _categoriesRef.get();
var categories = querySnapshot.docs
.map((doc) => Category.fromJson(doc.data())..id = doc.id)
.toList();
return categories;
}
@override
Future<Category> update(Category category, String id) async {
var document = _categoriesRef.doc(id);
await document.update(category.toJson());
var snapshot = await document.get();
return Category.fromJson(snapshot.data()!)..id = snapshot.id;
}
}
| samples/experimental/web_dashboard/lib/src/api/firebase.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/api/firebase.dart",
"repo_id": "samples",
"token_count": 1518
} | 1,347 |
// 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:intl/intl.dart' as intl;
import 'package:provider/provider.dart';
import 'package:web_dashboard/src/api/api.dart';
import '../app.dart';
import 'categories_dropdown.dart';
class NewEntryForm extends StatefulWidget {
const NewEntryForm({super.key});
@override
State<NewEntryForm> createState() => _NewEntryFormState();
}
class _NewEntryFormState extends State<NewEntryForm> {
late Category _selected;
final Entry _entry = Entry(0, DateTime.now());
@override
Widget build(BuildContext context) {
var api = Provider.of<AppState>(context).api!;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: CategoryDropdown(
api: api.categories,
onSelected: (category) {
if (category == null) return;
setState(() {
_selected = category;
});
},
),
),
EditEntryForm(
entry: _entry,
onDone: (shouldInsert) {
if (shouldInsert) {
api.entries.insert(_selected.id!, _entry);
}
Navigator.of(context).pop();
},
),
],
);
}
}
class EditEntryForm extends StatefulWidget {
final Entry? entry;
final ValueChanged<bool> onDone;
const EditEntryForm({
required this.entry,
required this.onDone,
super.key,
});
@override
State<EditEntryForm> createState() => _EditEntryFormState();
}
class _EditEntryFormState extends State<EditEntryForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8),
child: TextFormField(
initialValue: widget.entry!.value.toString(),
decoration: const InputDecoration(labelText: 'Value'),
keyboardType: TextInputType.number,
validator: (value) {
try {
int.parse(value!);
} catch (e) {
return "Please enter a whole number";
}
return null;
},
onChanged: (newValue) {
widget.entry!.value = int.parse(newValue);
},
),
),
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(intl.DateFormat('MM/dd/yyyy').format(widget.entry!.time)),
FilledButton(
child: const Text('Edit'),
onPressed: () async {
var result = await showDatePicker(
context: context,
initialDate: widget.entry!.time,
firstDate:
DateTime.now().subtract(const Duration(days: 365)),
lastDate: DateTime.now());
if (result == null) {
return;
}
setState(() {
widget.entry!.time = result;
});
},
)
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: FilledButton(
child: const Text('Cancel'),
onPressed: () {
widget.onDone(false);
},
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: FilledButton(
child: const Text('OK'),
onPressed: () {
if (_formKey.currentState!.validate()) {
widget.onDone(true);
}
},
),
),
],
)
],
),
);
}
}
| samples/experimental/web_dashboard/lib/src/widgets/edit_entry.dart/0 | {
"file_path": "samples/experimental/web_dashboard/lib/src/widgets/edit_entry.dart",
"repo_id": "samples",
"token_count": 2427
} | 1,348 |
# form_app
A sample demonstrating different types of forms and best practices.
## Sign In with HTTP
[*lib/src/sign_in_http.dart*](lib/src/sign_in_http.dart)
A sign in form using `package:http` to send a request.
## Form widgets
[*lib/src/form_widgets.dart*](lib/src/form_widgets.dart)
A stylized form that uses widgets like TextField, DatePicker, Slider, Checkbox,
and Switch.
## Autofill
[*lib/src/autofill.dart*](lib/src/autofill.dart)
A form that uses AutofillGroup to auto-fill the users name, email, and address.
In order to use Autofill in a browser, your app needs to be hosted with HTTPS.
If you would like to test locally, you can build the app in release mode
(`flutter run -d chrome --release --web-port=5000`).
Then use [tunnelmole](https://tunnelmole.com/docs), an open source tunneling
tool or [ngrok](https://ngrok.com/), a popular closed source tunneling tool
to create an HTTPS url for your local app (`tmole 5000` or `ngrok http 5000`).
## Validation
[*lib/src/validation.dart*](lib/src/validation.dart)
A form that alerts the user if the data entered is invalid.
| samples/form_app/README.md/0 | {
"file_path": "samples/form_app/README.md",
"repo_id": "samples",
"token_count": 365
} | 1,349 |
// 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:intl/intl.dart' as intl;
class FormWidgetsDemo extends StatefulWidget {
const FormWidgetsDemo({super.key});
@override
State<FormWidgetsDemo> createState() => _FormWidgetsDemoState();
}
class _FormWidgetsDemoState extends State<FormWidgetsDemo> {
final _formKey = GlobalKey<FormState>();
String title = '';
String description = '';
DateTime date = DateTime.now();
double maxValue = 0;
bool? brushedTeeth = false;
bool enableFeature = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Form widgets'),
),
body: Form(
key: _formKey,
child: Scrollbar(
child: Align(
alignment: Alignment.topCenter,
child: Card(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
...[
TextFormField(
decoration: const InputDecoration(
filled: true,
hintText: 'Enter a title...',
labelText: 'Title',
),
onChanged: (value) {
setState(() {
title = value;
});
},
),
TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
filled: true,
hintText: 'Enter a description...',
labelText: 'Description',
),
onChanged: (value) {
description = value;
},
maxLines: 5,
),
_FormDatePicker(
date: date,
onChanged: (value) {
setState(() {
date = value;
});
},
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Estimated value',
style: Theme.of(context).textTheme.bodyLarge,
),
],
),
Text(
intl.NumberFormat.currency(
symbol: "\$", decimalDigits: 0)
.format(maxValue),
style: Theme.of(context).textTheme.titleMedium,
),
Slider(
min: 0,
max: 500,
divisions: 500,
value: maxValue,
onChanged: (value) {
setState(() {
maxValue = value;
});
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Checkbox(
value: brushedTeeth,
onChanged: (checked) {
setState(() {
brushedTeeth = checked;
});
},
),
Text('Brushed Teeth',
style: Theme.of(context).textTheme.titleMedium),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Enable feature',
style: Theme.of(context).textTheme.bodyLarge),
Switch(
value: enableFeature,
onChanged: (enabled) {
setState(() {
enableFeature = enabled;
});
},
),
],
),
].expand(
(widget) => [
widget,
const SizedBox(
height: 24,
)
],
)
],
),
),
),
),
),
),
),
);
}
}
class _FormDatePicker extends StatefulWidget {
final DateTime date;
final ValueChanged<DateTime> onChanged;
const _FormDatePicker({
required this.date,
required this.onChanged,
});
@override
State<_FormDatePicker> createState() => _FormDatePickerState();
}
class _FormDatePickerState extends State<_FormDatePicker> {
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
'Date',
style: Theme.of(context).textTheme.bodyLarge,
),
Text(
intl.DateFormat.yMd().format(widget.date),
style: Theme.of(context).textTheme.titleMedium,
),
],
),
TextButton(
child: const Text('Edit'),
onPressed: () async {
var newDate = await showDatePicker(
context: context,
initialDate: widget.date,
firstDate: DateTime(1900),
lastDate: DateTime(2100),
);
// Don't change the date if the date picker returns null.
if (newDate == null) {
return;
}
widget.onChanged(newDate);
},
)
],
);
}
}
| samples/form_app/lib/src/form_widgets.dart/0 | {
"file_path": "samples/form_app/lib/src/form_widgets.dart",
"repo_id": "samples",
"token_count": 4869
} | 1,350 |
// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'package:games_services/games_services.dart' as gs;
import 'package:logging/logging.dart';
import 'score.dart';
/// Allows awarding achievements and leaderboard scores,
/// and also showing the platforms' UI overlays for achievements
/// and leaderboards.
///
/// A facade of `package:games_services`.
class GamesServicesController {
static final Logger _log = Logger('GamesServicesController');
final Completer<bool> _signedInCompleter = Completer();
Future<bool> get signedIn => _signedInCompleter.future;
/// Unlocks an achievement on Game Center / Play Games.
///
/// You must provide the achievement ids via the [iOS] and [android]
/// parameters.
///
/// Does nothing when the game isn't signed into the underlying
/// games service.
Future<void> awardAchievement(
{required String iOS, required String android}) async {
if (!await signedIn) {
_log.warning('Trying to award achievement when not logged in.');
return;
}
try {
await gs.GamesServices.unlock(
achievement: gs.Achievement(
androidID: android,
iOSID: iOS,
),
);
} catch (e) {
_log.severe('Cannot award achievement: $e');
}
}
/// Signs into the underlying games service.
Future<void> initialize() async {
try {
await gs.GamesServices.signIn();
// The API is unclear so we're checking to be sure. The above call
// returns a String, not a boolean, and there's no documentation
// as to whether every non-error result means we're safely signed in.
final signedIn = await gs.GamesServices.isSignedIn;
_signedInCompleter.complete(signedIn);
} catch (e) {
_log.severe('Cannot log into GamesServices: $e');
_signedInCompleter.complete(false);
}
}
/// Launches the platform's UI overlay with achievements.
Future<void> showAchievements() async {
if (!await signedIn) {
_log.severe('Trying to show achievements when not logged in.');
return;
}
try {
await gs.GamesServices.showAchievements();
} catch (e) {
_log.severe('Cannot show achievements: $e');
}
}
/// Launches the platform's UI overlay with leaderboard(s).
Future<void> showLeaderboard() async {
if (!await signedIn) {
_log.severe('Trying to show leaderboard when not logged in.');
return;
}
try {
await gs.GamesServices.showLeaderboards(
// TODO: When ready, change both these leaderboard IDs.
iOSLeaderboardID: "some_id_from_app_store",
androidLeaderboardID: "sOmE_iD_fRoM_gPlAy",
);
} catch (e) {
_log.severe('Cannot show leaderboard: $e');
}
}
/// Submits [score] to the leaderboard.
Future<void> submitLeaderboardScore(Score score) async {
if (!await signedIn) {
_log.warning('Trying to submit leaderboard when not logged in.');
return;
}
_log.info('Submitting $score to leaderboard.');
try {
await gs.GamesServices.submitScore(
score: gs.Score(
// TODO: When ready, change these leaderboard IDs.
iOSLeaderboardID: 'some_id_from_app_store',
androidLeaderboardID: 'sOmE_iD_fRoM_gPlAy',
value: score.score,
),
);
} catch (e) {
_log.severe('Cannot submit leaderboard score: $e');
}
}
}
| samples/game_template/lib/src/games_services/games_services.dart/0 | {
"file_path": "samples/game_template/lib/src/games_services/games_services.dart",
"repo_id": "samples",
"token_count": 1314
} | 1,351 |
// 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';
import 'persistence/settings_persistence.dart';
/// An class that holds settings like [playerName] or [musicOn],
/// and saves them to an injected persistence store.
class SettingsController {
final SettingsPersistence _persistence;
/// Whether or not the sound is on at all. This overrides both music
/// and sound.
ValueNotifier<bool> muted = ValueNotifier(false);
ValueNotifier<String> playerName = ValueNotifier('Player');
ValueNotifier<bool> soundsOn = ValueNotifier(false);
ValueNotifier<bool> musicOn = ValueNotifier(false);
/// Creates a new instance of [SettingsController] backed by [persistence].
SettingsController({required SettingsPersistence persistence})
: _persistence = persistence;
/// Asynchronously loads values from the injected persistence store.
Future<void> loadStateFromPersistence() async {
await Future.wait([
_persistence
// On the web, sound can only start after user interaction, so
// we start muted there.
// On any other platform, we start unmuted.
.getMuted(defaultValue: kIsWeb)
.then((value) => muted.value = value),
_persistence.getSoundsOn().then((value) => soundsOn.value = value),
_persistence.getMusicOn().then((value) => musicOn.value = value),
_persistence.getPlayerName().then((value) => playerName.value = value),
]);
}
void setPlayerName(String name) {
playerName.value = name;
_persistence.savePlayerName(playerName.value);
}
void toggleMusicOn() {
musicOn.value = !musicOn.value;
_persistence.saveMusicOn(musicOn.value);
}
void toggleMuted() {
muted.value = !muted.value;
_persistence.saveMuted(muted.value);
}
void toggleSoundsOn() {
soundsOn.value = !soundsOn.value;
_persistence.saveSoundsOn(soundsOn.value);
}
}
| samples/game_template/lib/src/settings/settings.dart/0 | {
"file_path": "samples/game_template/lib/src/settings/settings.dart",
"repo_id": "samples",
"token_count": 671
} | 1,352 |
{
"offices": [
{
"address": "Aabogade 15\n8200 Aarhus\nDenmark",
"id": "aarhus",
"image": "https://lh3.googleusercontent.com/tpBMFN5os8K-qXIHiAX5SZEmN5fCzIGrj9FdJtbZPUkC91ookSoY520NYn7fK5yqmh1L1m3F2SJA58v6Qps3JusdrxoFSwk6Ajv2K88",
"lat": 56.172249,
"lng": 10.187372,
"name": "Aarhus",
"phone": "",
"region": "europe"
},
{
"address": "Claude Debussylaan 34\n1082 MD, Amsterdam\nNetherlands",
"id": "amsterdam",
"image": "https://lh3.googleusercontent.com/gG1zKXcSmRyYWHwUn2Z0MITpdqwb52RAEp3uthG2J5Xl-4_Wz7_WmoM6T_TBg6Ut3L1eF-8XENO10sxVIFdQHilj8iRG29wROpSoug",
"lat": 52.337801,
"lng": 4.872066,
"name": "Amsterdam",
"phone": "",
"region": "europe"
},
{
"address": "2300 Traverwood Dr.\nAnn Arbor, MI 48105\nUnited States",
"id": "ann-arbor",
"image": "https://lh3.googleusercontent.com/Iim0OVcAgg9vmXc5ADn9KvOQFplrMZ8hBTg2biiTtuWPy_r56cy4Byx1ROk6coGt7knQdmx_jO45VX1kiCJZ0QzEtS97AP_BYG4F2w",
"lat": 42.3063848,
"lng": -83.7140833,
"name": "Ann Arbor",
"phone": "+1 734-332-6500",
"region": "north-america"
},
{
"address": "Fragkokklisias 7\nAthens 151 25\nGreece",
"id": "athens",
"image": "https://lh3.googleusercontent.com/XroZnqewSrO6KuvXM5hDHtjUJzUcRQLZYfCKs4jP44dKezRvNx58uxaqUKS4fQ2eXzG2TpJNJ1X2xtfBe7Prl5hSG_xjPEF1xLtFodM",
"lat": 38.03902,
"lng": 23.804595,
"name": "Athens",
"phone": "",
"region": "europe"
},
{
"address": "10 10th Street NE\nAtlanta, GA 30309\nUnited States",
"id": "atlanta",
"image": "https://lh3.googleusercontent.com/py7Qvqqoec1MB0dMKnGWn7ju9wET_dIneTb24U-ri8XAsECJnOaBoNmvfa51PIaC0rlsyQvQXvAK8RdLqpkhpkRSzmhNKqb-tY2_",
"lat": 33.781827,
"lng": -84.387301,
"name": "Atlanta",
"phone": "+1 404-487-9000",
"region": "north-america"
},
{
"address": "500 W 2nd St\nSuite 2900\nAustin, TX 78701\nUnited States",
"id": "austin",
"image": "https://lh3.googleusercontent.com/WFaJgWPdd7xPL7CQHizlqEzLDjT_GUAiWHIWUM0PiVSsv8q3Rjt9QgbyQazuQwYfN5qLORajv8eKSHlKwZo-M89T2Y12zFSxSIme08c",
"lat": 30.266035,
"lng": -97.749237,
"name": "Austin",
"phone": "+1 512-343-5283",
"region": "north-america"
},
{
"address": "No. 3, RMZ Infinity \u2013 Tower E\nOld Madras Road\n4th and 5th Floors\nBangalore, 560 016, India",
"id": "bangalore",
"image": "https://lh3.googleusercontent.com/YDyQevoY-D0eZQ9sYHp8dQjpFF5JpLfLK-0OM-uJK1oNK3_LRnGJAM0uXi9qb9UigKnVIIXlIgidxhRlnaB_FPtUOqPzrsCSiFZyoQ",
"lat": 12.99332,
"lng": 77.660176,
"name": "Bangalore",
"phone": "+91-80-67218000",
"region": "asia-pacific"
},
{
"address": "57 Park Ventures Ecoplex\n14th Floor, Wireless Road\nBangkok, 10330, Thailand",
"id": "bangkok",
"image": "https://lh3.googleusercontent.com/nh9uOUPj6iWjKZSHIrnkfGhIWGBb8thguRM5_ehCOkyF-qfwzYciDJFVRSvQ6QxlSA6eZUMkzgdW9zR0Gab2ZZPg8NlB7V_V3wB5",
"lat": 13.742866,
"lng": 100.547983,
"name": "Bangkok",
"phone": "",
"region": "asia-pacific"
},
{
"address": "6th Floor, Tower B, Raycom InfoTech Park\nNo. 2 Kexueyuan South Road\nZhongguancun Beijing 100190",
"id": "beijing",
"image": "https://lh3.googleusercontent.com/v_tD3VvC8-dnhqSF9xhj5Hx7F_bb3-wieM19i-Ho2C3by6mt7-JpPc7KsYVHUZFqQl5ON3adVEV1N4OlzSvHLrr3sr4GtXErDbGC",
"lat": 39.9848878,
"lng": 116.3265708,
"name": "Beijing",
"phone": "+86-10-62503000",
"region": "asia-pacific"
},
{
"address": "Boulevard Corporate Tower\nAv. dos Andradas, 3000 - Andares 14-17\nSanta Efig\u00eania\nBelo Horizonte\n30260-070, Brazil",
"id": "belo-horizonte",
"image": "https://lh3.googleusercontent.com/f7F8gTi9GSgAZR3lv24I1yb-D0wRlDy0lQTcxCB4yJGtSgxrWdKoB3dX3J8SMrjYLwOSXquO3LuGFUE82QUjzVK9buHGNIRUPGpqM3E",
"lat": -19.920225,
"lng": -43.920845,
"name": "Belo Horizonte",
"phone": "+55-31-2128-6800",
"region": "latin-america"
},
{
"address": "Tucholskystra\u00dfe 2\n10117 Berlin\nGermany",
"id": "berlin",
"image": "https://lh3.googleusercontent.com/XcPyEMiSlLdZJq7nh3orGy3UqjtUHdhxXiwn52ZY47wfEChfZNDO78zDy9H0tBeegogZBZpIE0Q9mdVBGN4aQ0M5vfgz8ZWMEe43Mg",
"lat": 52.5231079,
"lng": 13.39203120000002,
"name": "Berlin",
"phone": "+49 30 303986300",
"region": "europe"
},
{
"address": "Carrera 11A 94 - 45\nCentro Empresarial Oxo Centre\nBogota, Colombia",
"id": "bogota",
"image": "https://lh3.googleusercontent.com/_APoV1zAR0g5_pXVDlT2ovgNQfr3zvjOuj4HFHViiy2ahyjapJMXlYRE48qYMyFTWXJybbK4psz-fQ82QhMhO0keYJ27I8tNTHe_ww",
"lat": 4.678267,
"lng": -74.046901,
"name": "Bogota",
"phone": "+57 (1) 5939400",
"region": "latin-america"
},
{
"address": "2600 Pearl Street\nBoulder, CO 80302\nUnited States",
"id": "boulder",
"image": "https://lh3.googleusercontent.com/lF9KBhOolmb958FFmMdLwFcedQAn1wEsVleBRrJQmyfhvD3u4lwCneR09ADJ9sG4tMBP5LDSLkn9bkbavzyqqql_0X7hj39dzl-n1w",
"lat": 40.021693,
"lng": -105.260139,
"name": "Boulder",
"phone": "+1 303-245-0086",
"region": "north-america"
},
{
"address": "2930 Pearl St\nBoulder, CO 80301\nUnited States",
"id": "boulder-pearl",
"image": "https://lh3.googleusercontent.com/_JvBccdhLZSIxenZEubM2Qu8Eky6udmnwekH7BhjI1EUo8mCDXDHa0Z7mfNzvZtlmiXI6b6w8U-PY47oUQhPtvYazGS4mG8S61Rr",
"lat": 40.021948,
"lng": -105.253978,
"name": "Boulder \u2013 Pearl Place",
"phone": "+1 303-245-0086",
"region": "north-america"
},
{
"address": "3333 Walnut St\nBoulder CO, 80301\nUnited States",
"id": "boulder-walnut",
"image": "https://lh3.googleusercontent.com/nGvIFmh9d2J68l-U7gYdQAqLZkLNNS_pqhNMtGopMujEpZEneMSH75NFr1WmXJC0GafDLyTVSpnqbuj5Tfjjjk889Zk23dIggqNN",
"lat": 40.01993,
"lng": -105.24936,
"name": "Boulder \u2013 Walnut",
"phone": "+1 303-245-0086",
"region": "north-america"
},
{
"address": "Chaussee d'Etterbeek 180\n1040 Brussels\nBelgium",
"id": "brussels",
"image": "https://lh3.googleusercontent.com/Vdcj2ozYBIOyJLAhRyQic7xjw-OfQ_F5b8M9Kaom_56M2zp8UW65Lm1bYJLLEc4_U4tXfAp-CA81U2O2tdHcXPdsCEUO0hyK_SFKF-Y",
"lat": 50.839315,
"lng": 4.380984,
"name": "Brussels",
"phone": "",
"region": "europe"
},
{
"address": "Alicia M. De Justo 350, 2nd Floor\nBuenos Aires, C1107AAH\nArgentina",
"id": "buenos-aires",
"image": "https://lh3.googleusercontent.com/08n-ZBH23cWYWAbRo7_uZ6VObzDOLdfvxiAy4vZvX2I_FBn4vlUl_qiwALWBMUp7gQ4LEkj7aW6gB_jdJWNmnsmYEKbWzNsh0EaYpw",
"lat": -34.602734,
"lng": -58.366992,
"name": "Buenos Aires",
"phone": "+54-11-5530-3000",
"region": "latin-america"
},
{
"address": "355 Main Street\nCambridge, MA 02142\nUnited States",
"id": "cambridge",
"image": "https://lh3.googleusercontent.com/OLL4nJ-esDQ3JFh2XpWSpX8WnO69yzFpYPWIy9yL_2WFapf74z_ZYvfqb4XkF0_hT2rCi3pzN2Y-yglQ-jWMw3u89YKwn4GfdT7FfQ",
"lat": 42.362757,
"lng": -71.087109,
"name": "Cambridge",
"phone": "+1 617-575-1300",
"region": "north-america"
},
{
"address": "200 West Franklin Street\nChapel Hill, NC 27516\nUnited States",
"id": "chapel-hill",
"image": "https://lh3.googleusercontent.com/AHShjZrvscMoWixuAd0zIXqER2wKMXtoqX4edIzur3FRLJ3DBDIAQqD6PZqB4it_ApAVyitFkjsRPER38oX6XHYOl9mxKbLCXrAQKA",
"lat": 35.912445,
"lng": -79.058488,
"name": "Chapel Hill",
"phone": "",
"region": "north-america"
},
{
"address": "210 Carpenter Ave\nChicago, IL 60607\nUnited States",
"id": "chicago-carpenter",
"image": "https://lh3.googleusercontent.com/pgZ_JGnbpqS4P8H29c6hOCQcLXiG1EZEw5W92FKddWuUTW8618AwIho27aAFPmniDUpH_jS3mCpAx3nY6WkT46oetsFMC__SrPCUmw",
"lat": 41.88609,
"lng": -87.65333,
"name": "Chicago \u2013 Carpenter",
"phone": "",
"region": "north-america"
},
{
"address": "320 N. Morgan, Suite 600\nChicago, IL 60607\nUnited States",
"id": "chicago-fulton",
"image": "https://lh3.googleusercontent.com/ulGqMc02YGomqRC2EN0JP7jOL-6qaIvhCq225DwyeP7b8l-H7ZTWkYDwVKHc0Z4nXEq_TBRCqqPfcc3N8WHm54XpOh16Yx73F4ng",
"lat": 41.8873457,
"lng": -87.6526874,
"name": "Chicago \u2013 Fulton Market",
"phone": "+1 312-840-4100",
"region": "north-america"
},
{
"address": "Skt. Petri Passage 5\n1165 Copenhagen\nDenmark",
"id": "copenhagen",
"image": "https://lh3.googleusercontent.com/SNSbrYGI_ZBuCl_S8aRh63IIta895tqIUUX3ZT0FWmK7ykhJRy_HNtzoud7XrohnjnSAkuXg9YykkFZqbvkRiZQC7osXrZzGerWdmG8",
"lat": 55.680452,
"lng": 12.570071,
"name": "Copenhagen",
"phone": "+45 3370 2600",
"region": "europe"
},
{
"address": "52 Henry St.\n3rd Floor\nDetroit, MI 48201\nUnited States",
"id": "detroit",
"image": "https://lh3.googleusercontent.com/WEP2INGXZc9vRv1ii6KDZGoRFPyumV466B3RzUwyzf8W81a7du2KGXlDEqS5g0nbOHsYTAvagFGVJskSonpt6wJWN2mVq8ti7JYPtvs",
"lat": 42.340458,
"lng": -83.054494,
"name": "Detroit",
"phone": "+1 248-593-4003",
"region": "north-america"
},
{
"address": "TECOM Zone, Dubai Internet City\nDubai, United Arab Emirates",
"id": "dubai",
"image": "https://lh3.googleusercontent.com/xw0iylnw3b3-qxwoNzLSLJlAAPtkF1KONnIoBTDHtURr04fzH9DeO08GYvEsKYQtE9GCdOMTk_s08H6-btSquKo3moeILfc3Kpu4MA",
"lat": 25.0929,
"lng": 55.1591,
"name": "Dubai",
"phone": "+971 4 4509500",
"region": "africa-middle-east"
},
{
"address": "Gordon House\nBarrow St\nDublin 4\nIreland",
"id": "dublin",
"image": "https://lh3.googleusercontent.com/1z3Fhr6nKlCDeTwc1KoFAMSrnywR0lb8nNdwTI1YgoKSXKIDjQeVB_I3Q8oDZuqqHtlXiUbPmfoUYyAXMObjvMxDcMeTqSY21YvP_A",
"lat": 53.3399526,
"lng": -6.2360967,
"name": "Dublin",
"phone": "",
"region": "europe"
},
{
"address": "Taikoo Hui Tower 1, No.383 Tianhe Road\nGuangzhou, 510620\nChina",
"id": "guangzhou",
"image": "https://lh3.googleusercontent.com/BjYQfVMor1QT5hAkc7DcN6_MJdwaySHY6VJ6IY7mQGJRdXjFZhiP-t4MV_QUbp0tBeuYvuMw3nUetTiI-vFl6-BcialJhhurhFrDVeY",
"lat": 23.1339728,
"lng": 113.3332488,
"name": "Guangzhou",
"phone": "",
"region": "asia-pacific"
},
{
"address": "Sector 15, Part II Village Silokhera\nGurgaon 122001\nIndia",
"id": "gurgaon",
"image": "https://lh3.googleusercontent.com/8plKBiWKmwllCXePad0JJ22u1GG7Qe1hveXlx_xJ87XoiQpclQubwxyGxcDU6tkatpb3oi9MYXjm2XszFi5kGn1flfTtjv6MycBWrQ",
"lat": 28.460581,
"lng": 77.048194,
"name": "Gurgaon",
"phone": "+91-12-44512900",
"region": "asia-pacific"
},
{
"address": "Building 30\nMATAM, Advanced Technology Centre\nHaifa, 3190500\nIsrael ",
"id": "haifa",
"image": "https://lh3.googleusercontent.com/syKfT9cVMzLi0d4_DSiJztWGwcmWct6IEbpAApEFk_G8ym0xyLLxMBT484zROIOZHMSe9N1o-QQrCAqVWfKRSY6EOeJY9Qa1ftwb",
"lat": 32.78897,
"lng": 34.958432,
"name": "Haifa",
"phone": "+972-74-746-6245",
"region": "africa-middle-east"
},
{
"address": "ABC-Strasse 19\n20354 Hamburg\nGermany",
"id": "hamburg",
"image": "https://lh3.googleusercontent.com/66R0svr2--6zNOnrqf6JbeZ-bF39bRfHpExjcTlE_AIlPEPk8jO1LjF39FUbDnJB1gh_FiRFX6aCRg4ACjYRbDqb5lf9PdV6qY4S",
"lat": 53.553752,
"lng": 9.986229,
"name": "Hamburg",
"phone": "49 40-80-81-79-000",
"region": "europe"
},
{
"address": "1 Matheson Street\nCauseway Bay, Hong Kong",
"id": "hong-kong",
"image": "https://lh3.googleusercontent.com/-Ult8_R6TfQAk16CfjSfl6PLypQBYohUjNjE6xeeektZsrP8XwTv7PnVVE-5Ueh3I-2hPnAdRGg6XrMn9IwI7W1h5LJKtlMVe93Wfw",
"lat": 22.278203,
"lng": 114.18176,
"name": "Hong Kong",
"phone": "+852-3923-5400",
"region": "asia-pacific"
},
{
"address": "Survey No. 13, DivyaSree Omega\nKondapur Village\nHyderabad, Telangana 500084\nIndia",
"id": "hyderabad",
"image": "https://lh3.googleusercontent.com/LAEnc0tzA-JSb5XM5oct5paX98QK9zh_aqa_qKcjAoXo2MChgOjdj_EZpgIZsVAvEY-I0bmMmhCBb5gkoVN4ebqCG9ZfjCbo_stJaw",
"lat": 17.458461,
"lng": 78.372452,
"name": "Hyderabad",
"phone": "+91-40-6619-3000",
"region": "asia-pacific"
},
{
"address": "19510 Jamboree Road\nIrvine, CA 92612\nUnited States",
"id": "irvine",
"image": "https://lh3.googleusercontent.com/LWGkhXkRRzWnMlNy_Ps74-VTxB2ISXK0Kkick1SujTLYvNAUqo9_HR7SILSZZsiaiGWsXtx7dR5Hz9Q5psu1MWP9BHtDuGYc_hz_eg",
"lat": 33.658792,
"lng": -117.859322,
"name": "Irvine",
"phone": "+1 949-794-1600",
"region": "north-america"
},
{
"address": "Eski Buyukdere Caddesi No: 209\n34394\nIstanbul, Turkey",
"id": "istanbul",
"image": "https://lh3.googleusercontent.com/_mdN7z1Q-9fKgpHTb1rQJosllxqn7glRJ_G2enX4WPmImuJjLHKw-JBZ8z5B9vMSo12SexGBOD1i2NHXqEy4OaOJekn0g3Fp3bDk_Q",
"lat": 41.081697,
"lng": 29.00859,
"name": "Istanbul",
"phone": "",
"region": "africa-middle-east"
},
{
"address": "Pacific Century Place Tower Level 45 SCBD Lot 10,\nJl. Jend. Sudirman No.53,\nRT.5/RW.3, Senayan, Kby. Baru,\nKota Jakarta Selatan,\nDaerah Khusus Ibukota Jakarta 12190, \nIndonesia",
"id": "jakarta",
"image": "https://lh3.googleusercontent.com/JEaMUfOUq6bxN7jeIN1z2me5-JvlLRkrFJgf_A0GvqtOquU6Tfjg0ecKeR_Ck27L0S1zC2t_4I6nVP6pBdBtSKst7tkJEoC7LyYq",
"lat": -6.227664,
"lng": 106.808471,
"name": "Jakarta",
"phone": "",
"region": "asia-pacific"
},
{
"address": "35 Ballyclare Drive, Building E\nJohannesburg\n2191, South Africa",
"id": "johannesburg",
"image": "https://lh3.googleusercontent.com/EDxefwSgeKyh8zN9VUUGhu3hiBqH7Z3UEOXfZeij7YnUhZLqLElu8dhi4FziOepRun-fjfwIWdf5W8CTG5ZSYMu4k8z9QZjTgjQRuQ",
"lat": -26.0734457,
"lng": 28.032035,
"name": "Johannesburg",
"phone": "",
"region": "africa-middle-east"
},
{
"address": "777 6th Street South\nKirkland, WA\nUnited States",
"id": "kirkland",
"image": "https://lh3.googleusercontent.com/Vgmu21GQbS0pga_tJaG0_35AYOzM64Uxp-zNYyMVnd3oXFHmHeMJpx8UjcsMYdnxbdlFZ4KGFowOtpHxsNlUw8qS21sYBy9jPbqkuA",
"lat": 47.669568,
"lng": -122.196912,
"name": "Kirkland",
"phone": "+1 425-739-5600",
"region": "north-america"
},
{
"address": "51 Breithaupt Street\nKitchener, ON N2H 5G5\nCanada",
"id": "kitchener",
"image": "https://lh3.googleusercontent.com/jUCZzQYnJXCUZ3ZxAEB14qukCV6aGxfh84hExpcpye314DhOWB4jtpUoNDrCtA2laV7qDHBAYGtIuZan9Ir5Hp6_U0B2zTGgPqsb",
"lat": 43.4541137,
"lng": -80.4992423,
"name": "Kitchener",
"phone": "+1-519-880-2300",
"region": "north-america"
},
{
"address": "Axiata Tower\nNo. 9, Jalan Stesen Sentral 5\n50470 Kuala Lumpur\nMalaysia",
"id": "kuala-lumpur",
"image": "https://lh3.googleusercontent.com/c5kAdRoyejY1Z5i9A3hYKfIG55GrKdAc0iJjH-gYo-tWd3JUksvsfZx7LU5yzay4HJmxCQEir2cejbZ2LurYfKL_emC9e9PCDVxd",
"lat": 3.133445,
"lng": 101.684609,
"name": "Kuala Lumpur",
"phone": "",
"region": "asia-pacific"
},
{
"address": "Avenida da Liberdade, 110\nLisbon, 1269-046, Portugal",
"id": "lisbon",
"image": "https://lh3.googleusercontent.com/py3HZVLLpxjMhRL6fgUKmHqGODp6ZH-5abQBHGqyKrCyuoW0t-q0ypNVN_jOfD3ZEO08Y9Q0m-E4ZyuNrMgl-mlaECkCAEyc7Af1",
"lat": 38.718887,
"lng": -9.143781,
"name": "Lisbon",
"phone": "+351 21 122 1803",
"region": "europe"
},
{
"address": "6 Pancras Square\nLondon N1C 4AG\nUnited Kingdom",
"id": "london-6ps",
"image": "https://lh3.googleusercontent.com/WTxWzt3AOcEMwoT2OonLTlc63pa4V-GsYbZg5Hu7rfe9ZioMaRurkxaQ5tOcuC9nZkCyh2IjQb-xMy4Tq8ISrHjfDHmzZXnExTjP",
"lat": 51.533311,
"lng": -0.126026,
"name": "London \u2013 6PS",
"phone": "+44-20-7031-3000",
"region": "europe"
},
{
"address": "Belgrave House\n76 Buckingham Palace Road\nLondon SW1W 9TQ\nUnited Kingdom",
"id": "london-bel",
"image": "https://lh3.googleusercontent.com/bLxZNCaDE2Fdj7woV_9JUJEUfUvTrhI57jHNEeW-OenTspzM21miwz1gGydzZ2Ke_vfRdkqdo4dyN2mJCntC2p4qvRUyipPWppAC9g",
"lat": 51.494961,
"lng": -0.146652,
"name": "London \u2013 BEL",
"phone": "+44-20-7031-3001",
"region": "europe"
},
{
"address": "1\u201313 St Giles High St\nLondon WC2H 8AG\nUnited Kingdom",
"id": "london-csg",
"image": "https://lh3.googleusercontent.com/32nlExbSrV5rJR9Qsqfkbckn6_yd-4QRaoSDmp9JLyaZxojfl9aH1LZSrSvcsT128AUzHqkEfMhTE2miDuOu7gj-7x3Ginqr4rgowg",
"lat": 51.516027,
"lng": -0.12755,
"name": "London \u2013 CSG",
"phone": "+44 (0)20-7031-3000",
"region": "europe"
},
{
"address": "340 Main Street\nLos Angeles, CA 90291\nUnited States",
"id": "los-angeles",
"image": "https://lh3.googleusercontent.com/MWGnaY3t_1-j7YylPpq35rvBU9gIBJIsnrtW95THrBw9N0PWrAVtbHKUBH8OdxyWI9gYdymndmSgwS8tl23GylytyefNC74i4-pniQ",
"lat": 33.995939,
"lng": -118.4766773,
"name": "Los Angeles, US",
"phone": "+1 310-310-6000",
"region": "north-america"
},
{
"address": "811 E Washington Ave\nSuite 700\nMadison, WI 53703\nUnited States",
"id": "madison",
"image": "https://lh3.googleusercontent.com/sQDFJpbQl4EVGfdpHsw_24mxsnUNAnDs6f-00QCj0g_Z38CEqjG4PuLPoS_T6eTOPV3QXX907Kap_TkaE3cEG4fhJWIoWsZELIGyvw",
"lat": 43.081091,
"lng": -89.374619,
"name": "Madison",
"phone": "+1 608-669-9841",
"region": "north-america"
},
{
"address": "Plaza Pablo Ruiz Picasso, I\nMadrid 28020\nSpain",
"id": "madrid",
"image": "https://lh3.googleusercontent.com/x36CdPxkwxxctp0wvDYfTjgTzNgMiZV0xoKeLMwHzdccpJGYUA6a61fSeX1_Rt-lfofMjfUwAhFxd7DbjsE8_393plkTly-T5YkpCA",
"lat": 40.4505331,
"lng": -3.6931161,
"name": "Madrid",
"phone": "+34 91-748-6400",
"region": "europe"
},
{
"address": "161 Collins Street,\nMelbourne VIC 3000,\nAustralia",
"id": "melbourne",
"image": "https://lh3.googleusercontent.com/U_5KiB8x7T-Rrdp90ygnO1kbZxiWJz4G6CbD6_51CjH5zaMP23upWELryFOe99k_AqlPZschCY7Nx--wYufcIV54HnjGcP3lf28X1A",
"lat": -37.815328,
"lng": 144.968737,
"name": "Melbourne",
"phone": "",
"region": "asia-pacific"
},
{
"address": "Google Mexico, S. de R.L. de C.V.\nMontes Urales 445\nLomas de Chapultepec\nMexico City 11000, Mexico",
"id": "mexico-city",
"image": "https://lh3.googleusercontent.com/P_U5ECZJ--t8khoKFxoeeJwa7PZy-3TriZbit5sRJDUdupf3NZRJegsnB4ucLqdLEV3De41fmByckDDC6uHMI82cXIFp4C1WwI1a1g",
"lat": 19.4283793,
"lng": -99.2065518,
"name": "Mexico City",
"phone": "+52 55-5342-8400",
"region": "latin-america"
},
{
"address": "1450 Brickell Ave Ste 900 \nMiami FL 33131\nUnited States",
"id": "miami",
"image": "https://lh3.googleusercontent.com/DTk99d9bCqiCN8sFj3FBr8BdGPYC97PCYbiLbdq6GZ-_Er268DSlvfRM_g8hwA5tOmw_6c3PBjpKpuRQTuXS8H8_hpIlCQKyobyYjQ",
"lat": 25.758473,
"lng": -80.1932144,
"name": "Miami",
"phone": "+1 305-985-7900",
"region": "north-america"
},
{
"address": "Porta Nuova Isola, Building C, Via Federico Confalonieri 4\n20124 Milan\nItaly",
"id": "milan",
"image": "https://lh3.googleusercontent.com/nZ_KE1LqNmW5qb6i-czLlm_yqRJtLmvEmyLRI0BYjqMlOiC_5VmbEI3DeHQyPOHp6PzoN2gKJ0j73BALkddFmDFXOIe9Wwctmt73cqI",
"lat": 45.486147,
"lng": 9.189546,
"name": "Milan",
"phone": "",
"region": "europe"
},
{
"address": "1253 McGill College Avenue\nMontreal, QC H3B 2Y5\nCanada",
"id": "montreal",
"image": "https://lh3.googleusercontent.com/S310Um4pKym8bvHQcQmJLc4ohURWEq3AQHjJ-b5aMY-TpA9P4LCKcxGEg4fik-zSL6MrtiEi8Qt3JbAZl8x-GiI31wfm_myGfb3manQ",
"lat": 45.50191,
"lng": -73.570365,
"name": "Montreal",
"phone": "514-670-8700",
"region": "north-america"
},
{
"address": "7 Balchug St\nMoscow 115035\nRussia",
"id": "moscow",
"image": "https://lh3.googleusercontent.com/i6cwRxcix3LUdviTVKoLG2Ep6q9pjfPIX_nrge-YkgjIvTgCH5QQpSI6wCpKvg0HiH56lHu6K8eAkCrPZUCzspS6Y9K19U47xr4hww",
"lat": 55.746747,
"lng": 37.626435,
"name": "Moscow",
"phone": "+7-495-644-1400",
"region": "europe"
},
{
"address": "1600 Amphitheatre Parkway\nMountain View, CA 94043\nUnited States",
"id": "mountain-view",
"image": "https://lh3.googleusercontent.com/Mh8P8gvVwO7NOXfg8anxwPXRy5oKZJ6Cz_LbFfOVdeIsdDfogmMcMsiW7HD7HD2NOINzAPH_v8dALWSuDiiTjCjRnenI7B3l6Pg4yw",
"lat": 37.421512,
"lng": -122.084101,
"name": "Mountain View",
"phone": "",
"region": "north-america"
},
{
"address": "3 North Avenue\nMaker Maxity, Bandra Kurla Complex\nBandra East\nMumbai, Maharashtra 400051\nIndia",
"id": "mumbai",
"image": "https://lh3.googleusercontent.com/twldrlVORn84fYsOLwNLabfRPQYX-dJAzJtpam-Ea4D7QIY1pvMa9FCMbpjUFA8uniBg6XAh8pMijf9qnjmEm4d17UFkwRGToiv5Ug",
"lat": 19.054364,
"lng": 72.850591,
"name": "Mumbai",
"phone": "+91-22-6611-7150",
"region": "asia-pacific"
},
{
"address": "Erika-Mann-Str. 33\n80636 Munich\nGermany",
"id": "munich",
"image": "https://lh3.googleusercontent.com/sVZqxencTTD84raIgMWd5SbmXZTvQmwUzxj6IakbIGuAua5JDu-Q64uJE-cm3TYeSjKVQo7VSwIODVpwswjtrpwBUvXTa5MDFXoNAw",
"lat": 48.14305556,
"lng": 11.54083333,
"name": "Munich",
"phone": "",
"region": "europe"
},
{
"address": "111 8th Avenue\nNew York, NY 10011\nUnited States",
"id": "new-york",
"image": "https://lh3.googleusercontent.com/BWdXxSOqBpjGFzAJVVr02QQs5XSe33dEeNDG6lXhd-nuv32ruMjD01yBJX3Rk4_xP6glB1ycMvwypEPr6YO665grfWqEEI2LPYUaMg",
"lat": 40.741445,
"lng": -74.003102,
"name": "New York",
"phone": "+1 212-565-0000",
"region": "north-america"
},
{
"address": "Aker Brygge\nBryggegata 6\n0250 Oslo\nNorway",
"id": "oslo",
"image": "https://lh3.googleusercontent.com/lc9jPxaz4CzdC3sD4wFlzml1Y221PvtsisYGenint536WNbyIMY2cp2qnQOmnT0IWPoOCjarwMgK6zddvTcOu6YcAuaVLfQAdqZ2UQg",
"lat": 59.90987,
"lng": 10.72598,
"name": "Oslo",
"phone": "",
"region": "europe"
},
{
"address": "8 Rue de Londres\n75009 Paris\nFrance",
"id": "paris",
"image": "https://lh3.googleusercontent.com/GHZlAB7t3toRGww1NJ6ZC2IpvR0jkgqFkQ0ZvM02dmQWt6fiHIKJZ7Eova959UD0PAapPE2r2TYMe3-dE3jGDgEoqHch0qyjAKvPENc",
"lat": 48.8771,
"lng": 2.33,
"name": "Paris",
"phone": "",
"region": "europe"
},
{
"address": "6425 Penn Avenue\nPittsburgh, PA 15206\nUnited States",
"id": "pittsburgh",
"image": "https://lh3.googleusercontent.com/47kJwc4CR6oGOI2l_su5CJHnEWkrUZlz7LZRGXHgF71xa-0gJc8qCBhnsNoigcNEGFfBpb3y5AxVXJP_TxvHtgUgTrU8zmBm3Two7w",
"lat": 40.45716,
"lng": -79.916596,
"name": "Pittsburgh",
"phone": "+1 412-345-6700",
"region": "north-america"
},
{
"address": "12422 W. Bluff Creek Drive\nPlaya Vista, CA 90094\nUnited States",
"id": "playa-vista",
"image": "https://lh3.googleusercontent.com/xnHVNI6bCcQxJyLV6sG3op8PlJcT9XgMAGmHrXtj5axhCZPH7Tbc9Ppjb2gTCtGbKmilT17B0dKzczOJh9JANh8Wwz0SXH0pEqCOkQ",
"lat": 33.97684,
"lng": -118.407244,
"name": "Playa Vista",
"phone": "",
"region": "north-america"
},
{
"address": "Wells Fargo Building, 309 SW 6th Ave\nPortland, OR 97204\nUnited States",
"id": "portland",
"image": "https://lh3.googleusercontent.com/FMeFmwWFZJD02kj0H73t5v8NPrVOecVxuCl9cA-vLiXgaXErYQxmMXJKvvROgwSNvgPdmRZ4-GQuub74p0dDwJgY37vBNN2vgx7Utw",
"lat": 45.521622,
"lng": -122.677458,
"name": "Portland",
"phone": "",
"region": "north-america"
},
{
"address": "Stroupeznickeho str. 3191/17\nPrague, Czech Republic\n150 00",
"id": "prague",
"image": "https://lh3.googleusercontent.com/jVNKH2mzDQ4Zu1-1G80-nDvLHYE9dmeetv43WG3zo7-dQWJoX1ghtXvviZHDLRG-ScqA804I2guuExY-8pkzIdkYlU28QGOB8Jkkiw",
"lat": 50.070259,
"lng": 14.402642,
"name": "Prague",
"phone": "",
"region": "europe"
},
{
"address": "1600 Seaport Boulevard\nRedwood City, CA 94063\nUnited States",
"id": "redwood-city",
"image": "https://lh3.googleusercontent.com/a7GCRT1go5jQzEQj--A-kq98pURYsO4cTCJPj6azEev7za4Y__Kd3E_khFyn5uxRtPC0Co_ZxzQtqrlXeOSNey8fOSV4pK0ffzSW5A",
"lat": 37.512171,
"lng": -122.201178,
"name": "Redwood City",
"phone": "",
"region": "north-america"
},
{
"address": "1875 Explorer Street \n10th Floor\nReston, VA 20190\nUnited States",
"id": "reston",
"image": "https://lh3.googleusercontent.com/4WuJCZlLflcQjsyhsGX3VSGDEVmC0Ljq291ECgVk3nN89ppnhSbdQIRI1I1-qh5YEf0Yicdc6amuqKz7oAdgLvQoNBrM9Zh3BcUwSw",
"lat": 38.958309,
"lng": -77.359795,
"name": "Reston",
"phone": "+1 202-370-5600",
"region": "north-america"
},
{
"address": "901 Cherry Avenue\nSan Bruno, CA 94066\nUnited States",
"id": "san-bruno",
"image": "https://lh3.googleusercontent.com/zcy-Un_QDZfx7nTlImk-jCocxSUjQAQ4SS0eVdBuNRZz3Nyb5WK_2oGwYpnBEdqjIcv_b-umq_akpWBEylaEp-wXk3pj9-gu6Ko9Igs",
"lat": 37.62816,
"lng": -122.426491,
"name": "San Bruno",
"phone": "",
"region": "north-america"
},
{
"address": "6420 Sequence Dr \nSuite 400\nSan Diego, CA 92121\nUnited States",
"id": "san-diego",
"image": "https://lh3.googleusercontent.com/RgGUUE3ra1j-mQIH8vp6an37hlwduD8uVnaCv8ivo5mX6ekdnZYd0-hlQ1hpQzV0ZgPk7y8h60oWy5MK5VF48ozZMYRXnh1ddJjuVGo",
"lat": 32.90961,
"lng": -117.181899,
"name": "San Diego",
"phone": "+1 858-239-4000",
"region": "north-america"
},
{
"address": "345 Spear Street\nSan Francisco, CA 94105\nUnited States",
"id": "san-francisco",
"image": "https://lh3.googleusercontent.com/OC_0_XdXLar-ytOETAv3uwRGfnLABSRu66hqLQpLrwIhqInPD6ccdZSEu_d5S8wmjc1knb9OM7yNh2K7hoGznvKZOgFlvrxJesd7mQ",
"lat": 37.789972,
"lng": -122.390013,
"name": "San Francisco",
"phone": "+1 415-736-0000",
"region": "north-america"
},
{
"address": "Costanera Sur Rio 2730 \nLas Condes, Santiago\nChile",
"id": "santiago",
"image": "https://lh3.googleusercontent.com/KrMbZzxFsAcNmYg8BQL_qBAekN1bNNJGo1aar8nkFhYXYDYOBmwJc2x1XElkDdIqLdedU5V7QKTGxXne8-f-qAW_bOy1FUqmJ8JM",
"lat": -33.413383,
"lng": -70.605665,
"name": "Santiago",
"phone": "",
"region": "latin-america"
},
{
"address": "Av. Brigadeiro Faria Lima, 3477 \nS\u00e3o Paulo\n04538-133, Brazil",
"id": "sao-paulo",
"image": "https://lh3.googleusercontent.com/MwcGyEZBKkmoycVLcpl_U3gdIJBoWDU8u2kUNq57DmZVkWDyraoaZyQC0HOiFQvNHjVugEiVTWsy-poAsNfDLoSkJ5RoTBi1Hpd4GcI",
"lat": -23.586479,
"lng": -46.682078,
"name": "Sao Paulo",
"phone": "",
"region": "latin-america"
},
{
"address": "601 N. 34th Street\nSeattle, WA 98103\nUnited States",
"id": "seattle",
"image": "https://lh3.googleusercontent.com/pNaRyPV3SkqsVvmdmN0sC-viBupr-41tZM3_cpSNH_3Zdy826gIhM0zHfoowA6SCkcsOkUxDvJ8wG5CodorohisOgR9q_QE7wH1ua-M",
"lat": 47.649316,
"lng": -122.350629,
"name": "Seattle",
"phone": "+1 206-876-1800",
"region": "north-america"
},
{
"address": "Google Korea LLC.\n22nd Floor, Gangnam Finance Centre\n152 Teheran-ro, Gangnam-gu\nSeoul 06236\nSouth Korea",
"id": "seoul",
"image": "https://lh3.googleusercontent.com/i8rfvJIUNpLBkmWWSoetUzFGHUd_RaulLh8F3EHme3FMTUtDs8EVWsrFLuaemh1Zd60p5ndCcKq8-ZQN8eibbua-YNzlzQ8AKtHFzrQ",
"lat": 37.500295,
"lng": 127.036843,
"name": "Seoul",
"phone": "+82-2-531-9000",
"region": "asia-pacific"
},
{
"address": "100 Century Avenue, Pudong\nShanghai 200120\nChina",
"id": "shanghai",
"image": "https://lh3.googleusercontent.com/wFCKLAJvrAoE_GiXqRNa0w4Rsr0iY_SyMGbO2jnIhLXGanYs1c5_BPE8TxQJw-e14uaLDHjY772V-Vv-Kf3GmrIRSlHjoV9yD339wRQ",
"lat": 31.23464,
"lng": 121.507662,
"name": "Shanghai",
"phone": "+86-21-6133-7666",
"region": "asia-pacific"
},
{
"address": "70 Pasir Panjang Road, #03-71, \nMapletree Business City \nSingapore 117371",
"id": "singapore",
"image": "https://lh3.googleusercontent.com/--5H57B8aG4-DX9s79Spo3ygrsI9NMFnZo1uTZzs5s5AeeOvmiy81k__tu9r7JbRTTLzryK-oUy0UREclmD_qfV81VvaT4K9jJa8gg",
"lat": 1.276466,
"lng": 103.798965,
"name": "Singapore",
"phone": "+65 6521-8000",
"region": "asia-pacific"
},
{
"address": "Kungsbron 2 \n111 22 Stockholm\nSweden",
"id": "stockholm",
"image": "https://lh3.googleusercontent.com/Q2016qdodQKowCyzfN14RLYERc2IplyM2FzJvj0kzbW4eLXnIxoFF1eZMc_CwtodxbpyfhfebUrawHtIgFb2kh9-EQnhcaHXpV0Fnw",
"lat": 59.333432,
"lng": 18.054619,
"name": "Stockholm",
"phone": "",
"region": "europe"
},
{
"address": "803 11th Avenue\nSunnyvale, CA 94089\nUnited States",
"id": "sunnyvale",
"image": "https://lh3.googleusercontent.com/xd1Z3wr4cee9gtKQSnrOd-NWjc6UTwpwngElt4pkqukzOf-l0hrgQuRRBzvSjqmF4w1ZAHR1I12grFa5Zhqd9-7dKUitPtpMg51Zrf8",
"lat": 37.403694,
"lng": -122.031583,
"name": "Sunnyvale",
"phone": "",
"region": "north-america"
},
{
"address": "48 Pirrama Road\nSydney, NSW 2009\nAustralia ",
"id": "sydney",
"image": "https://lh3.googleusercontent.com/03Hp4ZwQHs_rWLEWQtrOc62hEHzffD_uoZFCbo56eoeLyZ3L89-Fy5Dd8WcmrGFGK31QC_hZqzuU7f9QhxqjckE7BSLo_arwWjCH1w",
"lat": -33.866638,
"lng": 151.195672,
"name": "Sydney",
"phone": "+61 2 9374 4000",
"region": "asia-pacific"
},
{
"address": "No. 7 XinYi Road Section 5, Taipei\nTaiwan",
"id": "taipei",
"image": "https://lh3.googleusercontent.com/h19TQz36F4jY_ZfQxuP5F-THZbl4nAIGz473uFfLqzD_6kpw-r3b6M_Wbna5QvvymqZ-wdnhkLCRt63Pypnc9GyawNqMlQwM1_BYbg",
"lat": 25.033447,
"lng": 121.564901,
"name": "Taipei",
"phone": "+886 2 8729 6000",
"region": "asia-pacific"
},
{
"address": "Yigal Alon 98\nTel Aviv, 6789141\nIsrael ",
"id": "tel-aviv",
"image": "https://lh3.googleusercontent.com/BZxU1dJCWFmtVeBqVYFC8SmSzX4CCzO5eedosW1s7sv2b2HoKwEno15vICfeQdsc_BGIaysKb8VyF64IB9hbFzMZ_MlQDJhP7kfF",
"lat": 32.070043,
"lng": 34.794087,
"name": "Tel Aviv",
"phone": "+972-74-746-6453",
"region": "africa-middle-east"
},
{
"address": "Roppongi Hills Mori Tower\n6-10-1 Roppongi\nMinato-ku, Tokyo 106-6126\nJapan",
"id": "tokyo-rpg",
"image": "https://lh3.googleusercontent.com/i7PqriAmbeqB7KQ4h_8K0T60DD-oAoz7bvvjlB4vx2267l9QHfKBHb7WUMSutYd88Xu4TRwWqIquL05bYcpTyU_58gWp8Ja2Xo2zOfM",
"lat": 35.66047,
"lng": 139.729231,
"name": "Tokyo \u2013 RPG",
"phone": "+81-3-6384-9000",
"region": "asia-pacific"
},
{
"address": "Shibuya Stream\n3-21-3 Shibuya\nShibuya-ku, Tokyo 150-0002\nJapan",
"id": "tokyo-strm",
"image": "https://lh3.googleusercontent.com/GzaUJcEqlixelFX8dg1qcLPwAb4RpEXr3JMxyxpgSTWL17Gso_aq3NeMtQPES7f_JdIrGr9YTBSt08XgNAeoLSkxr3Ue_J0cW3VMCw",
"lat": 35.6572564,
"lng": 139.7028246,
"name": "Tokyo \u2013 STRM",
"phone": "+81-3-6384-9000",
"region": "asia-pacific"
},
{
"address": "111 Richmond Street West\nToronto, ON M5H 2G4\nCanada",
"id": "toronto",
"image": "https://lh3.googleusercontent.com/vZUQcWL3r_bsHBRP-Z0XfhMxjlSAAe9sZLlw5rbBzqsM6w-WVjnTZGaw3w-PkqkhHPy0x-2Xzg_gishFkVjn5r3epKifwhmRc741",
"lat": 43.650477,
"lng": -79.383858,
"name": "Toronto",
"phone": "416-915-8200",
"region": "north-america"
},
{
"address": "Graben 19\n1010 Wien\nAustria",
"id": "vienna",
"image": "https://lh3.googleusercontent.com/roYQN_TnYd_fP0FCdZxA6lMLbp-h7PyPlDBKwVdfVWKkOCxmLjFHqm-n7hrcakcXHS1FzjXW5XWF_MApzuGIrvy2cewCYd7Z9q5MUw",
"lat": 48.209351,
"lng": 16.368419,
"name": "Vienna",
"phone": "",
"region": "europe"
},
{
"address": "Emilii Plater 53\n00-113 Warsaw\nPoland ",
"id": "warsaw",
"image": "https://lh3.googleusercontent.com/jTf0m2s5A2qS25ArE3x6Tl1KXtpv3JmHIfcBuw7f-JHsTR0tMiyUVeHO1wBeJ2eEGcAWUbTe3b9B8iP8wyL-TROS5zxmMofMHsnf",
"lat": 52.233448,
"lng": 21.001668,
"name": "Warsaw",
"phone": "+48 22 207 19 00",
"region": "europe"
},
{
"address": "25 Massachusetts Avenue\nWashington DC, 20001\nUnited States",
"id": "washington-dc",
"image": "https://lh3.googleusercontent.com/6rKu8CCH6nMVKjwpnxDlgf_Sdlc7jk83QBVhoLikzEyibYTZkvNPn-QPCJTv3AkjUYf2dHcE15UvPsrg18xNd4R8_eg3b-yn01yXgQ",
"lat": 38.898337,
"lng": -77.010286,
"name": "Washington DC",
"phone": " (202) 346-1100",
"region": "north-america"
},
{
"address": "Gen. Jozefa Bema nr 2\n50-265 Wroclaw\nPoland",
"id": "wroclaw",
"image": "https://lh3.googleusercontent.com/Or6dY4MCUCbMnDv4kG8J7u-QTsWhvbqbAbMN9Vp38aJAS7ec7A39gYddcEGbrwd_veFeZo2phypqc1ABk20PZ9jCVxZfuNGYS7j3LDc",
"lat": 51.117687,
"lng": 17.041737,
"name": "Wroclaw",
"phone": "+48 (71) 73 41 000",
"region": "europe"
},
{
"address": "Brandschenkestrasse 110\n8002 Z\u00fcrich\nSwitzerland",
"id": "zurich",
"image": "https://lh3.googleusercontent.com/kmEsDEYzbMlluwDPYkeEEBpAvL9MJbXZR3hD3uettOqE8T7lbXvV508j4d4QngB7iwYZa8YYlXiVnGWfZ4ZvTJbputGXsfxrLGhD3tI",
"lat": 47.365063,
"lng": 8.524425,
"name": "Zurich",
"phone": "+41 44 668 18 00",
"region": "europe"
}
],
"regions": [
{
"coords": {
"lat": 2.9660291,
"lng": 1.3271339
},
"id": "africa-middle-east",
"name": "Africa & Middle East",
"zoom": 3.0
},
{
"coords": {
"lat": 0.0524811,
"lng": 127.6560787
},
"id": "asia-pacific",
"name": "Asia Pacific",
"zoom": 3.0
},
{
"coords": {
"lat": 46.1352815,
"lng": 7.4033438
},
"id": "europe",
"name": "Europe",
"zoom": 4.0
},
{
"coords": {
"lat": -17.5554497,
"lng": -99.2316195
},
"id": "latin-america",
"name": "Latin America",
"zoom": 3.0
},
{
"coords": {
"lat": 45.7128252,
"lng": -97.1547448
},
"id": "north-america",
"name": "North America",
"zoom": 4.0
}
]
}
| samples/google_maps/assets/locations.json/0 | {
"file_path": "samples/google_maps/assets/locations.json",
"repo_id": "samples",
"token_count": 25316
} | 1,353 |
import UIKit
import Flutter
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| samples/ios_app_clip/ios/Runner/AppDelegate.swift/0 | {
"file_path": "samples/ios_app_clip/ios/Runner/AppDelegate.swift",
"repo_id": "samples",
"token_count": 121
} | 1,354 |
include: package:analysis_defaults/flutter.yaml
| samples/isolate_example/analysis_options.yaml/0 | {
"file_path": "samples/isolate_example/analysis_options.yaml",
"repo_id": "samples",
"token_count": 15
} | 1,355 |
// 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 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// Computes the nth number in the Fibonacci sequence.
int fib(int n) {
var a = n - 1;
var b = n - 2;
if (n == 1) {
return 0;
} else if (n == 0) {
return 1;
} else {
return (fib(a) + fib(b));
}
}
class PerformancePage extends StatefulWidget {
const PerformancePage({super.key});
@override
State<PerformancePage> createState() => _PerformancePageState();
}
class _PerformancePageState extends State<PerformancePage> {
Future<void> computeFuture = Future.value();
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SmoothAnimationWidget(),
Container(
alignment: Alignment.bottomCenter,
padding: const EdgeInsets.only(top: 150),
child: Column(
children: [
FutureBuilder(
future: computeFuture,
builder: (context, snapshot) {
return ElevatedButton(
style: ElevatedButton.styleFrom(elevation: 8.0),
onPressed: switch (snapshot.connectionState) {
ConnectionState.done => () =>
handleComputeOnMain(context),
_ => null
},
child: const Text('Compute on Main'),
);
},
),
FutureBuilder(
future: computeFuture,
builder: (context, snapshot) {
return ElevatedButton(
style: ElevatedButton.styleFrom(elevation: 8.0),
onPressed: switch (snapshot.connectionState) {
ConnectionState.done => () =>
handleComputeOnSecondary(context),
_ => null
},
child: const Text('Compute on Secondary'));
},
),
],
),
),
],
),
);
}
void handleComputeOnMain(BuildContext context) {
var future = computeOnMainIsolate()
..then((_) {
var snackBar = const SnackBar(
content: Text('Main Isolate Done!'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
setState(() {
computeFuture = future;
});
}
void handleComputeOnSecondary(BuildContext context) {
var future = computeOnSecondaryIsolate()
..then((_) {
var snackBar = const SnackBar(
content: Text('Secondary Isolate Done!'),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
setState(() {
computeFuture = future;
});
}
Future<void> computeOnMainIsolate() async {
// A delay is added here to give Flutter the chance to redraw the UI at
// least once before the computation (which, since it's run on the main
// isolate, will lock up the app) begins executing.
await Future<void>.delayed(const Duration(milliseconds: 100));
fib(45);
}
Future<void> computeOnSecondaryIsolate() async {
// Compute the Fibonacci series on a secondary isolate.
await compute(fib, 45);
}
}
class SmoothAnimationWidget extends StatefulWidget {
const SmoothAnimationWidget({super.key});
@override
State<SmoothAnimationWidget> createState() => _SmoothAnimationWidgetState();
}
class _SmoothAnimationWidgetState extends State<SmoothAnimationWidget>
with TickerProviderStateMixin {
late final AnimationController _animationController;
late final Animation<BorderRadius?> _borderAnimation;
@override
void initState() {
super.initState();
_animationController =
AnimationController(duration: const Duration(seconds: 1), vsync: this);
_borderAnimation = BorderRadiusTween(
begin: BorderRadius.circular(100.0),
end: BorderRadius.circular(0.0))
.animate(_animationController);
_animationController.repeat(reverse: true);
}
@override
Widget build(BuildContext context) {
return Center(
child: AnimatedBuilder(
animation: _borderAnimation,
builder: (context, child) {
return Container(
alignment: Alignment.bottomCenter,
width: 350,
height: 200,
decoration: BoxDecoration(
gradient: const LinearGradient(
begin: Alignment.topLeft,
colors: [
Colors.blueAccent,
Colors.redAccent,
],
),
borderRadius: _borderAnimation.value,
),
child: const FlutterLogo(
size: 200,
),
);
},
),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
}
| samples/isolate_example/lib/performance_page.dart/0 | {
"file_path": "samples/isolate_example/lib/performance_page.dart",
"repo_id": "samples",
"token_count": 2482
} | 1,356 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/isolate_example/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/isolate_example/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,357 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
| samples/material_3_demo/android/gradle.properties/0 | {
"file_path": "samples/material_3_demo/android/gradle.properties",
"repo_id": "samples",
"token_count": 31
} | 1,358 |
// 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 'color_palettes_screen.dart';
import 'component_screen.dart';
import 'constants.dart';
import 'elevation_screen.dart';
import 'typography_screen.dart';
class Home extends StatefulWidget {
const Home({
super.key,
required this.useLightMode,
required this.useMaterial3,
required this.colorSelected,
required this.handleBrightnessChange,
required this.handleMaterialVersionChange,
required this.handleColorSelect,
required this.handleImageSelect,
required this.colorSelectionMethod,
required this.imageSelected,
});
final bool useLightMode;
final bool useMaterial3;
final ColorSeed colorSelected;
final ColorImageProvider imageSelected;
final ColorSelectionMethod colorSelectionMethod;
final void Function(bool useLightMode) handleBrightnessChange;
final void Function() handleMaterialVersionChange;
final void Function(int value) handleColorSelect;
final void Function(int value) handleImageSelect;
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> with SingleTickerProviderStateMixin {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
late final AnimationController controller;
late final CurvedAnimation railAnimation;
bool controllerInitialized = false;
bool showMediumSizeLayout = false;
bool showLargeSizeLayout = false;
int screenIndex = ScreenSelected.component.value;
@override
initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: transitionLength.toInt() * 2),
value: 0,
vsync: this,
);
railAnimation = CurvedAnimation(
parent: controller,
curve: const Interval(0.5, 1.0),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final double width = MediaQuery.of(context).size.width;
final AnimationStatus status = controller.status;
if (width > mediumWidthBreakpoint) {
if (width > largeWidthBreakpoint) {
showMediumSizeLayout = false;
showLargeSizeLayout = true;
} else {
showMediumSizeLayout = true;
showLargeSizeLayout = false;
}
if (status != AnimationStatus.forward &&
status != AnimationStatus.completed) {
controller.forward();
}
} else {
showMediumSizeLayout = false;
showLargeSizeLayout = false;
if (status != AnimationStatus.reverse &&
status != AnimationStatus.dismissed) {
controller.reverse();
}
}
if (!controllerInitialized) {
controllerInitialized = true;
controller.value = width > mediumWidthBreakpoint ? 1 : 0;
}
}
void handleScreenChanged(int screenSelected) {
setState(() {
screenIndex = screenSelected;
});
}
Widget createScreenFor(
ScreenSelected screenSelected,
bool showNavBarExample,
) =>
switch (screenSelected) {
ScreenSelected.component => Expanded(
child: OneTwoTransition(
animation: railAnimation,
one: FirstComponentList(
showNavBottomBar: showNavBarExample,
scaffoldKey: scaffoldKey,
showSecondList: showMediumSizeLayout || showLargeSizeLayout),
two: SecondComponentList(
scaffoldKey: scaffoldKey,
),
),
),
ScreenSelected.color => const ColorPalettesScreen(),
ScreenSelected.typography => const TypographyScreen(),
ScreenSelected.elevation => const ElevationScreen()
};
PreferredSizeWidget createAppBar() {
return AppBar(
title: widget.useMaterial3
? const Text('Material 3')
: const Text('Material 2'),
actions: !showMediumSizeLayout && !showLargeSizeLayout
? [
_BrightnessButton(
handleBrightnessChange: widget.handleBrightnessChange,
),
_Material3Button(
handleMaterialVersionChange: widget.handleMaterialVersionChange,
),
_ColorSeedButton(
handleColorSelect: widget.handleColorSelect,
colorSelected: widget.colorSelected,
colorSelectionMethod: widget.colorSelectionMethod,
),
_ColorImageButton(
handleImageSelect: widget.handleImageSelect,
imageSelected: widget.imageSelected,
colorSelectionMethod: widget.colorSelectionMethod,
)
]
: [Container()],
);
}
Widget _trailingActions() => Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Flexible(
child: _BrightnessButton(
handleBrightnessChange: widget.handleBrightnessChange,
showTooltipBelow: false,
),
),
Flexible(
child: _Material3Button(
handleMaterialVersionChange: widget.handleMaterialVersionChange,
showTooltipBelow: false,
),
),
Flexible(
child: _ColorSeedButton(
handleColorSelect: widget.handleColorSelect,
colorSelected: widget.colorSelected,
colorSelectionMethod: widget.colorSelectionMethod,
),
),
Flexible(
child: _ColorImageButton(
handleImageSelect: widget.handleImageSelect,
imageSelected: widget.imageSelected,
colorSelectionMethod: widget.colorSelectionMethod,
),
),
],
);
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: controller,
builder: (context, child) {
return NavigationTransition(
scaffoldKey: scaffoldKey,
animationController: controller,
railAnimation: railAnimation,
appBar: createAppBar(),
body: createScreenFor(
ScreenSelected.values[screenIndex], controller.value == 1),
navigationRail: NavigationRail(
extended: showLargeSizeLayout,
destinations: navRailDestinations,
selectedIndex: screenIndex,
onDestinationSelected: (index) {
setState(() {
screenIndex = index;
handleScreenChanged(screenIndex);
});
},
trailing: Expanded(
child: Padding(
padding: const EdgeInsets.only(bottom: 20),
child: showLargeSizeLayout
? _ExpandedTrailingActions(
useLightMode: widget.useLightMode,
handleBrightnessChange: widget.handleBrightnessChange,
useMaterial3: widget.useMaterial3,
handleMaterialVersionChange:
widget.handleMaterialVersionChange,
handleImageSelect: widget.handleImageSelect,
handleColorSelect: widget.handleColorSelect,
colorSelectionMethod: widget.colorSelectionMethod,
imageSelected: widget.imageSelected,
colorSelected: widget.colorSelected,
)
: _trailingActions(),
),
),
),
navigationBar: NavigationBars(
onSelectItem: (index) {
setState(() {
screenIndex = index;
handleScreenChanged(screenIndex);
});
},
selectedIndex: screenIndex,
isExampleBar: false,
),
);
},
);
}
}
class _BrightnessButton extends StatelessWidget {
const _BrightnessButton({
required this.handleBrightnessChange,
this.showTooltipBelow = true,
});
final Function handleBrightnessChange;
final bool showTooltipBelow;
@override
Widget build(BuildContext context) {
final isBright = Theme.of(context).brightness == Brightness.light;
return Tooltip(
preferBelow: showTooltipBelow,
message: 'Toggle brightness',
child: IconButton(
icon: isBright
? const Icon(Icons.dark_mode_outlined)
: const Icon(Icons.light_mode_outlined),
onPressed: () => handleBrightnessChange(!isBright),
),
);
}
}
class _Material3Button extends StatelessWidget {
const _Material3Button({
required this.handleMaterialVersionChange,
this.showTooltipBelow = true,
});
final void Function() handleMaterialVersionChange;
final bool showTooltipBelow;
@override
Widget build(BuildContext context) {
final useMaterial3 = Theme.of(context).useMaterial3;
return Tooltip(
preferBelow: showTooltipBelow,
message: 'Switch to Material ${useMaterial3 ? 2 : 3}',
child: IconButton(
icon: useMaterial3
? const Icon(Icons.filter_2)
: const Icon(Icons.filter_3),
onPressed: handleMaterialVersionChange,
),
);
}
}
class _ColorSeedButton extends StatelessWidget {
const _ColorSeedButton({
required this.handleColorSelect,
required this.colorSelected,
required this.colorSelectionMethod,
});
final void Function(int) handleColorSelect;
final ColorSeed colorSelected;
final ColorSelectionMethod colorSelectionMethod;
@override
Widget build(BuildContext context) {
return PopupMenuButton(
icon: Icon(
Icons.palette_outlined,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
tooltip: 'Select a seed color',
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
itemBuilder: (context) {
return List.generate(ColorSeed.values.length, (index) {
ColorSeed currentColor = ColorSeed.values[index];
return PopupMenuItem(
value: index,
enabled: currentColor != colorSelected ||
colorSelectionMethod != ColorSelectionMethod.colorSeed,
child: Wrap(
children: [
Padding(
padding: const EdgeInsets.only(left: 10),
child: Icon(
currentColor == colorSelected &&
colorSelectionMethod != ColorSelectionMethod.image
? Icons.color_lens
: Icons.color_lens_outlined,
color: currentColor.color,
),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: Text(currentColor.label),
),
],
),
);
});
},
onSelected: handleColorSelect,
);
}
}
class _ColorImageButton extends StatelessWidget {
const _ColorImageButton({
required this.handleImageSelect,
required this.imageSelected,
required this.colorSelectionMethod,
});
final void Function(int) handleImageSelect;
final ColorImageProvider imageSelected;
final ColorSelectionMethod colorSelectionMethod;
@override
Widget build(BuildContext context) {
return PopupMenuButton(
icon: Icon(
Icons.image_outlined,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
tooltip: 'Select a color extraction image',
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
itemBuilder: (context) {
return List.generate(ColorImageProvider.values.length, (index) {
ColorImageProvider currentImageProvider =
ColorImageProvider.values[index];
return PopupMenuItem(
value: index,
enabled: currentImageProvider != imageSelected ||
colorSelectionMethod != ColorSelectionMethod.image,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 10),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 48),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image(
image: NetworkImage(
ColorImageProvider.values[index].url),
),
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: Text(currentImageProvider.label),
),
],
),
);
});
},
onSelected: handleImageSelect,
);
}
}
class _ExpandedTrailingActions extends StatelessWidget {
const _ExpandedTrailingActions({
required this.useLightMode,
required this.handleBrightnessChange,
required this.useMaterial3,
required this.handleMaterialVersionChange,
required this.handleColorSelect,
required this.handleImageSelect,
required this.imageSelected,
required this.colorSelected,
required this.colorSelectionMethod,
});
final void Function(bool) handleBrightnessChange;
final void Function() handleMaterialVersionChange;
final void Function(int) handleImageSelect;
final void Function(int) handleColorSelect;
final bool useLightMode;
final bool useMaterial3;
final ColorImageProvider imageSelected;
final ColorSeed colorSelected;
final ColorSelectionMethod colorSelectionMethod;
@override
Widget build(BuildContext context) {
final screenHeight = MediaQuery.of(context).size.height;
final trailingActionsBody = Container(
constraints: const BoxConstraints.tightFor(width: 250),
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
const Text('Brightness'),
Expanded(child: Container()),
Switch(
value: useLightMode,
onChanged: (value) {
handleBrightnessChange(value);
})
],
),
Row(
children: [
useMaterial3
? const Text('Material 3')
: const Text('Material 2'),
Expanded(child: Container()),
Switch(
value: useMaterial3,
onChanged: (_) {
handleMaterialVersionChange();
})
],
),
const Divider(),
_ExpandedColorSeedAction(
handleColorSelect: handleColorSelect,
colorSelected: colorSelected,
colorSelectionMethod: colorSelectionMethod,
),
const Divider(),
_ExpandedImageColorAction(
handleImageSelect: handleImageSelect,
imageSelected: imageSelected,
colorSelectionMethod: colorSelectionMethod,
),
],
),
);
return screenHeight > 740
? trailingActionsBody
: SingleChildScrollView(child: trailingActionsBody);
}
}
class _ExpandedColorSeedAction extends StatelessWidget {
const _ExpandedColorSeedAction({
required this.handleColorSelect,
required this.colorSelected,
required this.colorSelectionMethod,
});
final void Function(int) handleColorSelect;
final ColorSeed colorSelected;
final ColorSelectionMethod colorSelectionMethod;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 200.0),
child: GridView.count(
crossAxisCount: 3,
children: List.generate(
ColorSeed.values.length,
(i) => IconButton(
icon: const Icon(Icons.radio_button_unchecked),
color: ColorSeed.values[i].color,
isSelected: colorSelected.color == ColorSeed.values[i].color &&
colorSelectionMethod == ColorSelectionMethod.colorSeed,
selectedIcon: const Icon(Icons.circle),
onPressed: () {
handleColorSelect(i);
},
tooltip: ColorSeed.values[i].label,
),
),
),
);
}
}
class _ExpandedImageColorAction extends StatelessWidget {
const _ExpandedImageColorAction({
required this.handleImageSelect,
required this.imageSelected,
required this.colorSelectionMethod,
});
final void Function(int) handleImageSelect;
final ColorImageProvider imageSelected;
final ColorSelectionMethod colorSelectionMethod;
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 150.0),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: GridView.count(
crossAxisCount: 3,
children: List.generate(
ColorImageProvider.values.length,
(i) => Tooltip(
message: ColorImageProvider.values[i].name,
child: InkWell(
borderRadius: BorderRadius.circular(4.0),
onTap: () => handleImageSelect(i),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Material(
borderRadius: BorderRadius.circular(4.0),
elevation: imageSelected == ColorImageProvider.values[i] &&
colorSelectionMethod == ColorSelectionMethod.image
? 3
: 0,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(4.0),
child: Image(
image: NetworkImage(ColorImageProvider.values[i].url),
),
),
),
),
),
),
),
),
),
),
);
}
}
class NavigationTransition extends StatefulWidget {
const NavigationTransition(
{super.key,
required this.scaffoldKey,
required this.animationController,
required this.railAnimation,
required this.navigationRail,
required this.navigationBar,
required this.appBar,
required this.body});
final GlobalKey<ScaffoldState> scaffoldKey;
final AnimationController animationController;
final CurvedAnimation railAnimation;
final Widget navigationRail;
final Widget navigationBar;
final PreferredSizeWidget appBar;
final Widget body;
@override
State<NavigationTransition> createState() => _NavigationTransitionState();
}
class _NavigationTransitionState extends State<NavigationTransition> {
late final AnimationController controller;
late final CurvedAnimation railAnimation;
late final ReverseAnimation barAnimation;
bool controllerInitialized = false;
bool showDivider = false;
@override
void initState() {
super.initState();
controller = widget.animationController;
railAnimation = widget.railAnimation;
barAnimation = ReverseAnimation(
CurvedAnimation(
parent: controller,
curve: const Interval(0.0, 0.5),
),
);
}
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return Scaffold(
key: widget.scaffoldKey,
appBar: widget.appBar,
body: Row(
children: <Widget>[
RailTransition(
animation: railAnimation,
backgroundColor: colorScheme.surface,
child: widget.navigationRail,
),
widget.body,
],
),
bottomNavigationBar: BarTransition(
animation: barAnimation,
backgroundColor: colorScheme.surface,
child: widget.navigationBar,
),
endDrawer: const NavigationDrawerSection(),
);
}
}
final List<NavigationRailDestination> navRailDestinations = appBarDestinations
.map(
(destination) => NavigationRailDestination(
icon: Tooltip(
message: destination.label,
child: destination.icon,
),
selectedIcon: Tooltip(
message: destination.label,
child: destination.selectedIcon,
),
label: Text(destination.label),
),
)
.toList();
class SizeAnimation extends CurvedAnimation {
SizeAnimation(Animation<double> parent)
: super(
parent: parent,
curve: const Interval(
0.2,
0.8,
curve: Curves.easeInOutCubicEmphasized,
),
reverseCurve: Interval(
0,
0.2,
curve: Curves.easeInOutCubicEmphasized.flipped,
),
);
}
class OffsetAnimation extends CurvedAnimation {
OffsetAnimation(Animation<double> parent)
: super(
parent: parent,
curve: const Interval(
0.4,
1.0,
curve: Curves.easeInOutCubicEmphasized,
),
reverseCurve: Interval(
0,
0.2,
curve: Curves.easeInOutCubicEmphasized.flipped,
),
);
}
class RailTransition extends StatefulWidget {
const RailTransition(
{super.key,
required this.animation,
required this.backgroundColor,
required this.child});
final Animation<double> animation;
final Widget child;
final Color backgroundColor;
@override
State<RailTransition> createState() => _RailTransition();
}
class _RailTransition extends State<RailTransition> {
late Animation<Offset> offsetAnimation;
late Animation<double> widthAnimation;
@override
void didChangeDependencies() {
super.didChangeDependencies();
// The animations are only rebuilt by this method when the text
// direction changes because this widget only depends on Directionality.
final bool ltr = Directionality.of(context) == TextDirection.ltr;
widthAnimation = Tween<double>(
begin: 0,
end: 1,
).animate(SizeAnimation(widget.animation));
offsetAnimation = Tween<Offset>(
begin: ltr ? const Offset(-1, 0) : const Offset(1, 0),
end: Offset.zero,
).animate(OffsetAnimation(widget.animation));
}
@override
Widget build(BuildContext context) {
return ClipRect(
child: DecoratedBox(
decoration: BoxDecoration(color: widget.backgroundColor),
child: Align(
alignment: Alignment.topLeft,
widthFactor: widthAnimation.value,
child: FractionalTranslation(
translation: offsetAnimation.value,
child: widget.child,
),
),
),
);
}
}
class BarTransition extends StatefulWidget {
const BarTransition(
{super.key,
required this.animation,
required this.backgroundColor,
required this.child});
final Animation<double> animation;
final Color backgroundColor;
final Widget child;
@override
State<BarTransition> createState() => _BarTransition();
}
class _BarTransition extends State<BarTransition> {
late final Animation<Offset> offsetAnimation;
late final Animation<double> heightAnimation;
@override
void initState() {
super.initState();
offsetAnimation = Tween<Offset>(
begin: const Offset(0, 1),
end: Offset.zero,
).animate(OffsetAnimation(widget.animation));
heightAnimation = Tween<double>(
begin: 0,
end: 1,
).animate(SizeAnimation(widget.animation));
}
@override
Widget build(BuildContext context) {
return ClipRect(
child: DecoratedBox(
decoration: BoxDecoration(color: widget.backgroundColor),
child: Align(
alignment: Alignment.topLeft,
heightFactor: heightAnimation.value,
child: FractionalTranslation(
translation: offsetAnimation.value,
child: widget.child,
),
),
),
);
}
}
class OneTwoTransition extends StatefulWidget {
const OneTwoTransition({
super.key,
required this.animation,
required this.one,
required this.two,
});
final Animation<double> animation;
final Widget one;
final Widget two;
@override
State<OneTwoTransition> createState() => _OneTwoTransitionState();
}
class _OneTwoTransitionState extends State<OneTwoTransition> {
late final Animation<Offset> offsetAnimation;
late final Animation<double> widthAnimation;
@override
void initState() {
super.initState();
offsetAnimation = Tween<Offset>(
begin: const Offset(1, 0),
end: Offset.zero,
).animate(OffsetAnimation(widget.animation));
widthAnimation = Tween<double>(
begin: 0,
end: mediumWidthBreakpoint,
).animate(SizeAnimation(widget.animation));
}
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Flexible(
flex: mediumWidthBreakpoint.toInt(),
child: widget.one,
),
if (widthAnimation.value.toInt() > 0) ...[
Flexible(
flex: widthAnimation.value.toInt(),
child: FractionalTranslation(
translation: offsetAnimation.value,
child: widget.two,
),
)
],
],
);
}
}
| samples/material_3_demo/lib/home.dart/0 | {
"file_path": "samples/material_3_demo/lib/home.dart",
"repo_id": "samples",
"token_count": 11350
} | 1,359 |
// 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 'package:go_router/go_router.dart';
import 'package:url_launcher/link.dart';
import '../data.dart';
import 'author_details.dart';
class BookDetailsScreen extends StatelessWidget {
final Book? book;
const BookDetailsScreen({
super.key,
this.book,
});
@override
Widget build(BuildContext context) {
if (book == null) {
return const Scaffold(
body: Center(
child: Text('No book found.'),
),
);
}
return Scaffold(
appBar: AppBar(
title: Text(book!.title),
),
body: Center(
child: Column(
children: [
Text(
book!.title,
style: Theme.of(context).textTheme.headlineMedium,
),
Text(
book!.author.name,
style: Theme.of(context).textTheme.titleMedium,
),
TextButton(
child: const Text('View author (Push)'),
onPressed: () {
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (context) => AuthorDetailsScreen(
author: book!.author,
onBookTapped: (book) {
GoRouter.of(context).go('/books/all/book/${book.id}');
},
),
),
);
},
),
Link(
uri: Uri.parse('/authors/author/${book!.author.id}'),
builder: (context, followLink) => TextButton(
onPressed: followLink,
child: const Text('View author (Link)'),
),
),
],
),
),
);
}
}
| samples/navigation_and_routing/lib/src/screens/book_details.dart/0 | {
"file_path": "samples/navigation_and_routing/lib/src/screens/book_details.dart",
"repo_id": "samples",
"token_count": 1026
} | 1,360 |
// 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_test/flutter_test.dart';
void main() {
testWidgets('empty test', (tester) async {});
}
| samples/navigation_and_routing/test/widget_test.dart/0 | {
"file_path": "samples/navigation_and_routing/test/widget_test.dart",
"repo_id": "samples",
"token_count": 96
} | 1,361 |
// 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:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'place.dart';
import 'place_tracker_app.dart';
import 'stub_data.dart';
class PlaceDetails extends StatefulWidget {
final Place place;
const PlaceDetails({
required this.place,
super.key,
});
@override
State<PlaceDetails> createState() => _PlaceDetailsState();
}
class _PlaceDetailsState extends State<PlaceDetails> {
late Place _place;
GoogleMapController? _mapController;
final Set<Marker> _markers = {};
final TextEditingController _nameController = TextEditingController();
final TextEditingController _descriptionController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_place.name),
backgroundColor: Colors.green[700],
actions: [
Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0),
child: IconButton(
icon: const Icon(Icons.save, size: 30.0),
onPressed: () {
_onChanged(_place);
Navigator.pop(context);
},
),
),
],
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: _detailsBody(),
),
);
}
@override
void initState() {
_place = widget.place;
_nameController.text = _place.name;
_descriptionController.text = _place.description ?? '';
return super.initState();
}
Widget _detailsBody() {
return ListView(
padding: const EdgeInsets.fromLTRB(24.0, 12.0, 24.0, 12.0),
children: [
_NameTextField(
controller: _nameController,
onChanged: (value) {
setState(() {
_place = _place.copyWith(name: value);
});
},
),
_DescriptionTextField(
controller: _descriptionController,
onChanged: (value) {
setState(() {
_place = _place.copyWith(description: value);
});
},
),
_StarBar(
rating: _place.starRating,
onChanged: (value) {
setState(() {
_place = _place.copyWith(starRating: value);
});
},
),
_Map(
center: _place.latLng,
mapController: _mapController,
onMapCreated: _onMapCreated,
markers: _markers,
),
const _Reviews(),
],
);
}
void _onMapCreated(GoogleMapController controller) {
_mapController = controller;
setState(() {
_markers.add(Marker(
markerId: MarkerId(_place.latLng.toString()),
position: _place.latLng,
));
});
}
void _onChanged(Place value) {
// Replace the place with the modified version.
final newPlaces = List<Place>.from(context.read<AppState>().places);
final index = newPlaces.indexWhere((place) => place.id == value.id);
newPlaces[index] = value;
context.read<AppState>().setPlaces(newPlaces);
}
}
class _DescriptionTextField extends StatelessWidget {
final TextEditingController controller;
final ValueChanged<String> onChanged;
const _DescriptionTextField({
required this.controller,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 16.0),
child: TextField(
decoration: const InputDecoration(
labelText: 'Description',
labelStyle: TextStyle(fontSize: 18.0),
),
style: const TextStyle(fontSize: 20.0, color: Colors.black87),
maxLines: null,
autocorrect: true,
controller: controller,
onChanged: (value) {
onChanged(value);
},
),
);
}
}
class _Map extends StatelessWidget {
final LatLng center;
final GoogleMapController? mapController;
final ArgumentCallback<GoogleMapController> onMapCreated;
final Set<Marker> markers;
const _Map({
required this.center,
required this.mapController,
required this.onMapCreated,
required this.markers,
});
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.symmetric(vertical: 16.0),
elevation: 4,
child: SizedBox(
width: 340,
height: 240,
child: GoogleMap(
onMapCreated: onMapCreated,
initialCameraPosition: CameraPosition(
target: center,
zoom: 16,
),
markers: markers,
zoomGesturesEnabled: false,
rotateGesturesEnabled: false,
tiltGesturesEnabled: false,
scrollGesturesEnabled: false,
),
),
);
}
}
class _NameTextField extends StatelessWidget {
final TextEditingController controller;
final ValueChanged<String> onChanged;
const _NameTextField({
required this.controller,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 16),
child: TextField(
decoration: const InputDecoration(
labelText: 'Name',
labelStyle: TextStyle(fontSize: 18),
),
style: const TextStyle(fontSize: 20, color: Colors.black87),
autocorrect: true,
controller: controller,
onChanged: (value) {
onChanged(value);
},
),
);
}
}
class _Reviews extends StatelessWidget {
const _Reviews();
@override
Widget build(BuildContext context) {
return Column(
children: [
const Padding(
padding: EdgeInsets.fromLTRB(0, 12, 0, 8),
child: Align(
alignment: Alignment.topLeft,
child: Text(
'Reviews',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline,
color: Colors.black87,
),
),
),
),
Column(
children: StubData.reviewStrings
.map((reviewText) => _buildSingleReview(reviewText))
.toList(),
),
],
);
}
Widget _buildSingleReview(String reviewText) {
return Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Row(
children: [
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
border: Border.all(
width: 3,
color: Colors.grey,
),
),
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'5',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
Icon(
Icons.star,
color: Colors.amber,
size: 36,
),
],
),
),
const SizedBox(width: 16),
Expanded(
child: Text(
reviewText,
style: const TextStyle(fontSize: 20, color: Colors.black87),
maxLines: null,
),
),
],
),
),
Divider(
height: 8,
color: Colors.grey[700],
),
],
);
}
}
class _StarBar extends StatelessWidget {
static const int maxStars = 5;
final int rating;
final ValueChanged<int> onChanged;
const _StarBar({
required this.rating,
required this.onChanged,
}) : assert(rating >= 0 && rating <= maxStars);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(maxStars, (index) {
return IconButton(
icon: const Icon(Icons.star),
iconSize: 40,
color: rating > index ? Colors.amber : Colors.grey[400],
onPressed: () {
onChanged(index + 1);
},
);
}).toList(),
);
}
}
| samples/place_tracker/lib/place_details.dart/0 | {
"file_path": "samples/place_tracker/lib/place_details.dart",
"repo_id": "samples",
"token_count": 4255
} | 1,362 |
# Platform Channel Samples
A sample app which demonstrates how to use `MethodChannel`, `EventChannel`, `BasicMessageChannel` and `MessageCodec` in Flutter.
## Goals
* Demonstrate how to use `MethodChannel` to invoke platform methods.
* Demonstrate how to use `EventChannel` to listen continuous value changes from the platform.
* Demonstrate how to use `BasicMessageChannel` and `MessageCodec` to send messages of different types across the platform.
## The important bits
### [Method Channel demo](./lib/src/method_channel_demo.dart)
Demonstrates how to implement a `MethodChannel` to increment and decrement a
counter.
### [Event Channel demo](./lib/src/event_channel_demo.dart)
Demonstrates how to implement an `EventChannel` to listen to value changes from
the Accelerometer sensor from native side.
### [Platform Image demo](./lib/src/platform_image_demo.dart)
Demonstrates how to implement a `BasicMessageChannel` using
`StandardMessageCodec` to load an image from native asset.
### [Basic Message Channel demo](./lib/src/pet_list_screen.dart)
Demonstrates how to implement `BasicMessageChannel` using `JSONMessageCodec`,
`BinaryCodec` and `StringCodec` to send and receive data about pets.
## Questions/issues
If you have a general question about Platform Channels in 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 [here](https://github.com/flutter/samples/issues).
| samples/platform_channels/README.md/0 | {
"file_path": "samples/platform_channels/README.md",
"repo_id": "samples",
"token_count": 467
} | 1,363 |
// Copyright 2020 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform_channels/main.dart' as app;
void main() {
group('AddPetDetails tests', () {
var petList = <Map>[];
testWidgets('Enter pet details', (tester) async {
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler(
const BasicMessageChannel<dynamic>(
'jsonMessageCodecDemo', JSONMessageCodec()),
(dynamic message) async {
petList.add(message as Map);
},
);
var router = app.router('/petListScreen/addPetDetails');
await tester.pumpWidget(
MaterialApp.router(
routerConfig: router,
),
);
// Enter the breed of cat.
await tester.enterText(find.byType(TextField), 'Persian');
// Select cat from the pet type.
await tester.tap(find.text('Cat'));
// Initially the list will be empty.
expect(petList, isEmpty);
await tester.tap(find.byIcon(Icons.add));
expect(petList, isNotEmpty);
expect(petList.last['breed'], 'Persian');
// Navigate back to /petListScreen
await tester.pumpAndSettle();
expect(router.routeInformationProvider.value.uri.path, '/petListScreen');
});
});
}
| samples/platform_channels/test/src/add_pet_details_test.dart/0 | {
"file_path": "samples/platform_channels/test/src/add_pet_details_test.dart",
"repo_id": "samples",
"token_count": 575
} | 1,364 |
#include "Generated.xcconfig"
| samples/platform_design/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "samples/platform_design/ios/Flutter/Debug.xcconfig",
"repo_id": "samples",
"token_count": 12
} | 1,365 |
name: platform_view_swift
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ^3.2.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.4
dev_dependencies:
analysis_defaults:
path: ../analysis_defaults
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| samples/platform_view_swift/pubspec.yaml/0 | {
"file_path": "samples/platform_view_swift/pubspec.yaml",
"repo_id": "samples",
"token_count": 133
} | 1,366 |
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
| samples/provider_counter/macos/Runner/Configs/Debug.xcconfig/0 | {
"file_path": "samples/provider_counter/macos/Runner/Configs/Debug.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,367 |
// Copyright 2022 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' show Platform;
import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_layout_grid/flutter_layout_grid.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:math_expressions/math_expressions.dart';
import 'package:window_size/window_size.dart';
void main() {
if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
WidgetsFlutterBinding.ensureInitialized();
setWindowTitle('Simplistic Calculator');
setWindowMinSize(const Size(600, 500));
}
runApp(
const ProviderScope(
child: CalculatorApp(),
),
);
}
@immutable
class CalculatorState {
const CalculatorState({
required this.buffer,
required this.calcHistory,
required this.mode,
required this.error,
});
final String buffer;
final List<String> calcHistory;
final CalculatorEngineMode mode;
final String error;
CalculatorState copyWith({
String? buffer,
List<String>? calcHistory,
CalculatorEngineMode? mode,
String? error,
}) =>
CalculatorState(
buffer: buffer ?? this.buffer,
calcHistory: calcHistory ?? this.calcHistory,
mode: mode ?? this.mode,
error: error ?? this.error,
);
}
enum CalculatorEngineMode { input, result }
class CalculatorEngine extends StateNotifier<CalculatorState> {
CalculatorEngine()
: super(
const CalculatorState(
buffer: '0',
calcHistory: [],
mode: CalculatorEngineMode.result,
error: '',
),
);
void addToBuffer(String str, {bool continueWithResult = false}) {
if (state.mode == CalculatorEngineMode.result) {
state = state.copyWith(
buffer: (continueWithResult ? state.buffer : '') + str,
mode: CalculatorEngineMode.input,
error: '',
);
} else {
state = state.copyWith(
buffer: state.buffer + str,
error: '',
);
}
}
void backspace() {
final charList = Characters(state.buffer).toList();
if (charList.isNotEmpty) {
charList.length = charList.length - 1;
}
state = state.copyWith(buffer: charList.join());
}
void clear() {
state = state.copyWith(buffer: '');
}
void evaluate() {
try {
final parser = Parser();
final cm = ContextModel();
final exp = parser.parse(state.buffer);
final result = exp.evaluate(EvaluationType.REAL, cm) as double;
switch (result) {
case double(isInfinite: true):
state = state.copyWith(
error: 'Result is Infinite',
buffer: '',
mode: CalculatorEngineMode.result,
);
case double(isNaN: true):
state = state.copyWith(
error: 'Result is Not a Number',
buffer: '',
mode: CalculatorEngineMode.result,
);
default:
final resultStr = result.ceil() == result
? result.toInt().toString()
: result.toString();
state = state.copyWith(
buffer: resultStr,
mode: CalculatorEngineMode.result,
calcHistory: [
'${state.buffer} = $resultStr',
...state.calcHistory,
]);
}
} catch (err) {
state = state.copyWith(
error: err.toString(),
buffer: '',
mode: CalculatorEngineMode.result,
);
}
}
}
final calculatorStateProvider =
StateNotifierProvider<CalculatorEngine, CalculatorState>(
(_) => CalculatorEngine());
class ButtonDefinition {
const ButtonDefinition({
required this.areaName,
required this.label,
required this.op,
this.type = CalcButtonType.outlined,
});
final String areaName;
final String label;
final CalculatorEngineCallback op;
final CalcButtonType type;
}
final buttonDefinitions = <ButtonDefinition>[
ButtonDefinition(
areaName: 'clear',
op: (engine) => engine.clear(),
label: 'AC',
),
ButtonDefinition(
areaName: 'bkspc',
op: (engine) => engine.backspace(),
label: '⌫',
),
ButtonDefinition(
areaName: 'lparen',
op: (engine) => engine.addToBuffer('('),
label: '(',
),
ButtonDefinition(
areaName: 'rparen',
op: (engine) => engine.addToBuffer(')'),
label: ')',
),
ButtonDefinition(
areaName: 'sqrt',
op: (engine) => engine.addToBuffer('sqrt('),
label: '√',
),
ButtonDefinition(
areaName: 'pow',
op: (engine) => engine.addToBuffer('^'),
label: '^',
),
ButtonDefinition(
areaName: 'abs',
op: (engine) => engine.addToBuffer('abs('),
label: 'Abs',
),
ButtonDefinition(
areaName: 'sgn',
op: (engine) => engine.addToBuffer('sgn('),
label: 'Sgn',
),
ButtonDefinition(
areaName: 'ceil',
op: (engine) => engine.addToBuffer('ceil('),
label: 'Ceil',
),
ButtonDefinition(
areaName: 'floor',
op: (engine) => engine.addToBuffer('floor('),
label: 'Floor',
),
ButtonDefinition(
areaName: 'e',
op: (engine) => engine.addToBuffer('e('),
label: 'e',
),
ButtonDefinition(
areaName: 'ln',
op: (engine) => engine.addToBuffer('ln('),
label: 'ln',
),
ButtonDefinition(
areaName: 'sin',
op: (engine) => engine.addToBuffer('sin('),
label: 'Sin',
),
ButtonDefinition(
areaName: 'cos',
op: (engine) => engine.addToBuffer('cos('),
label: 'Cos',
),
ButtonDefinition(
areaName: 'tan',
op: (engine) => engine.addToBuffer('tan('),
label: 'Tan',
),
ButtonDefinition(
areaName: 'fact',
op: (engine) => engine.addToBuffer('!'),
label: '!',
),
ButtonDefinition(
areaName: 'arcsin',
op: (engine) => engine.addToBuffer('arcsin('),
label: 'Arc Sin',
),
ButtonDefinition(
areaName: 'arccos',
op: (engine) => engine.addToBuffer('arccos('),
label: 'Arc Cos',
),
ButtonDefinition(
areaName: 'arctan',
op: (engine) => engine.addToBuffer('arctan('),
label: 'Arc Tan',
),
ButtonDefinition(
areaName: 'mod',
op: (engine) => engine.addToBuffer('%'),
label: 'Mod',
),
ButtonDefinition(
areaName: 'seven',
op: (engine) => engine.addToBuffer('7'),
label: '7',
),
ButtonDefinition(
areaName: 'eight',
op: (engine) => engine.addToBuffer('8'),
label: '8',
),
ButtonDefinition(
areaName: 'nine',
op: (engine) => engine.addToBuffer('9'),
label: '9',
),
ButtonDefinition(
areaName: 'four',
op: (engine) => engine.addToBuffer('4'),
label: '4',
),
ButtonDefinition(
areaName: 'five',
op: (engine) => engine.addToBuffer('5'),
label: '5',
),
ButtonDefinition(
areaName: 'six',
op: (engine) => engine.addToBuffer('6'),
label: '6',
),
ButtonDefinition(
areaName: 'one',
op: (engine) => engine.addToBuffer('1'),
label: '1',
),
ButtonDefinition(
areaName: 'two',
op: (engine) => engine.addToBuffer('2'),
label: '2',
),
ButtonDefinition(
areaName: 'three',
op: (engine) => engine.addToBuffer('3'),
label: '3',
),
ButtonDefinition(
areaName: 'zero',
op: (engine) => engine.addToBuffer('0'),
label: '0',
),
ButtonDefinition(
areaName: 'point',
op: (engine) => engine.addToBuffer('.'),
label: '.',
),
ButtonDefinition(
areaName: 'equals',
op: (engine) => engine.evaluate(),
label: '=',
type: CalcButtonType.elevated,
),
ButtonDefinition(
areaName: 'plus',
op: (engine) => engine.addToBuffer('+', continueWithResult: true),
label: '+',
),
ButtonDefinition(
areaName: 'minus',
op: (engine) => engine.addToBuffer('-', continueWithResult: true),
label: '-',
),
ButtonDefinition(
areaName: 'multiply',
op: (engine) => engine.addToBuffer('*', continueWithResult: true),
label: '*',
),
ButtonDefinition(
areaName: 'divide',
op: (engine) => engine.addToBuffer('/', continueWithResult: true),
label: '/',
),
];
class CalculatorApp extends ConsumerWidget {
const CalculatorApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(calculatorStateProvider);
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light(),
home: Scaffold(
body: Container(
color: Colors.white,
child: SafeArea(
child: LayoutGrid(
areas: '''
display display display display history
clear bkspc lparen rparen history
sqrt pow abs sgn history
ceil floor e ln history
sin cos tan fact history
arcsin arccos arctan mod history
seven eight nine divide history
four five six multiply history
one two three minus history
zero point equals plus history
''',
columnSizes: [1.fr, 1.fr, 1.fr, 1.fr, 2.fr],
rowSizes: [
2.fr,
1.fr,
1.fr,
1.fr,
1.fr,
1.fr,
2.fr,
2.fr,
2.fr,
2.fr
],
children: [
NamedAreaGridPlacement(
areaName: 'display',
child: SizedBox.expand(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 8),
child: state.error.isEmpty
? AutoSizeText(
state.buffer,
textAlign: TextAlign.end,
style: const TextStyle(
fontSize: 80,
color: Colors.black,
),
maxLines: 2,
)
: AutoSizeText(
state.error,
textAlign: TextAlign.start,
style: const TextStyle(
fontSize: 80,
color: Colors.red,
),
maxLines: 2,
),
),
),
),
...buttonDefinitions.map(
(definition) => NamedAreaGridPlacement(
areaName: definition.areaName,
child: CalcButton(
label: definition.label,
op: definition.op,
type: definition.type,
),
),
),
NamedAreaGridPlacement(
areaName: 'history',
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: ListView(
children: [
const ListTile(
title: Text(
'History',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
...state.calcHistory.map(
(result) => ListTile(
title: Text(result),
),
)
],
),
),
),
],
),
),
),
),
);
}
}
typedef CalculatorEngineCallback = void Function(CalculatorEngine engine);
enum CalcButtonType { outlined, elevated }
class CalcButton extends ConsumerWidget {
const CalcButton({
super.key,
required this.op,
required this.label,
required this.type,
});
final CalculatorEngineCallback op;
final String label;
final CalcButtonType type;
@override
Widget build(BuildContext context, WidgetRef ref) {
final buttonConstructor = switch (type) {
CalcButtonType.elevated => ElevatedButton.new,
_ => OutlinedButton.new,
};
return SizedBox.expand(
child: Padding(
padding: const EdgeInsets.all(4),
child: buttonConstructor(
autofocus: false,
clipBehavior: Clip.none,
onPressed: () => op(ref.read(calculatorStateProvider.notifier)),
child: AutoSizeText(
label,
style: const TextStyle(fontSize: 40, color: Colors.black54),
),
),
),
);
}
}
| samples/simplistic_calculator/lib/main.dart/0 | {
"file_path": "samples/simplistic_calculator/lib/main.dart",
"repo_id": "samples",
"token_count": 6387
} | 1,368 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| samples/simplistic_calculator/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "samples/simplistic_calculator/macos/Runner/Configs/Release.xcconfig",
"repo_id": "samples",
"token_count": 32
} | 1,369 |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'app_state_manager.dart';
import 'formatting_toolbar.dart' show ToggleButtonsState;
import 'replacements.dart';
class AppState {
const AppState({
required this.replacementsController,
required this.textEditingDeltaHistory,
required this.toggleButtonsState,
});
final ReplacementTextEditingController replacementsController;
final List<TextEditingDelta> textEditingDeltaHistory;
final Set<ToggleButtonsState> toggleButtonsState;
AppState copyWith({
ReplacementTextEditingController? replacementsController,
List<TextEditingDelta>? textEditingDeltaHistory,
Set<ToggleButtonsState>? toggleButtonsState,
}) {
return AppState(
replacementsController:
replacementsController ?? this.replacementsController,
textEditingDeltaHistory:
textEditingDeltaHistory ?? this.textEditingDeltaHistory,
toggleButtonsState: toggleButtonsState ?? this.toggleButtonsState,
);
}
}
class AppStateWidget extends StatefulWidget {
const AppStateWidget({super.key, required this.child});
final Widget child;
static AppStateWidgetState of(BuildContext context) {
return context.findAncestorStateOfType<AppStateWidgetState>()!;
}
@override
State<AppStateWidget> createState() => AppStateWidgetState();
}
class AppStateWidgetState extends State<AppStateWidget> {
AppState _data = AppState(
replacementsController: ReplacementTextEditingController(
text: 'The quick brown fox jumps over the lazy dog.'),
textEditingDeltaHistory: <TextEditingDelta>[],
toggleButtonsState: <ToggleButtonsState>{},
);
void updateTextEditingDeltaHistory(List<TextEditingDelta> textEditingDeltas) {
_data = _data.copyWith(textEditingDeltaHistory: <TextEditingDelta>[
..._data.textEditingDeltaHistory,
...textEditingDeltas
]);
setState(() {});
}
void updateToggleButtonsStateOnSelectionChanged(
TextSelection selection, ReplacementTextEditingController controller) {
// When the selection changes we want to check the replacements at the new
// selection. Enable/disable toggle buttons based on the replacements found
// at the new selection.
final List<TextStyle> replacementStyles =
controller.getReplacementsAtSelection(selection);
final Set<ToggleButtonsState> hasChanged = {};
if (replacementStyles.isEmpty) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..removeAll({
ToggleButtonsState.bold,
ToggleButtonsState.italic,
ToggleButtonsState.underline,
}),
);
}
for (final TextStyle style in replacementStyles) {
// See [_updateToggleButtonsStateOnButtonPressed] for how
// Bold, Italic and Underline are encoded into [style]
if (style.fontWeight != null &&
!hasChanged.contains(ToggleButtonsState.bold)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..add(ToggleButtonsState.bold),
);
hasChanged.add(ToggleButtonsState.bold);
}
if (style.fontStyle != null &&
!hasChanged.contains(ToggleButtonsState.italic)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..add(ToggleButtonsState.italic),
);
hasChanged.add(ToggleButtonsState.italic);
}
if (style.decoration != null &&
!hasChanged.contains(ToggleButtonsState.underline)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..add(ToggleButtonsState.underline),
);
hasChanged.add(ToggleButtonsState.underline);
}
}
for (final TextStyle style in replacementStyles) {
if (style.fontWeight == null &&
!hasChanged.contains(ToggleButtonsState.bold)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..remove(ToggleButtonsState.bold),
);
hasChanged.add(ToggleButtonsState.bold);
}
if (style.fontStyle == null &&
!hasChanged.contains(ToggleButtonsState.italic)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..remove(ToggleButtonsState.italic),
);
hasChanged.add(ToggleButtonsState.italic);
}
if (style.decoration == null &&
!hasChanged.contains(ToggleButtonsState.underline)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..remove(ToggleButtonsState.underline),
);
hasChanged.add(ToggleButtonsState.underline);
}
}
setState(() {});
}
void updateToggleButtonsStateOnButtonPressed(int index) {
Map<int, TextStyle> attributeMap = const <int, TextStyle>{
0: TextStyle(fontWeight: FontWeight.bold),
1: TextStyle(fontStyle: FontStyle.italic),
2: TextStyle(decoration: TextDecoration.underline),
};
final ReplacementTextEditingController controller =
_data.replacementsController;
final TextRange replacementRange = TextRange(
start: controller.selection.start,
end: controller.selection.end,
);
final targetToggleButtonState = ToggleButtonsState.values[index];
if (_data.toggleButtonsState.contains(targetToggleButtonState)) {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..remove(targetToggleButtonState),
);
} else {
_data = _data.copyWith(
toggleButtonsState: Set.from(_data.toggleButtonsState)
..add(targetToggleButtonState),
);
}
if (_data.toggleButtonsState.contains(targetToggleButtonState)) {
controller.applyReplacement(
TextEditingInlineSpanReplacement(
replacementRange,
(string, range) => TextSpan(text: string, style: attributeMap[index]),
true,
),
);
_data = _data.copyWith(replacementsController: controller);
setState(() {});
} else {
controller.disableExpand(attributeMap[index]!);
controller.removeReplacementsAtRange(
replacementRange, attributeMap[index]);
_data = _data.copyWith(replacementsController: controller);
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return AppStateManager(
state: _data,
child: widget.child,
);
}
}
| samples/simplistic_editor/lib/app_state.dart/0 | {
"file_path": "samples/simplistic_editor/lib/app_state.dart",
"repo_id": "samples",
"token_count": 2551
} | 1,370 |
package dev.flutter.testing_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| samples/testing_app/android/app/src/main/kotlin/dev/flutter/testing_app/MainActivity.kt/0 | {
"file_path": "samples/testing_app/android/app/src/main/kotlin/dev/flutter/testing_app/MainActivity.kt",
"repo_id": "samples",
"token_count": 39
} | 1,371 |
// 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:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:veggieseasons/data/veggie.dart';
abstract class Styles {
static CupertinoThemeData veggieThemeData = const CupertinoThemeData(
textTheme: CupertinoTextThemeData(
textStyle: TextStyle(
color: CupertinoColors.label,
fontSize: 16,
fontWeight: FontWeight.normal,
fontStyle: FontStyle.normal,
fontFamily: 'NotoSans',
letterSpacing: -0.41,
decoration: TextDecoration.none,
),
),
);
static TextStyle headlineText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontSize: 32,
fontWeight: FontWeight.bold,
);
static TextStyle minorText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: const Color.fromRGBO(128, 128, 128, 1),
);
static TextStyle headlineName(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontSize: 24,
fontWeight: FontWeight.bold,
);
static TextStyle cardTitleText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: const Color.fromRGBO(0, 0, 0, 0.9),
fontSize: 32,
fontWeight: FontWeight.bold,
);
static TextStyle cardCategoryText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: const Color.fromRGBO(255, 255, 255, 0.9),
);
static TextStyle cardDescriptionText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: const Color.fromRGBO(0, 0, 0, 0.9),
);
static TextStyle detailsTitleText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontSize: 30,
fontWeight: FontWeight.bold,
);
static TextStyle detailsPreferredCategoryText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontWeight: FontWeight.bold,
);
static TextStyle detailsBoldDescriptionText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: const Color.fromRGBO(0, 0, 0, 0.9),
fontWeight: FontWeight.bold,
);
static TextStyle detailsServingHeaderText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: const Color.fromRGBO(176, 176, 176, 1),
fontWeight: FontWeight.bold,
);
static TextStyle detailsServingLabelText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontWeight: FontWeight.bold,
);
static TextStyle detailsServingNoteText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontStyle: FontStyle.italic,
);
static TextStyle triviaFinishedTitleText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontSize: 32,
);
static TextStyle triviaFinishedBigText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontSize: 48,
);
static TextStyle settingsGroupHeaderText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: CupertinoColors.inactiveGray,
fontSize: 13.5,
letterSpacing: -0.5,
);
static TextStyle settingsGroupFooterText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
color: Styles.settingsGroupSubtitle,
fontSize: 13,
letterSpacing: -0.08,
);
static const appBackground = Color(0xffd0d0d0);
static Color? scaffoldBackground(Brightness brightness) =>
brightness == Brightness.light
? CupertinoColors.lightBackgroundGray
: null;
static const frostedBackground = Color(0xccf8f8f8);
static const closeButtonUnpressed = Color(0xff101010);
static const closeButtonPressed = Color(0xff808080);
static TextStyle settingsItemSubtitleText(CupertinoThemeData themeData) =>
themeData.textTheme.textStyle.copyWith(
fontSize: 12,
letterSpacing: -0.2,
);
static const Color searchCursorColor = Color.fromRGBO(0, 122, 255, 1);
static const Color searchIconColor = Color.fromRGBO(128, 128, 128, 1);
static const seasonColors = <Season, Color>{
Season.winter: Color(0xff336dcc),
Season.spring: Color(0xff2fa02b),
Season.summer: Color(0xff287213),
Season.autumn: Color(0xff724913),
};
// While handy, some of the Font Awesome icons sometimes bleed over their
// allotted bounds. This padding is used to adjust for that.
static const seasonIconPadding = {
Season.winter: EdgeInsets.only(right: 0),
Season.spring: EdgeInsets.only(right: 4),
Season.summer: EdgeInsets.only(right: 6),
Season.autumn: EdgeInsets.only(right: 0),
};
static const seasonIconData = {
Season.winter: FontAwesomeIcons.snowflake,
Season.spring: FontAwesomeIcons.leaf,
Season.summer: FontAwesomeIcons.umbrellaBeach,
Season.autumn: FontAwesomeIcons.canadianMapleLeaf,
};
static const seasonBorder = Border(
top: BorderSide(color: Color(0xff606060)),
left: BorderSide(color: Color(0xff606060)),
bottom: BorderSide(color: Color(0xff606060)),
right: BorderSide(color: Color(0xff606060)),
);
static const uncheckedIcon = IconData(
0xf372,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage,
);
static const checkedIcon = IconData(
0xf373,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage,
);
static const transparentColor = Color(0x00000000);
static const shadowColor = Color(0xa0000000);
static const shadowGradient = LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [transparentColor, shadowColor],
);
static const Color settingsMediumGray = Color(0xffc7c7c7);
static const Color settingsItemPressed = Color(0xffd9d9d9);
static Color settingsItemColor(Brightness brightness) =>
brightness == Brightness.light
? CupertinoColors.tertiarySystemBackground
: CupertinoColors.darkBackgroundGray;
static Color settingsLineation(Brightness brightness) =>
brightness == Brightness.light
? const Color(0xffbcbbc1)
: const Color(0xff4c4b4b);
static const Color settingsBackground = Color(0xffefeff4);
static const Color settingsGroupSubtitle = Color(0xff777777);
static const Color iconBlue = Color(0xff0000ff);
static const Color iconGold = Color(0xffdba800);
static const preferenceIcon = IconData(
0xf443,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage,
);
static const resetIcon = IconData(
0xf4c4,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage,
);
static const calorieIcon = IconData(
0xf3bb,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage,
);
static const checkIcon = IconData(
0xf383,
fontFamily: CupertinoIcons.iconFont,
fontPackage: CupertinoIcons.iconFontPackage,
);
static const servingInfoBorderColor = Color(0xffb0b0b0);
static const ColorFilter desaturatedColorFilter =
// 222222 is a random color that has low color saturation.
ColorFilter.mode(Color(0xff222222), BlendMode.saturation);
}
| samples/veggieseasons/lib/styles.dart/0 | {
"file_path": "samples/veggieseasons/lib/styles.dart",
"repo_id": "samples",
"token_count": 2814
} | 1,372 |
// 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 'web_startup_analyzer_base.dart';
// This class is a stub so that unit tests can run without importing
// dart:js_interop and related packages.
class WebStartupAnalyzer extends WebStartupAnalyzerBase {
WebStartupAnalyzer({int additionalFrameCount = 0});
@override
List<int>? get additionalFrames => [];
@override
double get appRunnerRunApp => 0.0;
@override
double get domContentLoaded => 0.0;
@override
double? get firstContentfulPaint => 0.0;
@override
double? get firstFrame => 0.0;
@override
double? get firstPaint => 0.0;
@override
double get initializeEngine => 0.0;
@override
double get loadEntrypoint => 0.0;
@override
Map<String, dynamic> get startupTiming => {};
}
| samples/web/_packages/web_startup_analyzer/lib/src/web_startup_analyzer_io.dart/0 | {
"file_path": "samples/web/_packages/web_startup_analyzer/lib/src/web_startup_analyzer_io.dart",
"repo_id": "samples",
"token_count": 279
} | 1,373 |
// 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';
String indent(String content, int spaces) =>
LineSplitter.split(content).join('\n${' ' * spaces}');
String kebabCase(String input) => _fixCase(input, '-');
String snakeCase(String input) => _fixCase(input, '_');
final _upperCase = RegExp('[A-Z]');
String pascalCase(String input) {
if (input.isEmpty) {
return '';
}
return input[0].toUpperCase() + input.substring(1);
}
String _fixCase(String input, String separator) =>
input.replaceAllMapped(_upperCase, (match) {
var group = match.group(0);
if (group == null) return input;
var lower = group.toLowerCase();
if (match.start > 0) {
lower = '$separator$lower';
}
return lower;
});
| samples/web/samples_index/lib/src/util.dart/0 | {
"file_path": "samples/web/samples_index/lib/src/util.dart",
"repo_id": "samples",
"token_count": 325
} | 1,374 |
import 'package:flutter/material.dart';
class DashDemo extends StatefulWidget {
final ValueNotifier<String> text;
const DashDemo({super.key, required this.text});
@override
State<DashDemo> createState() => _DashDemoState();
}
class _DashDemoState extends State<DashDemo> {
final double textFieldHeight = 80;
final Color colorPrimary = Colors.blue.shade700;
late TextEditingController textController;
int totalCharCount = 0;
@override
void initState() {
super.initState();
// Initial value of the text box
totalCharCount = widget.text.value.length;
textController = TextEditingController.fromValue(TextEditingValue(
text: widget.text.value,
selection: TextSelection.collapsed(offset: widget.text.value.length)));
// Report changes
textController.addListener(_onTextControllerChange);
// Listen to changes from the outside
widget.text.addListener(_onTextStateChanged);
}
void _onTextControllerChange() {
widget.text.value = textController.text;
setState(() {
totalCharCount = textController.text.length;
});
}
void _onTextStateChanged() {
textController.value = TextEditingValue(
text: widget.text.value,
selection: TextSelection.collapsed(offset: widget.text.value.length),
);
}
@override
void dispose() {
super.dispose();
textController.dispose();
widget.text.removeListener(_onTextStateChanged);
}
void _handleClear() {
textController.value = TextEditingValue(
text: '',
selection: TextSelection.collapsed(offset: widget.text.value.length),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Expanded(
child: Container(
width: double.infinity,
color: colorPrimary,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'COUNT WITH DASH!',
style: Theme.of(context).textTheme.titleLarge!.copyWith(
color: Colors.white,
),
),
// Bordered dash avatar
Padding(
padding: const EdgeInsets.all(12),
child: ClipOval(
child: Container(
color: Colors.white,
padding: const EdgeInsets.all(2),
child: ClipOval(
child: Container(
color: colorPrimary,
padding: const EdgeInsets.all(2),
child: const CircleAvatar(
radius: 45,
backgroundColor: Colors.white,
foregroundImage:
AssetImage('assets/dash.png'),
)),
)),
),
),
Text(
'$totalCharCount',
style: Theme.of(context).textTheme.displayLarge!.copyWith(
color: Colors.white,
),
),
],
),
),
),
Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: TextField(
autofocus: true,
controller: textController,
maxLines: 1,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'Type something!',
),
),
),
Padding(
padding: const EdgeInsets.only(left: 12),
child: Ink(
decoration: ShapeDecoration(
color: colorPrimary,
shape: const CircleBorder(),
),
child: IconButton(
icon: const Icon(Icons.refresh),
color: Colors.white,
onPressed: _handleClear,
),
),
),
],
),
),
],
),
);
}
}
| samples/web_embedding/ng-flutter/flutter/lib/pages/dash.dart/0 | {
"file_path": "samples/web_embedding/ng-flutter/flutter/lib/pages/dash.dart",
"repo_id": "samples",
"token_count": 2519
} | 1,375 |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgFlutterComponent } from './ng-flutter.component';
describe('NgFlutterComponent', () => {
let component: NgFlutterComponent;
let fixture: ComponentFixture<NgFlutterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ NgFlutterComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(NgFlutterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| samples/web_embedding/ng-flutter/src/app/ng-flutter/ng-flutter.component.spec.ts/0 | {
"file_path": "samples/web_embedding/ng-flutter/src/app/ng-flutter/ng-flutter.component.spec.ts",
"repo_id": "samples",
"token_count": 200
} | 1,376 |
steps:
- name: gcr.io/cloud-builders/git
args: ['submodule', 'update', '--init', '--recursive']
- name: gcr.io/cloud-builders/docker
entrypoint: '/bin/bash'
args:
- '-c'
- |-
set -e
echo "Building the website using a makefile..."
make build
- name: gcr.io/flutter-dev-230821/firebase-ghcli
entrypoint: '/bin/bash'
args:
- '-c'
- |-
firebase deploy --project=flutter-docs-prod --only=hosting
options:
logging: CLOUD_LOGGING_ONLY
| website/cloud_build/deploy.yaml/0 | {
"file_path": "website/cloud_build/deploy.yaml",
"repo_id": "website",
"token_count": 237
} | 1,377 |
// Copyright 2019 the Dart project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
double randomBorderRadius() {
return Random().nextDouble() * 64;
}
double randomMargin() {
return Random().nextDouble() * 64;
}
Color randomColor() {
return Color(0xFFFFFFFF & Random().nextInt(0xFFFFFFFF));
}
class AnimatedContainerDemo extends StatefulWidget {
const AnimatedContainerDemo({super.key});
@override
State<AnimatedContainerDemo> createState() => _AnimatedContainerDemoState();
}
class _AnimatedContainerDemoState extends State<AnimatedContainerDemo> {
late Color color;
late double borderRadius;
late double margin;
@override
void initState() {
super.initState();
color = randomColor();
borderRadius = randomBorderRadius();
margin = randomMargin();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
SizedBox(
width: 128,
height: 128,
child: Container(
margin: EdgeInsets.all(margin),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(borderRadius),
),
),
),
ElevatedButton(
child: const Text('Change'),
onPressed: () => {},
),
],
),
),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: AnimatedContainerDemo(),
);
}
}
void main() {
runApp(
const MyApp(),
);
}
| website/examples/animation/implicit/container1/lib/main.dart/0 | {
"file_path": "website/examples/animation/implicit/container1/lib/main.dart",
"repo_id": "website",
"token_count": 782
} | 1,378 |
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
// #docregion animation
class _DraggableCardState extends State<DraggableCard>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
Alignment _dragAlignment = Alignment.center;
// #enddocregion alignment
// #enddocregion animation
// #docregion initState
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 1));
}
// #enddocregion initState
@override
void dispose() {
_controller.dispose();
super.dispose();
}
// #docregion build
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
// #docregion gesture
return GestureDetector(
onPanDown: (details) {},
onPanUpdate: (details) {
setState(() {
_dragAlignment += Alignment(
details.delta.dx / (size.width / 2),
details.delta.dy / (size.height / 2),
);
});
},
onPanEnd: (details) {},
child: Align(
alignment: _dragAlignment,
child: Card(
child: widget.child,
),
),
);
// #enddocregion gesture
}
// #enddocregion build
}
| website/examples/cookbook/animation/physics_simulation/lib/step2.dart/0 | {
"file_path": "website/examples/cookbook/animation/physics_simulation/lib/step2.dart",
"repo_id": "website",
"token_count": 733
} | 1,379 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Package Fonts',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
// The AppBar uses the app-default font.
appBar: AppBar(title: const Text('Package Fonts')),
body: const Center(
// This Text widget uses the Raleway font.
// #docregion TextStyle
child: Text(
'Using the Raleway font from the awesome_package',
style: TextStyle(
fontFamily: 'Raleway',
),
),
// #enddocregion TextStyle
),
);
}
}
| website/examples/cookbook/design/package_fonts/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/design/package_fonts/lib/main.dart",
"repo_id": "website",
"token_count": 358
} | 1,380 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
enum DownloadStatus {
notDownloaded,
fetchingDownload,
downloading,
downloaded,
}
// #docregion Display
@immutable
class DownloadButton extends StatelessWidget {
const DownloadButton({
super.key,
required this.status,
this.transitionDuration = const Duration(
milliseconds: 500,
),
});
final DownloadStatus status;
final Duration transitionDuration;
bool get _isDownloading => status == DownloadStatus.downloading;
bool get _isFetching => status == DownloadStatus.fetchingDownload;
bool get _isDownloaded => status == DownloadStatus.downloaded;
@override
Widget build(BuildContext context) {
return ButtonShapeWidget(
transitionDuration: transitionDuration,
isDownloaded: _isDownloaded,
isDownloading: _isDownloading,
isFetching: _isFetching,
);
}
}
@immutable
class ButtonShapeWidget extends StatelessWidget {
const ButtonShapeWidget({
super.key,
required this.isDownloading,
required this.isDownloaded,
required this.isFetching,
required this.transitionDuration,
});
final bool isDownloading;
final bool isDownloaded;
final bool isFetching;
final Duration transitionDuration;
@override
Widget build(BuildContext context) {
var shape = const ShapeDecoration(
shape: StadiumBorder(),
color: CupertinoColors.lightBackgroundGray,
);
if (isDownloading || isFetching) {
shape = ShapeDecoration(
shape: const CircleBorder(),
color: Colors.white.withOpacity(0),
);
}
return AnimatedContainer(
duration: transitionDuration,
curve: Curves.ease,
width: double.infinity,
decoration: shape,
child: const SizedBox(),
);
}
}
// #enddocregion Display
| website/examples/cookbook/effects/download_button/lib/display.dart/0 | {
"file_path": "website/examples/cookbook/effects/download_button/lib/display.dart",
"repo_id": "website",
"token_count": 624
} | 1,381 |
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show ViewportOffset;
void main() {
runApp(
const MaterialApp(
home: ExampleInstagramFilterSelection(),
debugShowCheckedModeBanner: false,
),
);
}
@immutable
class ExampleInstagramFilterSelection extends StatefulWidget {
const ExampleInstagramFilterSelection({super.key});
@override
State<ExampleInstagramFilterSelection> createState() =>
_ExampleInstagramFilterSelectionState();
}
class _ExampleInstagramFilterSelectionState
extends State<ExampleInstagramFilterSelection> {
final _filters = [
Colors.white,
...List.generate(
Colors.primaries.length,
(index) => Colors.primaries[(index * 4) % Colors.primaries.length],
)
];
final _filterColor = ValueNotifier<Color>(Colors.white);
void _onFilterChanged(Color value) {
_filterColor.value = value;
}
@override
Widget build(BuildContext context) {
return Material(
color: Colors.black,
child: Stack(
children: [
Positioned.fill(
child: _buildPhotoWithFilter(),
),
Positioned(
left: 0.0,
right: 0.0,
bottom: 0.0,
child: _buildFilterSelector(),
),
],
),
);
}
Widget _buildPhotoWithFilter() {
return ValueListenableBuilder(
valueListenable: _filterColor,
builder: (context, color, child) {
return Image.network(
'https://docs.flutter.dev/cookbook/img-files'
'/effects/instagram-buttons/millennial-dude.jpg',
color: color.withOpacity(0.5),
colorBlendMode: BlendMode.color,
fit: BoxFit.cover,
);
},
);
}
Widget _buildFilterSelector() {
return FilterSelector(
onFilterChanged: _onFilterChanged,
filters: _filters,
);
}
}
@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;
late int _page;
int get filterCount => widget.filters.length;
Color itemColor(int index) => widget.filters[index % filterCount];
@override
void initState() {
super.initState();
_page = 0;
_controller = PageController(
initialPage: _page,
viewportFraction: _viewportFractionPerItem,
);
_controller.addListener(_onPageChanged);
}
void _onPageChanged() {
final page = (_controller.page ?? 0).round();
if (page != _page) {
_page = page;
widget.onFilterChanged(widget.filters[page]);
}
}
void _onFilterTapped(int index) {
_controller.animateToPage(
index,
duration: const Duration(milliseconds: 450),
curve: Curves.ease,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scrollable(
controller: _controller,
axisDirection: AxisDirection.right,
physics: const PageScrollPhysics(),
viewportBuilder: (context, viewportOffset) {
return LayoutBuilder(
builder: (context, constraints) {
final itemSize = constraints.maxWidth * _viewportFractionPerItem;
viewportOffset
..applyViewportDimension(constraints.maxWidth)
..applyContentDimensions(0.0, itemSize * (filterCount - 1));
return Stack(
alignment: Alignment.bottomCenter,
children: [
_buildShadowGradient(itemSize),
_buildCarousel(
viewportOffset: viewportOffset,
itemSize: itemSize,
),
_buildSelectionRing(itemSize),
],
);
},
);
},
);
}
Widget _buildShadowGradient(double itemSize) {
return SizedBox(
height: itemSize * 2 + widget.padding.vertical,
child: const DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.black,
],
),
),
child: SizedBox.expand(),
),
);
}
Widget _buildCarousel({
required ViewportOffset viewportOffset,
required double itemSize,
}) {
return Container(
height: itemSize,
margin: widget.padding,
child: Flow(
delegate: CarouselFlowDelegate(
viewportOffset: viewportOffset,
filtersPerScreen: _filtersPerScreen,
),
children: [
for (int i = 0; i < filterCount; i++)
FilterItem(
onFilterSelected: () => _onFilterTapped(i),
color: itemColor(i),
),
],
),
);
}
Widget _buildSelectionRing(double itemSize) {
return IgnorePointer(
child: Padding(
padding: widget.padding,
child: SizedBox(
width: itemSize,
height: itemSize,
child: const DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.fromBorderSide(
BorderSide(width: 6, color: Colors.white),
),
),
),
),
),
);
}
}
class CarouselFlowDelegate extends FlowDelegate {
CarouselFlowDelegate({
required this.viewportOffset,
required this.filtersPerScreen,
}) : super(repaint: viewportOffset);
final ViewportOffset viewportOffset;
final int filtersPerScreen;
@override
void paintChildren(FlowPaintingContext context) {
final count = context.childCount;
// All available painting width
final size = context.size.width;
// The distance that a single item "page" takes up from the perspective
// of the scroll paging system. We also use this size for the width and
// height of a single item.
final itemExtent = size / filtersPerScreen;
// The current scroll position expressed as an item fraction, e.g., 0.0,
// or 1.0, or 1.3, or 2.9, etc. A value of 1.3 indicates that item at
// index 1 is active, and the user has scrolled 30% towards the item at
// index 2.
final active = viewportOffset.pixels / itemExtent;
// Index of the first item we need to paint at this moment.
// At most, we paint 3 items to the left of the active item.
final min = math.max(0, active.floor() - 3).toInt();
// Index of the last item we need to paint at this moment.
// At most, we paint 3 items to the right of the active item.
final max = math.min(count - 1, active.ceil() + 3).toInt();
// Generate transforms for the visible items and sort by distance.
for (var index = min; index <= max; index++) {
final itemXFromCenter = itemExtent * index - viewportOffset.pixels;
final percentFromCenter = 1.0 - (itemXFromCenter / (size / 2)).abs();
final itemScale = 0.5 + (percentFromCenter * 0.5);
final opacity = 0.25 + (percentFromCenter * 0.75);
final itemTransform = Matrix4.identity()
..translate((size - itemExtent) / 2)
..translate(itemXFromCenter)
..translate(itemExtent / 2, itemExtent / 2)
..multiply(Matrix4.diagonal3Values(itemScale, itemScale, 1.0))
..translate(-itemExtent / 2, -itemExtent / 2);
context.paintChild(
index,
transform: itemTransform,
opacity: opacity,
);
}
}
@override
bool shouldRepaint(covariant CarouselFlowDelegate oldDelegate) {
return oldDelegate.viewportOffset != viewportOffset;
}
}
@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/main.dart/0 | {
"file_path": "website/examples/cookbook/effects/photo_filter_carousel/lib/main.dart",
"repo_id": "website",
"token_count": 3728
} | 1,382 |
import 'package:flutter/material.dart';
class Menu extends StatefulWidget {
const Menu({super.key});
@override
State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> with SingleTickerProviderStateMixin {
final List<Interval> _itemSlideIntervals = [];
late Interval _buttonInterval;
// #docregion initState
@override
void initState() {
super.initState();
_createAnimationIntervals();
_staggeredController = AnimationController(
vsync: this,
duration: _animationDuration,
)..forward();
}
// #enddocregion initState
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,
);
}
Widget _buildContent() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 16),
..._buildListItems(),
const Spacer(),
_buildGetStartedButton(),
],
);
}
@override
Widget build(BuildContext context) {
return _buildContent();
}
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',
];
// #docregion buildListItems
List<Widget> _buildListItems() {
final listItems = <Widget>[];
for (var i = 0; i < _menuTitles.length; ++i) {
listItems.add(
AnimatedBuilder(
animation: _staggeredController,
builder: (context, child) {
final animationPercent = Curves.easeOut.transform(
_itemSlideIntervals[i].transform(_staggeredController.value),
);
final opacity = animationPercent;
final slideDistance = (1.0 - animationPercent) * 150;
return Opacity(
opacity: opacity,
child: Transform.translate(
offset: Offset(slideDistance, 0),
child: child,
),
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 16),
child: Text(
_menuTitles[i],
textAlign: TextAlign.left,
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w500,
),
),
),
),
);
}
return listItems;
}
// #enddocregion buildListItems
// #docregion buildGetStartedButton
Widget _buildGetStartedButton() {
return SizedBox(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.all(24),
child: AnimatedBuilder(
animation: _staggeredController,
builder: (context, child) {
final animationPercent = Curves.elasticOut.transform(
_buttonInterval.transform(_staggeredController.value));
final opacity = animationPercent.clamp(0.0, 1.0);
final scale = (animationPercent * 0.5) + 0.5;
return Opacity(
opacity: opacity,
child: Transform.scale(
scale: scale,
child: child,
),
);
},
child: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
backgroundColor: Colors.blue,
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 14),
),
onPressed: () {},
child: const Text(
'Get Started',
style: TextStyle(
color: Colors.white,
fontSize: 22,
),
),
),
),
),
);
}
// #enddocregion buildGetStartedButton
}
| website/examples/cookbook/effects/staggered_menu_animation/lib/step4.dart/0 | {
"file_path": "website/examples/cookbook/effects/staggered_menu_animation/lib/step4.dart",
"repo_id": "website",
"token_count": 2170
} | 1,383 |
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Retrieve Text Input',
home: MyCustomForm(),
);
}
}
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Retrieve Text Input'),
),
body: Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: myController,
),
),
floatingActionButton: FloatingActionButton(
// When the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text the that user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: const Icon(Icons.text_fields),
),
);
}
}
| website/examples/cookbook/forms/retrieve_input/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/forms/retrieve_input/lib/main.dart",
"repo_id": "website",
"token_count": 731
} | 1,384 |
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> {
final items = List<String>.generate(20, (i) => 'Item ${i + 1}');
@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),
),
// #docregion ListView
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
// #enddocregion ListView
),
);
}
}
| website/examples/cookbook/gestures/dismissible/lib/step1.dart/0 | {
"file_path": "website/examples/cookbook/gestures/dismissible/lib/step1.dart",
"repo_id": "website",
"token_count": 458
} | 1,385 |
name: fading_in_images
description: Example for fading_in_images cookbook recipe
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.6
transparent_image: ^2.0.1
dev_dependencies:
example_utils:
path: ../../../example_utils
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
| website/examples/cookbook/images/fading_in_images/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/images/fading_in_images/pubspec.yaml",
"repo_id": "website",
"token_count": 156
} | 1,386 |
name: navigation_basics
description: A new Flutter project.
publish_to: none # Remove this line if you wish to publish to pub.dev
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/navigation/navigation_basics/pubspec.yaml/0 | {
"file_path": "website/examples/cookbook/navigation/navigation_basics/pubspec.yaml",
"repo_id": "website",
"token_count": 152
} | 1,387 |
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
// #docregion parsePhotos
// A function that converts a response body into a List<Photo>.
List<Photo> parsePhotos(String responseBody) {
final parsed =
(jsonDecode(responseBody) as List).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
// Synchronously run parsePhotos in the main isolate.
return parsePhotos(response.body);
}
// #enddocregion parsePhotos
// #docregion Photo
class Photo {
final int albumId;
final int id;
final String title;
final String url;
final String thumbnailUrl;
const Photo({
required this.albumId,
required this.id,
required this.title,
required this.url,
required this.thumbnailUrl,
});
factory Photo.fromJson(Map<String, dynamic> json) {
return Photo(
albumId: json['albumId'] as int,
id: json['id'] as int,
title: json['title'] as String,
url: json['url'] as String,
thumbnailUrl: json['thumbnailUrl'] as String,
);
}
}
// #enddocregion Photo
| website/examples/cookbook/networking/background_parsing/lib/main_step3.dart/0 | {
"file_path": "website/examples/cookbook/networking/background_parsing/lib/main_step3.dart",
"repo_id": "website",
"token_count": 436
} | 1,388 |
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
// #docregion updateAlbum
Future<http.Response> updateAlbum(String title) {
return 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,
}),
);
}
// #enddocregion updateAlbum
| website/examples/cookbook/networking/update_data/lib/main_step2.dart/0 | {
"file_path": "website/examples/cookbook/networking/update_data/lib/main_step2.dart",
"repo_id": "website",
"token_count": 177
} | 1,389 |
// #docregion imports
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
// #enddocregion imports
void main() async {
// Avoid errors caused by flutter upgrade.
// Importing 'package:flutter/widgets.dart' is required.
WidgetsFlutterBinding.ensureInitialized();
// Open the database and store the reference.
// #docregion openDatabase
final database = openDatabase(
// Set the path to the database. Note: Using the `join` function from the
// `path` package is best practice to ensure the path is correctly
// constructed for each platform.
join(await getDatabasesPath(), 'doggie_database.db'),
// When the database is first created, create a table to store dogs.
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
'CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)',
);
},
// Set the version. This executes the onCreate function and provides a
// path to perform database upgrades and downgrades.
version: 1,
);
// #enddocregion openDatabase
// #docregion insertDog
// Define a function that inserts dogs into the database
Future<void> insertDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Insert the Dog into the correct table. You might also specify the
// `conflictAlgorithm` to use in case the same dog is inserted twice.
//
// In this case, replace any previous data.
await db.insert(
'dogs',
dog.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// #enddocregion insertDog
// #docregion dogs
// A method that retrieves all the dogs from the dogs table.
Future<List<Dog>> dogs() async {
// Get a reference to the database.
final db = await database;
// Query the table for all the dogs.
final List<Map<String, Object?>> dogMaps = await db.query('dogs');
// Convert the list of each dog's fields into a list of `Dog` objects.
return [
for (final {
'id': id as int,
'name': name as String,
'age': age as int,
} in dogMaps)
Dog(id: id, name: name, age: age),
];
}
// #enddocregion dogs
// #docregion update
Future<void> updateDog(Dog dog) async {
// Get a reference to the database.
final db = await database;
// Update the given Dog.
await db.update(
'dogs',
dog.toMap(),
// Ensure that the Dog has a matching id.
where: 'id = ?',
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [dog.id],
);
}
// #enddocregion update
// #docregion deleteDog
Future<void> deleteDog(int id) async {
// Get a reference to the database.
final db = await database;
// Remove the Dog from the database.
await db.delete(
'dogs',
// Use a `where` clause to delete a specific dog.
where: 'id = ?',
// Pass the Dog's id as a whereArg to prevent SQL injection.
whereArgs: [id],
);
}
// #enddocregion deleteDog
// #docregion fido
// Create a Dog and add it to the dogs table
var fido = Dog(
id: 0,
name: 'Fido',
age: 35,
);
await insertDog(fido);
// #enddocregion fido
// #docregion print
// Now, use the method above to retrieve all the dogs.
print(await dogs()); // Prints a list that include Fido.
// #enddocregion print
// #docregion update2
// Update Fido's age and save it to the database.
fido = Dog(
id: fido.id,
name: fido.name,
age: fido.age + 7,
);
await updateDog(fido);
// Print the updated results.
print(await dogs()); // Prints Fido with age 42.
// #enddocregion update2
// Delete Fido from the database.
await deleteDog(fido.id);
// Print the list of dogs (empty).
print(await dogs());
}
// #docregion Dog
class Dog {
final int id;
final String name;
final int age;
Dog({
required this.id,
required this.name,
required this.age,
});
// Convert a Dog into a Map. The keys must correspond to the names of the
// columns in the database.
Map<String, Object?> toMap() {
return {
'id': id,
'name': name,
'age': age,
};
}
// Implement toString to make it easier to see information about
// each dog when using the print statement.
@override
String toString() {
return 'Dog{id: $id, name: $name, age: $age}';
}
}
// #enddocregion Dog
| website/examples/cookbook/persistence/sqlite/lib/main.dart/0 | {
"file_path": "website/examples/cookbook/persistence/sqlite/lib/main.dart",
"repo_id": "website",
"token_count": 1608
} | 1,390 |
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
// ignore_for_file: unused_field
// #docregion 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',
),
);
_initializeVideoPlayerFuture = _controller.initialize();
}
@override
void dispose() {
// Ensure disposing of the VideoPlayerController to free up resources.
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Complete the code in the next step.
return Container();
}
}
// #enddocregion VideoPlayerScreen
| website/examples/cookbook/plugins/play_video/lib/main_step3.dart/0 | {
"file_path": "website/examples/cookbook/plugins/play_video/lib/main_step3.dart",
"repo_id": "website",
"token_count": 394
} | 1,391 |
// Import the test package and Counter class
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
test('Counter value should be incremented', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}
| website/examples/cookbook/testing/unit/counter_app/test/counter_test.dart/0 | {
"file_path": "website/examples/cookbook/testing/unit/counter_app/test/counter_test.dart",
"repo_id": "website",
"token_count": 89
} | 1,392 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
// Define a test. The TestWidgets function also provides a WidgetTester
// to work with. The WidgetTester allows building and interacting
// with widgets in the test environment.
testWidgets('MyWidget has a title and message', (tester) async {
// Create the widget by telling the tester to build it.
await tester.pumpWidget(const MyWidget(title: 'T', message: 'M'));
// Create the Finders.
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);
});
}
// #docregion widget
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),
),
),
);
}
}
// #enddocregion widget
| website/examples/cookbook/testing/widget/introduction/test/main_test.dart/0 | {
"file_path": "website/examples/cookbook/testing/widget/introduction/test/main_test.dart",
"repo_id": "website",
"token_count": 474
} | 1,393 |
name: isolates
description: Sample isolate code.
publish_to: none
version: 1.0.0+1
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
shared_preferences: any
dev_dependencies:
example_utils:
path: ../../../example_utils
| website/examples/development/concurrency/isolates/pubspec.yaml/0 | {
"file_path": "website/examples/development/concurrency/isolates/pubspec.yaml",
"repo_id": "website",
"token_count": 99
} | 1,394 |
// Autogenerated from Pigeon (v16.0.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon
// ignore_for_file: public_member_api_docs, constant_identifier_names, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers
import 'dart:async';
import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'package:flutter/services.dart';
PlatformException _createConnectionError(String channelName) {
return PlatformException(
code: 'channel-error',
message: 'Unable to establish connection on channel: "$channelName".',
);
}
class SearchRequest {
SearchRequest({
required this.query,
});
String query;
Object encode() {
return <Object?>[
query,
];
}
static SearchRequest decode(Object result) {
result as List<Object?>;
return SearchRequest(
query: result[0]! as String,
);
}
}
class SearchReply {
SearchReply({
required this.result,
});
String result;
Object encode() {
return <Object?>[
result,
];
}
static SearchReply decode(Object result) {
result as List<Object?>;
return SearchReply(
result: result[0]! as String,
);
}
}
class _ApiCodec extends StandardMessageCodec {
const _ApiCodec();
@override
void writeValue(WriteBuffer buffer, Object? value) {
if (value is SearchReply) {
buffer.putUint8(128);
writeValue(buffer, value.encode());
} else if (value is SearchRequest) {
buffer.putUint8(129);
writeValue(buffer, value.encode());
} else {
super.writeValue(buffer, value);
}
}
@override
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case 128:
return SearchReply.decode(readValue(buffer)!);
case 129:
return SearchRequest.decode(readValue(buffer)!);
default:
return super.readValueOfType(type, buffer);
}
}
}
class Api {
/// Constructor for [Api]. The [binaryMessenger] named argument is
/// available for dependency injection. If it is left null, the default
/// BinaryMessenger will be used which routes to the host platform.
Api({BinaryMessenger? binaryMessenger})
: __pigeon_binaryMessenger = binaryMessenger;
final BinaryMessenger? __pigeon_binaryMessenger;
static const MessageCodec<Object?> pigeonChannelCodec = _ApiCodec();
Future<SearchReply> search(SearchRequest request) async {
const String __pigeon_channelName =
'dev.flutter.pigeon.platform_integration.Api.search';
final BasicMessageChannel<Object?> __pigeon_channel =
BasicMessageChannel<Object?>(
__pigeon_channelName,
pigeonChannelCodec,
binaryMessenger: __pigeon_binaryMessenger,
);
final List<Object?>? __pigeon_replyList =
await __pigeon_channel.send(<Object?>[request]) as List<Object?>?;
if (__pigeon_replyList == null) {
throw _createConnectionError(__pigeon_channelName);
} else if (__pigeon_replyList.length > 1) {
throw PlatformException(
code: __pigeon_replyList[0]! as String,
message: __pigeon_replyList[1] as String?,
details: __pigeon_replyList[2],
);
} else if (__pigeon_replyList[0] == null) {
throw PlatformException(
code: 'null-error',
message: 'Host platform returned null value for non-null return value.',
);
} else {
return (__pigeon_replyList[0] as SearchReply?)!;
}
}
}
| website/examples/development/platform_integration/lib/generated_pigeon.dart/0 | {
"file_path": "website/examples/development/platform_integration/lib/generated_pigeon.dart",
"repo_id": "website",
"token_count": 1360
} | 1,395 |
// ignore_for_file: avoid_print
// #docregion Const
const foo = 1;
const bar = foo; // Convert foo to a const...
void onClick() {
print(foo);
print(bar);
}
// #enddocregion Const
| website/examples/development/tools/lib/hot-reload/foo_const.dart/0 | {
"file_path": "website/examples/development/tools/lib/hot-reload/foo_const.dart",
"repo_id": "website",
"token_count": 64
} | 1,396 |
// Avoid warning on "double _formProgress = 0;"
// ignore_for_file: prefer_final_fields
| website/examples/get-started/codelab_web/lib/test.dart/0 | {
"file_path": "website/examples/get-started/codelab_web/lib/test.dart",
"repo_id": "website",
"token_count": 26
} | 1,397 |
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sample App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample App'),
),
body: ListView(children: _getListData()),
);
}
List<Widget> _getListData() {
List<Widget> widgets = [];
for (int i = 0; i < 100; i++) {
widgets.add(
GestureDetector(
onTap: () {
developer.log('row tapped');
},
child: Padding(
padding: const EdgeInsets.all(10),
child: Text('Row $i'),
),
),
);
}
return widgets;
}
}
| website/examples/get-started/flutter-for/android_devs/lib/list_item_tapped.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/android_devs/lib/list_item_tapped.dart",
"repo_id": "website",
"token_count": 542
} | 1,398 |
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: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
Color red = Colors.red;
// #docregion declarative
// Declarative style
return ViewB(
color: red,
child: const ViewC(),
);
// #enddocregion declarative
}
}
class ViewB extends StatelessWidget {
const ViewB({super.key, required this.color, required this.child});
final Color color;
final Widget child;
@override
Widget build(BuildContext context) {
return const Text('Hello!');
}
}
class ViewC extends StatelessWidget {
const ViewC({super.key});
@override
Widget build(BuildContext context) {
return const Text('World!');
}
}
| website/examples/get-started/flutter-for/declarative/lib/main.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/declarative/lib/main.dart",
"repo_id": "website",
"token_count": 405
} | 1,399 |
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(
const App(),
);
}
class App extends StatelessWidget {
const App({
super.key,
});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: HomePage(),
);
}
}
// create a class that holds each person's data
@immutable
class Person {
final String name;
final int age;
const Person({
required this.name,
required this.age,
});
}
// As in SwiftUI, create a widget (a view in SwiftUI),
// that represents each person visually on the screen.
class PersonView extends StatelessWidget {
final Person person;
const PersonView({
super.key,
required this.person,
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
const Text('Name:'),
Text(person.name),
],
),
Row(
children: [
const Text('Age:'),
Text(person.age.toString()),
],
),
const Divider(),
],
);
}
}
// then we create a list of people
final mockPersons = Iterable.generate(
100,
(index) => Person(
name: 'Person #${index + 1}',
age: 10 + index,
),
);
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
// Finally, display the list of people on the screen,
// inside a scroll view of type
// SingleChildScrollView (equivalent of a ScrollView in SwiftUI).
body:
// #docregion ScrollExample
SingleChildScrollView(
child: Column(
children: mockPersons
.map(
(person) => PersonView(
person: person,
),
)
.toList(),
),
),
// #enddocregion ScrollExample
);
}
}
| website/examples/get-started/flutter-for/ios_devs/lib/scroll.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/ios_devs/lib/scroll.dart",
"repo_id": "website",
"token_count": 856
} | 1,400 |
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
// #docregion Components
/// Flutter
class CustomCard extends StatelessWidget {
const CustomCard({
super.key,
required this.index,
required this.onPress,
});
final int index;
final void Function() onPress;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: <Widget>[
Text('Card $index'),
TextButton(
onPressed: onPress,
child: const Text('Press'),
),
],
),
);
}
}
class UseCard extends StatelessWidget {
const UseCard({super.key, required this.index});
final int index;
@override
Widget build(BuildContext context) {
/// Usage
return CustomCard(
index: index,
onPress: () {
print('Card $index');
},
);
}
}
// #enddocregion Components
| website/examples/get-started/flutter-for/react_native_devs/lib/components.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/react_native_devs/lib/components.dart",
"repo_id": "website",
"token_count": 365
} | 1,401 |
import 'package:flutter/material.dart';
// #docregion TextStyle
TextStyle bold24Roboto = const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
);
// #enddocregion TextStyle
class MyWidget extends StatelessWidget {
MyWidget({super.key});
// #docregion Container
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: const Text(
'Lorem ipsum',
style: /*[[highlight]]*/ TextStyle(
fontFamily: 'Georgia',
fontSize: 24,
fontWeight: FontWeight.bold,
),
/*[[/highlight]]*/
/*[[highlight]]*/ textAlign: TextAlign.center, /*[[/highlight]]*/
),
);
// #enddocregion Container
@override
Widget build(BuildContext context) {
return container;
}
}
class Container2 extends StatelessWidget {
Container2({super.key});
// #docregion Container2
final container = Container(
// grey box
width: 320,
height: 240,
/*[[highlight]]*/ color: Colors.grey[300],
/*[[/highlight]]*/
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
);
// #enddocregion Container2
@override
Widget build(BuildContext context) {
return container;
}
}
class Container3 extends StatelessWidget {
Container3({super.key});
// #docregion Container3
final container = Container(
// grey box
width: 320,
height: 240,
/*[[highlight]]*/ decoration: BoxDecoration(
color: Colors.grey[300],
),
/*[[/highlight]]*/
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
);
// #enddocregion Container3
@override
Widget build(BuildContext context) {
return container;
}
}
class CenterWidget extends StatelessWidget {
CenterWidget({super.key});
// #docregion Center
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: /*[[highlight]]*/ Center(
child: /*[[/highlight]]*/ Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
);
// #enddocregion Center
@override
Widget build(BuildContext context) {
return container;
}
}
class Nested extends StatelessWidget {
Nested({super.key});
// #docregion Nested
final container = Container(
// grey box
/*[[highlight]]*/ width: 320,
/*[[/highlight]]*/
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red box
/*[[highlight]]*/ width: 240,
/*[[/highlight]]*/ // max-width is 240
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
),
);
// #enddocregion Nested
@override
Widget build(BuildContext context) {
return container;
}
}
class Absolute extends StatelessWidget {
Absolute({super.key});
// #docregion Absolute
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
/*[[highlight]]*/ child: Stack(
children: /*[[/highlight]]*/ [
Positioned(
// red box
/*[[highlight]]*/ left: 24,
top: 24,
/*[[/highlight]]*/
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
),
],
),
);
// #enddocregion Absolute
@override
Widget build(BuildContext context) {
return container;
}
}
class Rotating extends StatelessWidget {
Rotating({super.key});
// #docregion Rotating
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: /*[[highlight]]*/ Transform(
alignment: Alignment.center,
transform: Matrix4.identity()..rotateZ(15 * 3.1415927 / 180),
child: /*[[/highlight]]*/ Container(
// red box
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
textAlign: TextAlign.center,
),
),
),
),
);
// #enddocregion Rotating
@override
Widget build(BuildContext context) {
return container;
}
}
class Scaling extends StatelessWidget {
Scaling({super.key});
// #docregion Scaling
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: /*[[highlight]]*/ Transform(
alignment: Alignment.center,
transform: Matrix4.identity()..scale(1.5),
child: /*[[/highlight]]*/ Container(
// red box
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
textAlign: TextAlign.center,
),
),
),
),
);
// #enddocregion Scaling
@override
Widget build(BuildContext context) {
return container;
}
}
class Gradient extends StatelessWidget {
Gradient({super.key});
// #docregion Gradient
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red box
/*[[highlight]]*/ decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment(0.0, 0.6),
colors: <Color>[
Color(0xffef5350),
Color(0x00ef5350),
],
),
),
/*[[/highlight]]*/
padding: const EdgeInsets.all(16),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
),
);
// #enddocregion Gradient
@override
Widget build(BuildContext context) {
return container;
}
}
class HorizontalGradient extends StatelessWidget {
HorizontalGradient({super.key});
// #docregion HorizontalGradient
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red box
padding: const EdgeInsets.all(16),
/*[[highlight]]*/ decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment(-1.0, 0.0),
end: Alignment(0.6, 0.0),
colors: <Color>[
Color(0xffef5350),
Color(0x00ef5350),
],
),
),
/*[[/highlight]]*/
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
),
);
// #enddocregion HorizontalGradient
@override
Widget build(BuildContext context) {
return container;
}
}
class RoundCorners extends StatelessWidget {
RoundCorners({super.key});
// #docregion RoundCorners
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red circle
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
/*[[highlight]]*/ borderRadius: const BorderRadius.all(
Radius.circular(8),
), /*[[/highlight]]*/
),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
),
);
// #enddocregion RoundCorners
@override
Widget build(BuildContext context) {
return container;
}
}
class BoxShadowExample extends StatelessWidget {
BoxShadowExample({super.key});
// #docregion BoxShadow
final container = Container(
// grey box
width: 320,
height: 240,
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: Colors.grey[300],
),
child: Center(
child: Container(
// red box
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
/*[[highlight]]*/ boxShadow: const <BoxShadow>[
BoxShadow(
color: Color(0xcc000000),
offset: Offset(0, 2),
blurRadius: 4,
),
BoxShadow(
color: Color(0x80000000),
offset: Offset(0, 6),
blurRadius: 20,
),
], /*[[/highlight]]*/
),
child: Text(
'Lorem ipsum',
style: bold24Roboto,
),
),
),
);
// #enddocregion BoxShadow
@override
Widget build(BuildContext context) {
return container;
}
}
class CircleExample extends StatelessWidget {
CircleExample({super.key});
// #docregion Circle
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red circle
decoration: BoxDecoration(
color: Colors.red[400],
/*[[highlight]]*/ shape: BoxShape.circle, /*[[/highlight]]*/
),
padding: const EdgeInsets.all(16),
/*[[highlight]]*/ width: 160,
height: 160,
/*[[/highlight]]*/
child: Text(
'Lorem ipsum',
style: bold24Roboto,
/*[[highlight]]*/ textAlign: TextAlign.center, /*[[/highlight]]*/
),
),
),
);
// #enddocregion Circle
@override
Widget build(BuildContext context) {
return container;
}
}
class TextSpacingExample extends StatelessWidget {
TextSpacingExample({super.key});
// #docregion TextSpacing
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red box
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.red[400],
),
child: const Text(
'Lorem ipsum',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w900,
/*[[highlight]]*/ letterSpacing: 4, /*[[/highlight]]*/
),
),
),
),
);
// #enddocregion TextSpacing
@override
Widget build(BuildContext context) {
return container;
}
}
class InlineFormattingExample extends StatelessWidget {
InlineFormattingExample({super.key});
// #docregion InlineFormatting
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red box
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: const EdgeInsets.all(16),
child: /*[[highlight]]*/ RichText(
text: TextSpan(
style: bold24Roboto,
children: const <TextSpan>[
TextSpan(text: 'Lorem '),
TextSpan(
text: 'ipsum',
style: TextStyle(
fontWeight: FontWeight.w300,
fontStyle: FontStyle.italic,
fontSize: 48,
),
),
],
),
), /*[[/highlight]]*/
),
),
);
// #enddocregion InlineFormatting
@override
Widget build(BuildContext context) {
return container;
}
}
class TextExcerptsExample extends StatelessWidget {
TextExcerptsExample({super.key});
// #docregion TextExcerpt
final container = Container(
// grey box
width: 320,
height: 240,
color: Colors.grey[300],
child: Center(
child: Container(
// red box
decoration: BoxDecoration(
color: Colors.red[400],
),
padding: const EdgeInsets.all(16),
child: Text(
'Lorem ipsum dolor sit amet, consec etur',
style: bold24Roboto,
/*[[highlight]]*/ overflow: TextOverflow.ellipsis,
maxLines: 1, /*[[/highlight]]*/
),
),
),
);
// #enddocregion TextExcerpt
@override
Widget build(BuildContext context) {
return container;
}
}
| website/examples/get-started/flutter-for/web_devs/lib/main.dart/0 | {
"file_path": "website/examples/get-started/flutter-for/web_devs/lib/main.dart",
"repo_id": "website",
"token_count": 5629
} | 1,402 |
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
// The application under test.
import 'package:integration_test_example/main.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('end-to-end test', () {
testWidgets('tap on the floating action button; verify counter',
(tester) async {
app.main();
await tester.pumpAndSettle();
// Finds the floating action button to tap on.
final fab = find.byKey(const Key('increment'));
// Emulate a tap on the floating action button.
await tester.tap(fab);
await tester.pumpAndSettle();
expect(find.text('1'), findsOneWidget);
});
});
}
| website/examples/integration_test/integration_test/counter_test.dart/0 | {
"file_path": "website/examples/integration_test/integration_test/counter_test.dart",
"repo_id": "website",
"token_count": 284
} | 1,403 |
// 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.
// Ignore issues from commonly used lints in this file.
// ignore_for_file:implementation_imports, file_names
// ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering
// ignore_for_file:argument_type_not_assignable, invalid_assignment
// ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases
// ignore_for_file:comment_references
import 'package:intl/intl.dart';
import 'package:intl/message_lookup_by_library.dart';
import 'package:intl/src/intl_helpers.dart';
import 'messages_en.dart' as messages_en;
import 'messages_es.dart' as messages_es;
import 'messages_messages.dart' as messages_messages;
typedef Future<dynamic> LibraryLoader();
Map<String, LibraryLoader> _deferredLibraries = {
'en': () => Future.value(null),
'es': () => Future.value(null),
'messages': () => Future.value(null),
};
MessageLookupByLibrary? _findExact(String localeName) {
switch (localeName) {
case 'en':
return messages_en.messages;
case 'es':
return messages_es.messages;
case 'messages':
return messages_messages.messages;
default:
return null;
}
}
/// User programs should call this before using [localeName] for messages.
Future<bool> initializeMessages(String? localeName) async {
var availableLocale = Intl.verifiedLocale(
localeName, (locale) => _deferredLibraries[locale] != null,
onFailure: (_) => null);
if (availableLocale == null) {
return Future.value(false);
}
var lib = _deferredLibraries[availableLocale];
await (lib == null ? Future.value(false) : lib());
initializeInternalMessageLookup(() => CompositeMessageLookup());
messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor);
return Future.value(true);
}
bool _messagesExistFor(String locale) {
try {
return _findExact(locale) != null;
} catch (e) {
return false;
}
}
MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) {
var actualLocale =
Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null);
if (actualLocale == null) return null;
return _findExact(actualLocale);
}
| website/examples/internationalization/intl_example/lib/l10n/messages_all_locales.dart/0 | {
"file_path": "website/examples/internationalization/intl_example/lib/l10n/messages_all_locales.dart",
"repo_id": "website",
"token_count": 784
} | 1,404 |
// This app doesn't use any Material widgets, such as Scaffold.
// Normally, an app that doesn't use Scaffold has a black background
// and the default text color is black. This app changes its background
// to white and its text color to dark grey to mimic a material app.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
// #docregion MyApp
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(color: Colors.white),
child: const Center(
child: Text(
'Hello World',
textDirection: TextDirection.ltr,
style: TextStyle(
fontSize: 32,
color: Colors.black87,
),
),
),
);
}
}
| website/examples/layout/non_material/lib/main.dart/0 | {
"file_path": "website/examples/layout/non_material/lib/main.dart",
"repo_id": "website",
"token_count": 308
} | 1,405 |
name: architectural_overview
description: Samples for the Flutter architectural overview.
publish_to: none
environment:
sdk: ^3.3.0
dependencies:
flutter:
sdk: flutter
ffi: ^2.1.0
dev_dependencies:
example_utils:
path: ../../example_utils
flutter:
uses-material-design: true
| website/examples/resources/architectural_overview/pubspec.yaml/0 | {
"file_path": "website/examples/resources/architectural_overview/pubspec.yaml",
"repo_id": "website",
"token_count": 110
} | 1,406 |
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import './backend.dart';
void main() {
MyBackend myBackend = MyBackend();
// #docregion Initialize
runZonedGuarded(() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}, (error, stack) {
myBackend.sendError(error, stack);
});
// #enddocregion Initialize
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const Text('hello world!');
}
}
| website/examples/testing/errors/lib/run_zoned_guarded.dart/0 | {
"file_path": "website/examples/testing/errors/lib/run_zoned_guarded.dart",
"repo_id": "website",
"token_count": 219
} | 1,407 |
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class AbsorbKeysExample extends StatelessWidget {
const AbsorbKeysExample({super.key, required this.child});
final Widget child;
// #docregion AbsorbKeysExample
@override
Widget build(BuildContext context) {
return Focus(
onKeyEvent: (node, event) => KeyEventResult.handled,
canRequestFocus: false,
child: child,
);
}
// #enddocregion AbsorbKeysExample
}
class NoAExample extends StatelessWidget {
const NoAExample({super.key});
// #docregion NoAExample
@override
Widget build(BuildContext context) {
return Focus(
onKeyEvent: (node, event) {
return (event.logicalKey == LogicalKeyboardKey.keyA)
? KeyEventResult.handled
: KeyEventResult.ignored;
},
child: const TextField(),
);
}
// #enddocregion NoAExample
}
class BuilderExample extends StatelessWidget {
const BuilderExample({super.key});
// #docregion BuilderExample
@override
Widget build(BuildContext context) {
return Focus(
child: Builder(
builder: (context) {
final bool hasPrimary = Focus.of(context).hasPrimaryFocus;
print('Building with primary focus: $hasPrimary');
return const SizedBox(width: 100, height: 100);
},
),
);
}
// #enddocregion BuilderExample
}
// #docregion OrderedButtonRowExample
class OrderedButtonRow extends StatelessWidget {
const OrderedButtonRow({super.key});
@override
Widget build(BuildContext context) {
return FocusTraversalGroup(
policy: OrderedTraversalPolicy(),
child: Row(
children: <Widget>[
const Spacer(),
FocusTraversalOrder(
order: const NumericFocusOrder(2),
child: TextButton(
child: const Text('ONE'),
onPressed: () {},
),
),
const Spacer(),
FocusTraversalOrder(
order: const NumericFocusOrder(1),
child: TextButton(
child: const Text('TWO'),
onPressed: () {},
),
),
const Spacer(),
FocusTraversalOrder(
order: const NumericFocusOrder(3),
child: TextButton(
child: const Text('THREE'),
onPressed: () {},
),
),
const Spacer(),
],
),
);
}
}
// #enddocregion OrderedButtonRowExample
| website/examples/ui/advanced/focus/lib/samples.dart/0 | {
"file_path": "website/examples/ui/advanced/focus/lib/samples.dart",
"repo_id": "website",
"token_count": 1069
} | 1,408 |
import 'dart:math';
import 'package:flutter/material.dart';
import '../global/device_type.dart';
import '../global/targeted_actions.dart';
import '../widgets/buttons.dart';
class AdaptiveGridPage extends StatefulWidget {
const AdaptiveGridPage({super.key});
@override
State<AdaptiveGridPage> createState() => _AdaptiveGridPageState();
}
class _AdaptiveGridPageState extends State<AdaptiveGridPage> {
final List<int> _listItems = List.generate(100, (index) => index);
final ScrollController _scrollController = ScrollController();
List<int> _selectedItems = [];
@override
Widget build(BuildContext context) {
// Create a list of widgets to render, inject .isSelected into each item
Widget buildGridItem(int index) => _GridItem(index,
isSelected: _selectedItems.contains(index),
onPressed: _handleItemPressed);
List<Widget> listChildren = _listItems.map(buildGridItem).toList();
return TargetedActionBinding(
actions: {
SelectAllIntent:
CallbackAction(onInvoke: (intent) => _handleSelectAllPressed()),
SelectNoneIntent:
CallbackAction(onInvoke: (intent) => _handleSelectNonePressed()),
DeleteIntent: CallbackAction(
onInvoke: (intent) => _handleDeleteSelectedPressed()),
},
child: Column(
children: [
Row(
children: [
StyledTextButton(
onPressed: _handleSelectAllPressed,
child: const Text('Select All'),
),
StyledTextButton(
onPressed: _handleSelectNonePressed,
child: const Text('Select None'),
),
],
),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
// Calculate how many columns we want depending on available space
int colCount = max(1, (constraints.maxWidth / 250).floor());
// #docregion ScrollbarAlwaysShown
return Scrollbar(
thumbVisibility: DeviceType.isDesktop,
controller: _scrollController,
child: GridView.count(
controller: _scrollController,
padding: const EdgeInsets.all(Insets.extraLarge),
childAspectRatio: 1,
crossAxisCount: colCount,
children: listChildren,
),
);
// #enddocregion ScrollbarAlwaysShown
},
),
),
],
),
);
}
void _handleSelectAllPressed() =>
setState(() => _selectedItems = List.from(_listItems));
void _handleSelectNonePressed() => setState(() => _selectedItems.clear());
void _handleDeleteSelectedPressed() => setState(() => _selectedItems.clear());
void _handleItemPressed(int index) {
setState(() {
if (_selectedItems.contains(index)) {
_selectedItems.remove(index);
} else {
_selectedItems.add(index);
}
});
}
}
class _GridItem extends StatelessWidget {
const _GridItem(this.index,
{required this.isSelected, required this.onPressed});
final int index;
final bool isSelected;
final void Function(int index) onPressed;
@override
Widget build(BuildContext context) {
double borderWidth = isSelected ? 6 : 0;
return Padding(
padding: const EdgeInsets.all(Insets.large),
child: TextButton(
onPressed: () => onPressed.call(index),
child: Stack(children: [
const Center(child: FlutterLogo(size: 64)),
Container(color: Colors.grey.withOpacity(isSelected ? .5 : .7)),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity,
color: Colors.grey.shade600,
height: 50,
alignment: Alignment.center,
child: Text('Grid Item $index',
style: const TextStyle(color: Colors.white)))),
// Selected border
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue.shade200, width: borderWidth))),
]),
),
);
}
}
/// Intents to support keyboard shortcuts
class DeleteIntent extends Intent {}
class SelectAllIntent extends Intent {}
class SelectNoneIntent extends Intent {}
| website/examples/ui/layout/adaptive_app_demos/lib/pages/adaptive_grid_page.dart/0 | {
"file_path": "website/examples/ui/layout/adaptive_app_demos/lib/pages/adaptive_grid_page.dart",
"repo_id": "website",
"token_count": 2003
} | 1,409 |
import 'package:flutter/material.dart';
class Product {
const Product({required this.name});
final String name;
}
typedef CartChangedCallback = Function(Product product, bool inCart);
class ShoppingListItem extends StatelessWidget {
ShoppingListItem({
required this.product,
required this.inCart,
required this.onCartChanged,
}) : super(key: ObjectKey(product));
final Product product;
final bool inCart;
final CartChangedCallback onCartChanged;
Color _getColor(BuildContext context) {
// The theme depends on the BuildContext because different
// parts of the tree can have different themes.
// The BuildContext indicates where the build is
// taking place and therefore which theme to use.
return inCart //
? Colors.black54
: Theme.of(context).primaryColor;
}
TextStyle? _getTextStyle(BuildContext context) {
if (!inCart) return null;
return const TextStyle(
color: Colors.black54,
decoration: TextDecoration.lineThrough,
);
}
@override
Widget build(BuildContext context) {
return ListTile(
onTap: () {
onCartChanged(product, inCart);
},
leading: CircleAvatar(
backgroundColor: _getColor(context),
child: Text(product.name[0]),
),
title: Text(product.name, style: _getTextStyle(context)),
);
}
}
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: ShoppingListItem(
product: const Product(name: 'Chips'),
inCart: true,
onCartChanged: (product, inCart) {},
),
),
),
),
);
}
| website/examples/ui/widgets_intro/lib/main_shoppingitem.dart/0 | {
"file_path": "website/examples/ui/widgets_intro/lib/main_shoppingitem.dart",
"repo_id": "website",
"token_count": 623
} | 1,410 |
- title: 'Beginning App Development with Flutter'
authors:
- Rap Payne
publisher: Apress Publishing
cover: beginning-app-development-with-flutter.jpg
link: "https://www.amazon.com/Beginning-App-Development-Flutter-Cross-Platform/dp/1484251806"
desc: "Easy to understand starter book. Currently the best-selling and highest rated Flutter book on Amazon."
- title: 'Beginning Flutter: A Hands On Guide to App Development'
authors:
- Marco L. Napoli
publisher: Wiley Publishing
cover: beginning-flutter.png
link: "https://www.wiley.com/en-us/Beginning+Flutter%3A+A+Hands+On+Guide+to+App+Development-p-9781119550822"
desc: "Build your first app in Flutter - no experience necessary."
- title: 'Flutter Apps Development: Build Cross-Platform Flutter Apps with Trust'
authors:
- Mouaz M. Al-Shahmeh
publisher: Independently published
cover: flutter-apps-development.jpg
link: "https://www.amazon.com/dp/B0C6BSMR7N"
desc: "This book teaches what you need to know to build your first Flutter app. You will learn about the basics of Flutter (widgets, state management, and navigation), as well as how to build a variety of different app types (games, social media apps, and e-commerce apps). By the end of this book, you will be able to build beautiful, high-performance mobile apps using Flutter."
- title: 'Flutter Apprentice'
authors:
- Michael Katz
- Kevin David Moore
- Vincent Ngo
- Vincenzo Guzzi
publisher: Razeware LLC
cover: flutter-apprentice-2nd.png
link: "https://www.raywenderlich.com/books/flutter-apprentice"
desc: "Build for both iOS and Android With Flutter! With Flutter and Flutter Apprentice, you can achieve the dream of building fast applications, faster."
- title: 'Flutter Complete Reference 2.0'
authors:
- Alberto Miola
publisher: Amazon KDP
cover: flutter-complete-reference-2.png
link: "https://fluttercompletereference.com/buy.html"
desc: "The book's first eight chapters are dedicated to Dart 3.0 and all its features. Over 500 pages are about the Flutter framework: widgets basics, state management, animations, navigation, and more."
- title: 'Flutter: Développez vos applications mobiles multiplateformes avec Dart'
authors:
- Julien Trillard
publisher: Editions ENI
cover: flutter-ENI.jpg
link: "https://www.editions-eni.fr/livre/flutter-developpez-vos-applications-mobiles-multiplateformes-avec-dart-9782409025273"
desc: "Ce livre sur Flutter s'adresse aux développeurs, initiés comme plus aguerris, qui souhaitent disposer des connaissances nécessaires pour créer de A à Z des applications mobiles multiplateformes avec le framework de Google"
- title: 'Flutter for Beginners'
authors:
- Thomas Bailey
- Alessandro Biessek
publisher: Packt Publishing
cover: flutter-beginners-2nd.png
link: "https://www.amazon.com/dp/1800565992"
desc: "An introductory guide to building cross-platform mobile applications with Flutter 2.5 and Dart."
- title: 'Flutter in Action'
authors:
- Eric Windmill
publisher: Manning Publishing
cover: flutter-in-action.jpg
link: "https://www.amazon.com/Flutter-Action-Eric-Windmill/dp/1617296147"
desc: "Flutter in Action teaches you to build professional-quality mobile applications using the Flutter SDK and the Dart programming language."
- title: 'Flutter Libraries We Love'
authors:
- Codemagic
publisher: Codemagic
cover: flutter_libraries_we_love.png
link: "https://codemagic.io/flutter-libraries-ebook/"
desc: "\"Flutter libraries We Love\" focuses on 11 different categories of Flutter libraries. Each category lists available libraries as well as a highlighted library that is covered in more detail – including pros and cons, developer's perspective, and real-life code examples. The code snippets of all 11 highlighted libraries support Flutter 2 with sound null safety."
- title: 'Flutter Succinctly'
authors:
- Ed Freitas
publisher: Syncfusion
cover: flutter-succinctly.png
link: "https://www.syncfusion.com/ebooks/flutter-succinctly"
desc: "App UI in Flutter-from Zero to Hero."
- title: 'Google Flutter Mobile Development Quick Start Guide'
authors:
- Prajyot Mainkar
- Salvatore Girodano
publisher: Packt Publishing
cover: google-flutter-mobile-development-quick-start-guide.jpg
link: "https://www.amazon.com/Google-Flutter-Mobile-Development-Quick/dp/1789344964"
desc: "A fast-paced guide to get you started with cross-platform mobile application development with Google Flutter"
- title: 'Learn Google Flutter Fast'
authors:
- Mark Clow
publisher: Self-published
cover: learn-google-flutter-fast.jpg
link: "https://www.amazon.com/Learn-Google-Flutter-Fast-Example/dp/1092297375"
desc: "Learn Google Flutter by example. Over 65 example mini-apps."
- title: 'Managing State in Flutter Pragmatically'
authors:
- Waleed Arshad
publisher: Self-published
cover: managing-state-in-flutter.jpg
link: "https://www.amazon.com/Managing-State-Flutter-Pragmatically-management-dp-1801070776/dp/1801070776"
desc: "Explore popular state management techniques in Flutter."
- title: 'Practical Flutter'
authors:
- Frank Zammetti
publisher: Apress
cover: practical-flutter.jpg
link: "https://www.apress.com/us/book/9781484249710"
desc: "Improve your Mobile Development with Google's latest open source SDK."
- title: 'Pragmatic Flutter'
authors:
- Priyanka Tyagi
publisher: CRC Press
cover: pragmatic-flutter.jpg
link: "https://www.perlego.com/book/2554817/pragmatic-flutter-building-crossplatform-mobile-apps-for-android-ios-web-desktop-pdf"
desc: "Building Cross-Platform Mobile Apps for Android, iOS, Web & Desktop"
- title: 'Programming Flutter'
authors:
- Carmine Zaccagnino
publisher: Pragmatic Bookshelf
cover: programming-flutter.jpg
link: "https://pragprog.com/book/czflutr"
desc: "Native, Cross-Platform Apps the Easy Way. Doesn't require previous Dart knowledge."
- title: 'Flutter Architectures'
authors:
- Atul Vashisht
publisher: Amazon KDP
cover: flutter-architectures-ebook.jpeg
link: "https://www.amazon.com/Flutter-Architectures-Write-code-architecture-ebook/dp/B0CFM8QW1M"
desc: "Write code with a good architecture"
| website/src/_data/books.yml/0 | {
"file_path": "website/src/_data/books.yml",
"repo_id": "website",
"token_count": 1943
} | 1,411 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.